This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git
The following commit(s) were added to refs/heads/geoapi-4.0 by this push:
new e396481ed3 Add `ImageProcessor.aggregate(…)` method for creating
`AggregatedImage`. Enable parallel execution of `AggregatedImage`.
e396481ed3 is described below
commit e396481ed3fac1d20252cc9e814a5f0d2ebfb7f6
Author: Martin Desruisseaux <[email protected]>
AuthorDate: Fri Nov 13 19:23:38 2026 +0100
Add `ImageProcessor.aggregate(…)` method for creating `AggregatedImage`.
Enable parallel execution of `AggregatedImage`.
---
.../main/org/apache/sis/image/AggregatedImage.java | 210 ++++++++++----
.../main/org/apache/sis/image/Aggregation.java | 55 ++++
.../main/org/apache/sis/image/ImageLayout.java | 1 +
.../main/org/apache/sis/image/ImageProcessor.java | 309 ++++++++++++++-------
.../main/org/apache/sis/image/Interpolation.java | 13 +-
.../org/apache/sis/image/MultiSourcePrefetch.java | 4 +-
.../main/org/apache/sis/image/ResampledImage.java | 13 +-
.../sis/image/internal/shared/FillValues.java | 3 +
.../sis/image/internal/shared/TileOpExecutor.java | 13 +-
.../apache/sis/image/processing/TiledProcess.java | 6 +-
.../sis/storage/sql/feature/InfoStatements.java | 5 +-
.../sis/storage/folder/ConcurrentCloser.java | 2 +-
.../main/org/apache/sis/system/CommonExecutor.java | 17 +-
.../main/org/apache/sis/system/Shutdown.java | 2 +
.../apache/sis/gui/internal/BackgroundThreads.java | 2 +-
15 files changed, 482 insertions(+), 173 deletions(-)
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java
index d92a67dea9..db2c1f8257 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java
@@ -19,9 +19,11 @@ package org.apache.sis.image;
import java.util.Map;
import java.util.Vector;
import java.util.Arrays;
-import java.util.Objects;
+import java.util.ArrayList;
import java.util.ConcurrentModificationException;
-import java.util.concurrent.RecursiveTask;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Future;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.ColorModel;
@@ -39,10 +41,10 @@ import
org.apache.sis.image.internal.shared.WritableTiledImage;
import org.apache.sis.image.internal.shared.ImageUtilities;
import org.apache.sis.coverage.grid.PixelInCell;
import org.apache.sis.pending.jdk.JDK18;
+import org.apache.sis.system.CommonExecutor;
import org.apache.sis.util.Exceptions;
import org.apache.sis.util.ArgumentChecks;
import org.apache.sis.util.resources.Errors;
-import org.apache.sis.util.collection.BackingStoreException;
// Specific to the GeoAPI 3.1 and 4.0 branches:
import org.opengis.coverage.grid.SequenceType;
@@ -60,9 +62,9 @@ import org.opengis.coverage.grid.SequenceType;
* when an aggregation method is desired instead of an interpolation method.
* For example, weighted averages are preferred to bilinear interpolations when
* pixel values are proportional to physical energy and the total energy needs
to be preserved.
- * {@code AggregatedImage} can also be used as a fallback when {@code
ResampledImage} fails to
- * resample an image because of a {@link TransformException}.
- * Since these two image classes use {@link MathTransform} in opposite
directions,
+ * {@code AggregatedImage} can also be used as a fallback
+ * when {@code ResampledImage} fails because of a {@link TransformException}.
+ * Since {@code ResampledImage} and {@code AggregatedImage} use {@link
MathTransform} in opposite directions,
* an exception thrown in one direction may be absent in the opposite
direction.</p>
*
* <p>Contrary to {@link ComputedImage}, this image computes all tiles
immediately when one tile is requested.
@@ -140,37 +142,44 @@ public class AggregatedImage extends PlanarImage {
*/
private WritableRaster[] tiles;
+ /**
+ * Whether parallel execution is allowed.
+ * If {@code true}, may threads can be used for aggregating the pixel
values.
+ */
+ protected boolean parallel;
+
/**
* Creates a new image which will aggregate the given images. The
operation requires transforms
* (which can be non-linear) from the specified <em>source</em> images to
<em>this</em> image.
* The transforms shall map {@linkplain PixelInCell#CELL_CORNER pixel
corners}.
*
- * <p>The given {@code sampleModel} determines the tile size and the
target data type.
- * This is often the same sample model as the ones used by the source
images,
- * but may also be different for forcing a different tile size or a
different data type
- * (for example, casting {@code float} values to {@code byte}s).
- * If the specified sample model is not the same as the one used by the
source images,
- * then subclass should override {@link #getColorModel()} for returning a
color model which is
- * {@linkplain ColorModel#isCompatibleSampleModel(SampleModel) compatible
with the sample model}.</p>
- *
* @param sources the images to aggregate with their transforms from
<em>source</em> to <em>this</em>.
- * @param sampleModel the sample model for this aggregated image.
- * @param minTile indices of the first tile ({@code minTileX},
{@code minTileY}), or {@code null} for (0,0).
+ * @param layout preferences about how to derive a sample model for
this aggregated image.
* @param bounds domain of pixel coordinates of this aggregated
image, or {@code null} for automatic.
- * @param fillValues the values to use if the source images provide no
value, or {@code null} for zeros.
+ * @param aggregation the method to use for performing aggregations.
+ * @param fillValues the values to use if the source images have
missing bands, or {@code null} for NaNs.
* @throws TransformException if {@code bounds} is null and an error
occurred while computing automatic bounds.
*/
public AggregatedImage(final Map<RenderedImage, MathTransform> sources,
- final SampleModel sampleModel,
- final Point minTile,
+ final ImageLayout layout,
Rectangle bounds,
- double[] fillValues)
+ final Aggregation aggregation,
+ final Number[] fillValues)
throws TransformException
{
+ ArgumentChecks.ensureNonNull("sources", sources);
+ ArgumentChecks.ensureNonNull("layout", layout);
+ ArgumentChecks.ensureNonNull("aggregation", aggregation); //
Anticipation for a future version.
final int numSources = sources.size();
+ if (numSources == 0) {
+ throw new
IllegalArgumentException(Errors.format(Errors.Keys.EmptyArgument_1, "sources"));
+ }
this.sources = new RenderedImage[numSources];
this.fromSources = new MathTransform[numSources];
- this.sampleModel = Objects.requireNonNull(sampleModel);
+ /*
+ * Store sources and transforms, checking their validity in same time.
+ * Also compute the image bounds if it was not explicitly specified.
+ */
final boolean computeBounds = (bounds == null);
int i = 0, numBands = 0;
for (final var entry : sources.entrySet()) {
@@ -179,7 +188,7 @@ public class AggregatedImage extends PlanarImage {
ArgumentChecks.ensureNonNullElement("sources[#].key", i, source);
ArgumentChecks.ensureNonNullElement("sources[#].value", i,
fromSource);
ArgumentChecks.ensureDimensionsMatch("sources", BIDIMENSIONAL,
BIDIMENSIONAL, fromSource);
- this.fromSources[i] = fromSource;
+ fromSources[i] = fromSource;
this.sources[i++] = source;
numBands = Math.max(numBands, ImageUtilities.getNumBands(source));
if (computeBounds) {
@@ -195,28 +204,33 @@ public class AggregatedImage extends PlanarImage {
if (i != numSources) {
throw new ConcurrentModificationException(); // New entries
added while we were iterating.
}
- minX = bounds.x;
- minY = bounds.y;
+ /*
+ * Store the specified or inferred image bounds.
+ * Use the bounds for inferring a sample model.
+ */
ArgumentChecks.ensureStrictlyPositive("width", width = bounds.width);
ArgumentChecks.ensureStrictlyPositive("height", height =
bounds.height);
+ numChunks = Math.multiplyExact(numChunks(width), numChunks(height));
+ minX = bounds.x;
+ minY = bounds.y;
+ minTileX = layout.preferredMinTileX;
+ minTileY = layout.preferredMinTileY;
+ sampleModel =
layout.createCompatibleSampleModel(this.sources[0], bounds);
effectiveNumBands = Math.min(sampleModel.getNumBands(), numBands);
if (effectiveNumBands >= Integer.MAX_VALUE / (CHUNK_SIZE * CHUNK_SIZE
* NUM_ACCUMULATORS)) {
throw new
RasterFormatException(Errors.format(Errors.Keys.IllegalPropertyValue_2,
"numBands", effectiveNumBands));
}
- if (fillValues == null) {
- fillValues = new double[effectiveNumBands];
- } else {
- fillValues = Arrays.copyOf(fillValues, effectiveNumBands);
- }
- this.fillValues = fillValues;
- numChunks = Math.multiplyExact(numChunks(width), numChunks(height));
- if (minTile != null) {
- minTileX = minTile.x;
- minTileY = minTile.y;
- } else {
- minTileX = 0;
- minTileY = 0;
+ final var values = new double[sampleModel.getNumBands()];
+ Arrays.fill(values, Double.NaN);
+ if (fillValues != null) {
+ for (i = Math.min(values.length, fillValues.length); --i >= 0;) {
+ final Number value = fillValues[i];
+ if (value != null) {
+ values[i] = value.doubleValue();
+ }
+ }
}
+ this.fillValues = values;
}
/**
@@ -357,6 +371,7 @@ public class AggregatedImage extends PlanarImage {
* @throws ImagingOpException if an error occurred while computing the
image.
*/
@Override
+ @SuppressWarnings("UseSpecificCatch")
public synchronized Raster getTile(final int tileX, final int tileY) {
final int numXTiles = getNumXTiles();
final int numYTiles = getNumYTiles();
@@ -365,14 +380,14 @@ public class AggregatedImage extends PlanarImage {
final int chunkCellStride = effectiveNumBands * NUM_ACCUMULATORS;
if (tiles == null) try {
// Execute the aggregation now, possibly using many threads.
- final double[][] data = new SourceScanner().compute();
+ final double[][] data = new SourceScanner().call();
/*
* At this point, the calculatuon of all aggregated values is
completed.
* Dispatch the results in the tiles of this image.
*/
final int chunksPerImageRow = numChunks(width);
final var bounds = new Rectangle(CHUNK_SIZE, CHUNK_SIZE);
- final var samples = new double[effectiveNumBands];
+ final double[] samples = fillValues.clone();
final var writable = new WritableTiledImage(
null, // Properties, not needed for dispatching
values.
null, // Color model, not needed for dispatching
values.
@@ -384,6 +399,7 @@ public class AggregatedImage extends PlanarImage {
for (int i=0; i<data.length; i++) {
final double[] tileData = data[i];
if (tileData != null) {
+ data[i] = null;
bounds.y = (i / chunksPerImageRow) * CHUNK_SIZE + minX;
bounds.x = (i % chunksPerImageRow) * CHUNK_SIZE + minY;
try (WritablePixelIterator it = new PixelIterator.Builder()
@@ -399,7 +415,7 @@ public class AggregatedImage extends PlanarImage {
if (it.isBeginningOfNewRow()) {
valueIndex += toNextRow;
}
- for (int j=0; j < samples.length; j++) {
+ for (int j=0; j < effectiveNumBands; j++) {
// The two values counted by
`NUM_ACCUMULATORS`.
final double sum = tileData[valueIndex++];
final double num = tileData[valueIndex++];
@@ -425,24 +441,67 @@ public class AggregatedImage extends PlanarImage {
* However, each {@code SourceScanner} instance can be subdivided into
other instances
* working on a subset of the images and tiles. Each sub-task can be
executed
* in a different thread and their results combined after task completion.
+ *
+ * <p><b>Design note:</b>
+ * We do not use {@link java.util.concurrent.RecursiveTask} because the
latter is designed
+ * for a lot of small tasks, while we use a few large and potentially I/O
bounded tasks.
+ * Each task may create a lot of temporary arrays which need to be merged
afterward,
+ * therefore it is not necessarily advantageous to create a lot of
tasks.</p>
*/
- @SuppressWarnings("serial") // Not intended to be serialized.
- private final class SourceScanner extends RecursiveTask<double[][]> {
+ private final class SourceScanner implements Callable<double[][]> {
/**
* Index of the next source image to aggregate.
+ * This is initially 0, unless the work has been divided between many
threads.
*/
private int imageIndex;
/**
* Index after the last source image to aggregate.
+ * This is {@code sources.length}, unless the work has been divided
between many threads.
*/
private final int upperImageIndex;
+ /**
+ * Index of the next tile to read in the current image.
+ * This is initially 0, unless the work has been divided between many
threads.
+ */
+ private long srcTileIndex;
+
+ /**
+ * Index after the last source image tile to aggregate, or -1 for
aggregating all remaining tiles.
+ * This is {@code numTileX} × {@code numTileY}, unless the work has
been divided between many threads.
+ * This value is updated every time that {@link #call()} iterates over
a new image.
+ */
+ private long upperTileIndex;
+
+ /**
+ * Number of forks that are allowed. This is 0 if parallel execution
is not enabled.
+ * The number of tasks will be 2ⁿ. Therefore, a value of 3 will create
a maximum of 8 tasks.
+ * We avoid creating too much tasks because each of them brings an
additional cost in arrays
+ * creation and merges.
+ */
+ private byte numAllowedForks;
+
/**
* Creates a new task initialized for aggregating all tiles of all
images.
*/
SourceScanner() {
upperImageIndex = sources.length;
+ upperTileIndex = -1;
+ numAllowedForks = parallel ? (byte) 3 : 0;
+ }
+
+ /**
+ * Creates a new task for aggregating half of the tiles handled by the
given task.
+ * This new task will work on a prefix of the tile collection while
the given task
+ * will work on the suffix.
+ */
+ private SourceScanner(final SourceScanner suffix, final int
upperImageIndex, final long upperTileIndex) {
+ this.imageIndex = suffix.imageIndex;
+ this.upperImageIndex = upperImageIndex;
+ this.srcTileIndex = suffix.srcTileIndex;
+ this.upperTileIndex = upperTileIndex;
+ this.numAllowedForks = --suffix.numAllowedForks;
}
/**
@@ -461,10 +520,28 @@ public class AggregatedImage extends PlanarImage {
* value index with <var>y</var> pixel coordinate varying slowest,
then <var>x</var> pixel coordinate,
* then band index, then accumulator index for a total length of
{@link #accumulatorValuesPerChunk()}.
*
- * @return Result of the aggregation for each tile in the enclosing
target image.
+ * @return result of the aggregation for each tile in the enclosing
target image.
+ * @throws TransformException if an error occurred while transforming
coordinates.
+ * @throws InterruptedException if the current thread was interrupted
while waiting for other threads.
*/
@Override
- protected double[][] compute() {
+ public double[][] call() throws TransformException,
InterruptedException, ExecutionException {
+ /*
+ * If there are many images and we are allowed to fork,
+ * delegates half of the images to a background thread.
+ */
+ final var parallelTasks = new ArrayList<Future<double[][]>>();
+ while (numAllowedForks > 0) {
+ final int half = (upperImageIndex - imageIndex) / 2 +
imageIndex;
+ if (half <= imageIndex) break;
+ parallelTasks.add(CommonExecutor.instance().submit(new
SourceScanner(this, half, -1)));
+ imageIndex = half;
+ }
+ /*
+ * Prepare pixel aggregation on the remaining suffix of the tile
collection.
+ * The code may decide again, inside the loop, to delegate half of
the tiles
+ * to a background thread.
+ */
final double[] imageOffset = {getMinX(), getMinY()};
final double[][] data = new double[numChunks][];
final double[] sourcePixelCorners = new double[BIDIMENSIONAL * 2];
// Bounds of a single source pixel in target coordinates.
@@ -477,16 +554,25 @@ public class AggregatedImage extends PlanarImage {
final int srcMinTileX = source.getMinTileX();
final int srcMinTileY = source.getMinTileY();
final int srcNumTileX = source.getNumXTiles();
- final int srcNumTiles = Math.multiplyExact(srcNumTileX,
source.getNumYTiles());
- for (int srcTileIndex = 0; srcTileIndex < srcNumTiles;
srcTileIndex++) try {
+ if (upperTileIndex < 0) {
+ upperTileIndex = Math.multiplyFull(srcNumTileX,
source.getNumYTiles());
+ }
+ while (numAllowedForks > 0) {
+ // Try to delegate half of the tiles to a background
thread.
+ final long half = (upperTileIndex - srcTileIndex) / 2 +
srcTileIndex;
+ if (half <= srcTileIndex) break;
+ parallelTasks.add(CommonExecutor.instance().submit(new
SourceScanner(this, imageIndex + 1, half)));
+ srcTileIndex = half;
+ }
+ while (srcTileIndex < upperTileIndex) {
/*
* We will iterate over all pixels of a single tile of a
source image.
* For each pixel, the coordinates of the 4 corners will
be transformed
* to coordinates of a bounding box in the target image
(conceptually,
* actual implementation tries to be more efficient).
*/
- final Raster tile = source.getTile(srcMinTileX +
(srcTileIndex % srcNumTileX),
- srcMinTileY +
(srcTileIndex / srcNumTileX));
+ final Raster tile = source.getTile(srcMinTileX + (int)
(srcTileIndex % srcNumTileX),
+ srcMinTileY + (int)
(srcTileIndex / srcNumTileX));
final int numBands = Math.min(tile.getNumBands(),
effectiveNumBands);
final int scanline = tile.getWidth();
final int xmin = tile.getMinX();
@@ -557,11 +643,35 @@ public class AggregatedImage extends PlanarImage {
}
xyBottom = xyTop;
}
- } catch (TransformException e) {
- throw new BackingStoreException(e);
+ // Finished pixel aggregation of one tile of source image.
Move to next tile.
+ srcTileIndex++;
}
+ // Finished pixel aggregation of all tiles of one source
image. Move to next image.
+ srcTileIndex = 0;
+ upperTileIndex = -1;
imageIndex++;
}
+ /*
+ * Merges the data computed by other threads with the data
computed by this thread.
+ * The loop is executed only if parallel computation was enabled.
+ */
+ for (final Future<double[][]> fork : parallelTasks) {
+ final double[][] other = fork.get();
+ for (int i=0; i<other.length; i++) {
+ final double[] otherTile = other[i];
+ if (otherTile != null) {
+ other[i] = null;
+ final double[] tileData = data[i];
+ if (tileData == null) {
+ data[i] = otherTile;
+ } else {
+ for (int j = otherTile.length; --j >= 0;) {
+ tileData[j] += otherTile[j];
+ }
+ }
+ }
+ }
+ }
return data;
}
}
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Aggregation.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Aggregation.java
new file mode 100644
index 0000000000..0963721981
--- /dev/null
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Aggregation.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.image;
+
+
+/**
+ * Algorithm for image resampling based on aggregation methods.
+ * Aggregating is the action of computing the pixel values of an image
+ * from the values of overlapping pixels in one or many source images.
+ * The aggregation is performed by the {@link AggregatedImage} class.
+ *
+ * @author Martin Desruisseaux (Geomatys)
+ * @version 1.8
+ *
+ * @see AggregatedImage
+ * @see Interpolation
+ *
+ * @since SIS 1.8
+ */
+public class Aggregation {
+ /**
+ * Creates a new aggregation method.
+ */
+ Aggregation() {
+ }
+
+ /**
+ * Aggregation calculated by averages of pixel values with raster-space
weighting.
+ * For each pixel in the aggregated image, the value is computed by the
average of all
+ * overlapping pixels in source images weighted by the area of overlap in
pixel units.
+ */
+ public static final Aggregation RASTER_SPACE_WEIGHTING = new Aggregation();
+
+ /*
+ * Aggregation calculated by averages of pixel values with real world
weighting.
+ * For each pixel in the aggregated image, the value is computed by the
average of all
+ * overlapping pixels in source images weighted by the surface area of
pixel footprint
+ * on the ground, typically in square meters.
+ */
+// private static final Aggregation GROUND_AREA_WEIGHTING = new Aggregation();
+}
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageLayout.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageLayout.java
index 62c6fec269..96fc9f56c2 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageLayout.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageLayout.java
@@ -56,6 +56,7 @@ import org.apache.sis.feature.internal.Resources;
*
* @author Martin Desruisseaux (Geomatys)
* @version 1.7
+ *
* @since SIS 1.5
*/
public class ImageLayout {
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageProcessor.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageProcessor.java
index 9dd051cf82..6b5ecad65d 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageProcessor.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageProcessor.java
@@ -52,6 +52,7 @@ import org.apache.sis.math.Statistics;
import org.apache.sis.util.ArraysExt;
import org.apache.sis.util.ArgumentChecks;
import org.apache.sis.util.resources.Errors;
+import org.apache.sis.util.collection.Containers;
import org.apache.sis.util.collection.WeakHashSet;
import org.apache.sis.system.Modules;
import org.apache.sis.image.processing.isoline.Isolines;
@@ -71,6 +72,8 @@ import org.apache.sis.measure.Units;
* </li><li>
* {@linkplain #setInterpolation(Interpolation) Interpolation method} to
use during resampling operations.
* </li><li>
+ * {@linkplain #setAggregation(Aggregation) Aggregation method} to use
during aggregate operations.
+ * </li><li>
* {@linkplain #setFillValues(Number...) Fill values} to use for pixels
that cannot be computed.
* </li><li>
* {@linkplain #setColorizer(Colorizer) Colorization algorithm} to apply
for colorizing a computed image.
@@ -82,8 +85,8 @@ import org.apache.sis.measure.Units;
* {@link RenderedImage} implementations are executed sequentially in the
caller thread, for safety reasons.
* Some operations can be parallelized, but it should be enabled only if
the {@link RenderedImage} is known
* to be thread-safe and has concurrent (or fast) implementation of {@link
RenderedImage#getTile(int, int)}.
- * Apache SIS implementations of {@link RenderedImage} can be
parallelized, but it may not be the case of
- * images from other libraries.
+ * Apache <abbr>SIS</abbr> implementations of {@link RenderedImage} can be
parallelized,
+ * but it may not be the case of images from other libraries.
* </li><li>
* Whether the operations should fail if an exception is thrown while
processing a tile.
* By default errors during calculation are propagated as an {@link
ImagingOpException},
@@ -93,30 +96,32 @@ import org.apache.sis.measure.Units;
* </ul>
*
* For each image operations, above properties are combined with parameters
given to the operation method.
- * Each method in this {@code ImageProcessor} class documents the properties
used in addition of method parameters.
- *
- * <h2>API design</h2>
* Properties (setter methods) are used for values that can be applied
unchanged on many different images.
* For example, the {@linkplain #getInterpolation() interpolation method} can
be specified once and used
* unchanged for many {@link #resample resample(…)} operations.
* On the other hand, method arguments are used for values that are usually
specific to the image to process.
* For example, the {@link MathTransform} argument given to the {@link
#resample resample(…)} operation depends
- * tightly on the source image and destination bounds (also given in
arguments); those information usually need
- * to be recomputed for each image.
+ * tightly on the source image and destination bounds (also given in
arguments),
+ * and those information usually need to be different for each image.
+ * Each method in this {@code ImageProcessor} class documents the properties
used in addition of method parameters.
*
- * <h2>Deferred calculations</h2>
+ * <p>{@code ImageProcessor} is safe for concurrent use in multi-threading
environment.
+ * However since {@code ImageProcessor} instances are mutable, users should
consider to
+ * {@linkplain #clone() clone} if setter methods are invoked on a shared
instance.</p>
+ *
+ * <h2>Deferred tile calculations in computed images</h2>
* Methods in this class may compute the result at some later time after the
method returned, instead of computing
* the result immediately on method call. Consequently, unless otherwise
specified, {@link RenderedImage} arguments
* should be <em>stable</em>, i.e. pixel values should not be modified after
method return.
*
- * <h2>Area of interest</h2>
+ * <h2>Area Of Interest (<abbr>AOI</abbr>) for image operations</h2>
* Some operations accept an optional <var>area of interest</var> argument
specified as a {@link Shape} instance in
* pixel coordinates. If a shape is given, it should not be modified after
{@code ImageProcessor} method call because
* the given object may be retained directly (i.e. the {@code Shape} is not
always cloned; it depends on its class).
* In addition, the {@code Shape} implementation shall be thread-safe
(assuming its state stay unmodified)
* unless the execution mode is set to {@link Mode#PARALLEL}.
*
- * <h2>Error handling</h2>
+ * <h2>Error handling after failure to compute a tile</h2>
* If an exception occurs during the computation of a tile, then the {@code
ImageProcessor} behavior
* is controlled by the {@link #getErrorHandler() errorHandler} property:
*
@@ -129,14 +134,9 @@ import org.apache.sis.measure.Units;
* In both cases a partial result is returned.</li>
* </ul>
*
- * <h2>Thread-safety</h2>
- * {@code ImageProcessor} is safe for concurrent use in multi-threading
environment.
- * Note however that {@code ImageProcessor} instances are mutable;
- * consider {@linkplain #clone() cloning} if setter methods are invoked on a
shared instance.
- *
* @author Martin Desruisseaux (Geomatys)
* @author Alexis Manin (Geomatys)
- * @version 1.7
+ * @version 1.8
*
* @see org.apache.sis.coverage.grid.GridCoverageProcessor
*
@@ -169,13 +169,21 @@ public class ImageProcessor implements Cloneable {
private ImageLayout layout;
/**
- * Interpolation to use during resample operations.
+ * Interpolation method to use during resample operations.
*
* @see #getInterpolation()
* @see #setInterpolation(Interpolation)
*/
private Interpolation interpolation;
+ /**
+ * Aggregation method to use during resample operations.
+ *
+ * @see #getAggregation()
+ * @see #setAggregation(Aggregation)
+ */
+ private Aggregation aggregation;
+
/**
* The values to use for pixels that cannot be computed.
* This array may be {@code null} or may contain {@code null} elements.
@@ -265,6 +273,7 @@ public class ImageProcessor implements Cloneable {
executionMode = Mode.DEFAULT;
errorHandler = ErrorHandler.THROW;
interpolation = Interpolation.BILINEAR;
+ aggregation = Aggregation.RASTER_SPACE_WEIGHTING;
}
/**
@@ -311,6 +320,30 @@ public class ImageProcessor implements Cloneable {
interpolation = Objects.requireNonNull(method);
}
+ /**
+ * Returns the aggregation method to use during aggregate operations.
+ *
+ * @return aggregation method to use during aggregate operations.
+ *
+ * @see #aggregate(RenderedImage, Rectangle, MathTransform)
+ * @since SIS 1.8
+ */
+ public synchronized Aggregation getAggregation() {
+ return aggregation;
+ }
+
+ /**
+ * Sets the aggregation method to use during aggregate operations.
+ *
+ * @param method aggregate method to use during aggregate operations.
+ *
+ * @see #aggregate(RenderedImage, Rectangle, MathTransform)
+ * @since SIS 1.8
+ */
+ public synchronized void setAggregation(final Aggregation method) {
+ aggregation = Objects.requireNonNull(method);
+ }
+
/**
* Returns the values to use for pixels that cannot be computed.
* This method returns a copy of the array set by the last call to {@link
#setFillValues(Number...)}.
@@ -351,12 +384,11 @@ public class ImageProcessor implements Cloneable {
* The colorizer is invoked when the rendered image produced by an {@code
ImageProcessor} operation
* needs a {@link ColorModel} which is not straightforward.
*
- * <h4>Examples</h4>
- * <p>The color model of a {@link #resample(RenderedImage, Rectangle,
MathTransform) resample(…)}
+ * <p><b>Examples:</b>
+ * The color model of a {@link #resample(RenderedImage, Rectangle,
MathTransform) resample(…)}
* operation is straightforward: it is the same {@link ColorModel} than
the source image.
- * Consequently the colorizer is not invoked for that operation.</p>
- *
- * <p>But by contrast, the color model of an {@link
#aggregateBands(RenderedImage...) aggregateBands(…)}
+ * Consequently the colorizer is not invoked for that operation.
+ * But by contrast, the color model of an {@link
#aggregateBands(RenderedImage...) aggregateBands(…)}
* operation cannot be determined in such straightforward way.
* If three or four bands are aggregated, should they be interpreted as an
(A)RGB image?
* The {@link Colorizer} allows to specify the desired behavior.</p>
@@ -454,7 +486,7 @@ public class ImageProcessor implements Cloneable {
case PARALLEL: return true;
case SEQUENTIAL: return false;
default: {
- if (source instanceof BufferedImage) {
+ if (source == null || source instanceof BufferedImage) {
return true;
}
return
source.getClass().getName().startsWith(Modules.CLASSNAME_PREFIX);
@@ -480,11 +512,11 @@ public class ImageProcessor implements Cloneable {
* {@link LogRecord} instead, in which case a partial result may be
available.
* Only one log record is created for all tiles that failed for the same
operation on the same image.
*
- * <h4>Limitations</h4>
+ * <p><b>Limitations:</b>
* In current {@code ImageProcessor} implementation, the error handler is
not honored by all operations.
* Some operations may continue to throw an exception on failure (the
behavior of default error handler)
* even if a different handler has been specified.
- * Each operation specifies in its Javadoc whether the operation uses
error handler or not.
+ * Each operation specifies in its Javadoc whether the operation uses
error handler or not.</p>
*
* @param handler handler to notify when an operation failed on one or
more tiles,
* or {@link ErrorHandler#THROW} for propagating the
exception.
@@ -508,11 +540,11 @@ public class ImageProcessor implements Cloneable {
* if the <var>x</var> value is equal to one of the given no-data {@code
values},
* and will return <var>x</var> unchanged otherwise.
*
- * <h4>Usage</h4>
+ * <p><b>Usage:</b>
* This operator can be used as a {@code sampleFilters} argument in calls
to
* {@link #statistics statistics(…)} or {@link #valueOfStatistics
valueOfStatistics(…)} methods.
* It is redundant with {@linkplain SampleDimension#getTransferFunction()
transfer function} work,
- * but can be useful for images not managed by a {@link
org.apache.sis.coverage.grid.GridCoverage}.
+ * but can be useful for images not managed by a {@link
org.apache.sis.coverage.grid.GridCoverage}.</p>
*
* @param values the "no data" values, or {@code null} if none. Null and
NaN elements are ignored.
* @return an operator for filtering the given "no data" values,
@@ -543,22 +575,20 @@ public class ImageProcessor implements Cloneable {
* <li>Otherwise statistics are computed for the whole image.</li>
* </ul>
*
- * <h4>Sample converters</h4>
- * An arbitrary {@link DoubleUnaryOperator} can be applied on sample
values before to add them to statistics.
+ * <p>An arbitrary {@link DoubleUnaryOperator} can be applied on sample
values before to add them to statistics.
* The main purpose is to replace "no-data values" by {@link Double#NaN}
values for instructing
* {@link Statistics#accept(double)} to ignore them. The {@link
#filterNodataValues(Number...)}
- * convenience method can be used for building an operator filtering "no
data" sample values.
+ * convenience method can be used for building an operator filtering "no
data" sample values.</p>
*
- * <h4>Properties used</h4>
- * This operation uses the following properties in addition to method
parameters:
+ * <p>This operation uses the following properties in addition to method
parameters:</p>
* <ul>
* <li>{@linkplain #getExecutionMode() Execution mode} (parallel or
sequential).</li>
* <li>{@linkplain #getErrorHandler() Error handler} (custom action
executed if an exception is thrown).</li>
* </ul>
*
- * <h4>Result relationship with source</h4>
+ * <p><b>Result relationship with source:</b>
* This method fetches (from property values) or computes statistics
immediately.
- * Changes in the {@code source} image after this method call do not
change the results.
+ * Changes in the {@code source} image after this method call do not
change the results.</p>
*
* @param source the image for which to compute statistics.
* @param areaOfInterest pixel coordinates of the area of interest, or
{@code null} for the default.
@@ -643,23 +673,21 @@ public class ImageProcessor implements Cloneable {
* is returned.</li>
* </ul>
*
- * <h4>Sample converters</h4>
- * An arbitrary {@link DoubleUnaryOperator} can be applied on sample
values before to add them to statistics.
+ * <p>An arbitrary {@link DoubleUnaryOperator} can be applied on sample
values before to add them to statistics.
* The main purpose is to replace "no-data values" by {@link Double#NaN}
values for instructing
* {@link Statistics#accept(double)} to ignore them. The {@link
#filterNodataValues(Number...)}
- * convenience method can be used for building an operator filtering "no
data" sample values.
+ * convenience method can be used for building an operator filtering "no
data" sample values.</p>
*
- * <h5>API design note</h5>
+ * <p><b>API design note:</b>
* The {@code areaOfInterest} and {@code sampleFilters} arguments are
complementary.
* Both of them filter the data accepted for statistics. In ISO 19123
terminology,
* the {@code areaOfInterest} argument filters the <i>coverage domain</i>
while
* the {@code sampleFilters} argument filters the <i>coverage range</i>.
* Another connection with OGC/ISO standards is that {@link
DoubleUnaryOperator} in this context
* does the same work as {@linkplain SampleDimension#getTransferFunction()
transfer function}.
- * It can be useful for images not managed by a {@link
org.apache.sis.coverage.grid.GridCoverage}.
+ * It can be useful for images not managed by a {@link
org.apache.sis.coverage.grid.GridCoverage}.</p>
*
- * <h4>Properties used</h4>
- * This operation uses the following properties in addition to method
parameters:
+ * <p>This operation uses the following properties in addition to method
parameters:</p>
* <ul>
* <li>{@linkplain #getExecutionMode() Execution mode} (parallel or
sequential).</li>
* <li>{@linkplain #getErrorHandler() Error handler} (whether to fail if
an exception is thrown).</li>
@@ -760,16 +788,15 @@ public class ImageProcessor implements Cloneable {
* value will be the {@value PlanarImage#SAMPLE_DIMENSIONS_KEY} image
property value if defined.
* That value can be an array, in which case the sample dimension of the
visible band is taken.
*
- * <h4>Properties used</h4>
- * This operation uses the following properties in addition to method
parameters:
+ * <p>This operation uses the following properties in addition to method
parameters:</p>
* <ul>
* <li>(none)</li>
* </ul>
*
- * <h4>Limitation</h4>
+ * <p><b>Limitation:</b>
* Current implementation can stretch only gray scale images (a future
version may extend support to images
* using {@linkplain java.awt.image.IndexColorModel index color models}).
If this method cannot stretch the
- * color ramp, for example because the given image is an RGB image, then
the image is returned unchanged.
+ * color ramp, for example because the given image is an RGB image, then
the image is returned unchanged.</p>
*
* @param source the image to recolor.
* @param modifiers modifiers for narrowing the range of values, or
{@code null} if none.
@@ -833,8 +860,7 @@ public class ImageProcessor implements Cloneable {
* then the returned image will also be a {@link WritableRenderedImage}.
* In such case values written in the returned image will be written
directly in the source image.</p>
*
- * <h4>Properties used</h4>
- * This operation uses the following properties in addition to method
parameters:
+ * <p>This operation uses the following properties in addition to method
parameters:</p>
* <ul>
* <li>(none)</li>
* </ul>
@@ -882,30 +908,29 @@ public class ImageProcessor implements Cloneable {
* An empty array element (i.e. zero band to select) discards the
corresponding source image.
* In the latter case, the discarded element in the {@code sources} array
may be {@code null}.
*
- * <h4>Restrictions</h4>
+ * <p><b>Restrictions:</b>
* All images shall use the same {@linkplain SampleModel#getDataType()
data type},
* and all source images shall intersect each other with a non-empty
intersection area.
- * However it is not required that all images have the same bounds or the
same tiling scheme.
+ * However it is not required that all images have the same bounds or the
same tiling scheme.</p>
*
- * <h4>Writable image</h4>
+ * <p><b>Writable image:</b>
* If all source images are {@link WritableRenderedImage} instances,
* then the returned image will also be a {@link WritableRenderedImage}.
* In such case values written in the returned image will be copied back
- * to the source images.
+ * to the source images.</p>
*
- * <h4>Memory saving</h4>
+ * <p><b>Memory saving:</b>
* The returned image may opportunistically share the underlying data
arrays of
* some source images. Bands are really copied only when sharing is not
possible.
- * The actual strategy may be a mix of both arrays sharing and bands
copies.
+ * The actual strategy may be a mix of both arrays sharing and bands
copies.</p>
*
- * <h4>Repeated bands</h4>
+ * <p><b>Repeated bands:</b>
* For any value of <var>i</var>, the array at {@code bandsPerSource[i]}
shall not contain duplicated values.
* This restriction is for capturing common errors, in order to reduce the
risk of accidental band repetition.
* However the same band can be repeated indirectly if the same image is
repeated at different values of <var>i</var>.
- * But even when a source band is referenced many times, all occurrences
still share pixel data copied at most once.
+ * But even when a source band is referenced many times, all occurrences
still share pixel data copied at most once.</p>
*
- * <h4>Properties used</h4>
- * This operation uses the following properties in addition to method
parameters:
+ * <p>This operation uses the following properties in addition to method
parameters:</p>
* <ul>
* <li>{@linkplain #getColorizer() Colorizer}.</li>
* <li>{@linkplain #getExecutionMode() Execution mode} (parallel or
sequential).</li>
@@ -943,17 +968,16 @@ public class ImageProcessor implements Cloneable {
* that some sources will never be drawn (i.e., are fully hidden behind
the first images).
* If only one source appears to be effectively used, this method returns
that image directly.</p>
*
- * <h4>Optimization</h4>
+ * <p><b>Optimization:</b>
* The returned image may share some tiles from any source images (without
copy)
- * if the tile can be used directly with no change.
+ * if the tile can be used directly with no change.</p>
*
* <p><b>Preconditions:</b>
* All source images shall have the same number of bands (but not
necessarily the same sample model).
* All source images should have equivalent color model, otherwise color
consistency is not guaranteed.
* At least one image shall intersect the given bounds.</p>
*
- * <h4>Properties used</h4>
- * This operation uses the following properties in addition to method
parameters:
+ * <p>This operation uses the following properties in addition to method
parameters:</p>
* <ul>
* <li>{@linkplain #getImageLayout() Image layout} for the desired
sample model and color model.</li>
* <li>{@linkplain ImageLayout#isImageBoundsAdjustmentAllowed Image
bounds adjustment flag} for deciding
@@ -997,8 +1021,7 @@ public class ImageProcessor implements Cloneable {
* <p><b>Precondition:</b>
* The new sample model shall have the same number of bands as in the
given image.</p>
*
- * <h4>Properties used</h4>
- * This operation uses the following properties in addition to method
parameters:
+ * <p>This operation uses the following properties in addition to method
parameters:</p>
* <ul>
* <li>{@linkplain #getImageLayout() Image layout} for the default
sample model.</li>
* <li>{@linkplain ImageLayout#isImageBoundsAdjustmentAllowed Image
bounds adjustment flag} for deciding
@@ -1019,7 +1042,7 @@ public class ImageProcessor implements Cloneable {
final boolean parallel;
synchronized (this) {
layout = this.layout;
- parallel = executionMode != Mode.SEQUENTIAL;
+ parallel = parallel(source);
}
if (sampleModel == null) {
sampleModel = layout.sampleModel;
@@ -1034,8 +1057,7 @@ public class ImageProcessor implements Cloneable {
* If {@code maskInside} is {@code false}, then the mask is reversed:
* the pixels set to fill values are the ones outside the shape.
*
- * <h4>Properties used</h4>
- * This operation uses the following properties in addition to method
parameters:
+ * <p>This operation uses the following properties in addition to method
parameters:</p>
* <ul>
* <li>{@linkplain #getFillValues() Fill values} values to assign to
pixels inside/outside the shape.</li>
* </ul>
@@ -1082,15 +1104,14 @@ public class ImageProcessor implements Cloneable {
* and extraneous elements are ignored. Those ranges do not need to
encompass all possible values;
* it is sufficient to provide only typical or "most interesting"
ranges.</p>
*
- * <h4>Properties used</h4>
- * This operation uses the following properties in addition to method
parameters:
+ * <p>This operation uses the following properties in addition to method
parameters:</p>
* <ul>
* <li>{@linkplain #getColorizer() Colorizer} for customizing the
rendered image color model.</li>
* </ul>
*
- * <h4>Result relationship with source</h4>
+ * <p><b>Result relationship with source:</b>
* Changes in the source image are reflected in the returned image
- * if the source image notifies {@linkplain java.awt.image.TileObserver
tile observers}.
+ * if the source image notifies {@linkplain java.awt.image.TileObserver
tile observers}.</p>
*
* @param source the image for which to convert sample values.
* @param sourceRanges approximate ranges of values for each band in
source image, or {@code null} if unknown.
@@ -1127,16 +1148,18 @@ public class ImageProcessor implements Cloneable {
/**
* Verifies that the given rectangle is non-empty.
* This method assumes that the argument name is "bounds".
+ * Null argument is accepted because the bounds can be optional for some
operations.
*/
private static void ensureNonEmpty(final Rectangle bounds) {
- if (bounds.isEmpty()) {
+ if (bounds != null && bounds.isEmpty()) {
throw new
IllegalArgumentException(Errors.format(Errors.Keys.EmptyArgument_1, "bounds"));
}
}
/**
- * Creates a new image which will resample the given image. The resampling
operation is defined
- * by a potentially non-linear transform from the <em>new</em> image to
the specified <em>source</em> image.
+ * Creates a new image which will resample the given image.
+ * The resampling operation is defined by a potentially non-linear
transform
+ * of pixel coordinates from the <em>new</em> image to the specified
<em>source</em> image.
* That transform should map {@linkplain
org.apache.sis.coverage.grid.PixelInCell#CELL_CENTER pixel centers}.
* If that transform produces coordinates that are outside source envelope
bounds, then the corresponding pixels
* in the new image are set to {@linkplain #getFillValues() fill values}.
Otherwise sample values are interpolated
@@ -1146,8 +1169,7 @@ public class ImageProcessor implements Cloneable {
* then this method will use {@linkplain PlanarImage#getSources() the
source} of the given source.
* The intent is to avoid resampling a resampled image; instead this
method works on the original data.</p>
*
- * <h4>Properties used</h4>
- * This operation uses the following properties in addition to method
parameters:
+ * <p>This operation uses the following properties in addition to method
parameters:</p>
* <ul>
* <li>{@linkplain #getInterpolation() Interpolation method} (nearest
neighbor, bilinear, <i>etc</i>).</li>
* <li>{@linkplain #getFillValues() Fill values} for pixels outside
source image.</li>
@@ -1157,9 +1179,9 @@ public class ImageProcessor implements Cloneable {
* for enabling faster resampling at the cost of lower
precision.</li>
* </ul>
*
- * <h4>Result relationship with source</h4>
+ * <p><b>Result relationship with source:</b>
* Changes in the source image are reflected in the returned images
- * if the source image notifies {@linkplain java.awt.image.TileObserver
tile observers}.
+ * if the source image notifies {@linkplain java.awt.image.TileObserver
tile observers}.</p>
*
* @param source the image to be resampled.
* @param bounds domain of pixel coordinates of resampled image to
create. Fields are updated in-place
@@ -1180,8 +1202,10 @@ public class ImageProcessor implements Cloneable {
boolean isIdentity = toSource.isIdentity();
RenderedImage resampled = null;
for (;;) {
- if (isIdentity && bounds.x == source.getMinX() && bounds.y ==
source.getMinY() &&
- bounds.width == source.getWidth() && bounds.height ==
source.getHeight())
+ if (isIdentity && bounds.x == source.getMinX()
+ && bounds.y == source.getMinY()
+ && bounds.width == source.getWidth()
+ && bounds.height == source.getHeight())
{
resampled = source;
break;
@@ -1234,6 +1258,96 @@ public class ImageProcessor implements Cloneable {
return RecoloredImage.applySameColors(resampled, colored);
}
+ /**
+ * Creates a new image which will aggregate the pixel values of the given
image.
+ * The aggregating operation is defined by a potentially non-linear
transform
+ * of pixel coordinates from the specified <em>source</em> image to the
<em>new</em> image.
+ * That transform should map {@linkplain
org.apache.sis.coverage.grid.PixelInCell#CELL_CORNER pixel corners}.
+ *
+ * <p>This operation can be used as an alternative to
+ * {@link #resample(RenderedImage, Rectangle, MathTransform) resample(…)}
+ * when an aggregation method is desired instead of an interpolation
method.
+ * For example, weighted averages are preferred to bilinear interpolations
when
+ * pixel values are proportional to physical energy and the total energy
needs to be preserved.
+ * This operation can also be used as a fallback
+ * when {@code resample(…)} fails because of a {@link TransformException}.
+ * Since {@code resample(…)} and {@code aggregate(…)} use {@link
MathTransform} in opposite directions,
+ * an exception thrown in one direction may be absent in the opposite
direction.</p>
+ *
+ * <p>Contrary to {@code resample(…)} , this operation computes all tiles
immediately when one tile is requested.
+ * For very large images, {@link #resample(RenderedImage, Rectangle,
MathTransform) resample(…)} is preferred
+ * because it defers computation on a tile-by-tile basis instead of
computing the whole image.</p>
+ *
+ * <p>This operation uses the following properties in addition to method
parameters:</p>
+ * <ul>
+ * <li>{@linkplain #getAggregation() Aggregation method} (weighted
average, <i>etc</i>).</li>
+ * <li>{@linkplain #getFillValues() Fill values} for missing bands in
source images.</li>
+ * <li>{@linkplain #getImageLayout() Image layout} for inferring a
sample model.</li>
+ * <li>{@linkplain #getExecutionMode() Execution mode} (parallel or
sequential).</li>
+ * </ul>
+ *
+ * @param source the image to be resampled.
+ * @param bounds domain of pixel coordinates of the aggregated
image, or {@code null} for automatic.
+ * @param fromSource conversion of pixel corner coordinates from {@code
source} image to aggregated image.
+ * @return aggregation of pixel values of the given source image.
+ *
+ * @since SIS 1.8
+ */
+ public RenderedImage aggregate(final RenderedImage source, final Rectangle
bounds, final MathTransform fromSource) {
+ ArgumentChecks.ensureNonNull("source", source);
+ ArgumentChecks.ensureNonNull("fromSource", fromSource);
+ return aggregate(Map.of(source, fromSource), bounds);
+ }
+
+ /**
+ * Creates a new image which will aggregate the pixel values of the given
images.
+ * Aggregating is the action of computing the pixel values of an image
from the
+ * values of overlapping pixels in one or many source images.
+ * The aggregation can be performed by statistic methods such as weighted
average.
+ * Each source image is associated with a potentially non-linear transform
of
+ * pixel coordinates from the <em>source</em> image to the <em>new</em>
image.
+ * These transforms should map {@linkplain
org.apache.sis.coverage.grid.PixelInCell#CELL_CORNER pixel corners}.
+ *
+ * <p>This operation uses the following properties in addition to method
parameters:</p>
+ * <ul>
+ * <li>{@linkplain #getAggregation() Aggregation method} (weighted
average, <i>etc</i>).</li>
+ * <li>{@linkplain #getFillValues() Fill values} for missing bands in
source images.</li>
+ * <li>{@linkplain #getImageLayout() Image layout} for inferring a
sample model.</li>
+ * <li>{@linkplain #getExecutionMode() Execution mode} (parallel or
sequential).</li>
+ * </ul>
+ *
+ * @param sources the images to aggregate with their transforms from
<em>source</em> to <em>new</em> image.
+ * @param bounds domain of pixel coordinates of the aggregated image,
or {@code null} for automatic.
+ * @return aggregation of pixel values of all given source images.
+ *
+ * @since SIS 1.8
+ */
+ @SuppressWarnings("LocalVariableHidesMemberVariable")
+ public RenderedImage aggregate(final Map<RenderedImage, MathTransform>
sources, final Rectangle bounds) {
+ ArgumentChecks.ensureNonNull("sources", sources);
+ final RenderedImage source = Containers.peekFirst(sources.keySet());
+ ensureNonEmpty(bounds);
+ final ImageLayout layout;
+ final Aggregation aggregation;
+ final Number[] fillValues;
+ final boolean parallel;
+ synchronized (this) {
+ layout = this.layout;
+ aggregation = this.aggregation;
+ fillValues = this.fillValues;
+ parallel = parallel(source);
+ }
+ final AggregatedImage image;
+ try {
+ image = new AggregatedImage(sources, layout, bounds, aggregation,
fillValues);
+ } catch (TransformException e) {
+ throw (ImagingOpException) new
ImagingOpException(null).initCause(e);
+ }
+ image.parallel = parallel;
+ // We do not invoke `unique(…)` because `equals/hashCode` are not
implemented yet.
+ return image;
+ }
+
/**
* Creates an overview of the given image computed by the average of 4
pixels.
* NaN values are omitted from the average. If all values in a block of 4
pixels are NaN,
@@ -1252,9 +1366,9 @@ public class ImageProcessor implements Cloneable {
* └ ┘
* }
*
- * <h4>Result relationship with source</h4>
+ * <p><b>Result relationship with source:</b>
* Changes in the source image are reflected in the returned images
- * if the source image notifies {@linkplain java.awt.image.TileObserver
tile observers}.
+ * if the source image notifies {@linkplain java.awt.image.TileObserver
tile observers}.</p>
*
* @param source the image for which to compute an overview.
* @return image overview.
@@ -1270,8 +1384,7 @@ public class ImageProcessor implements Cloneable {
* Computes immediately all tiles in the given region of interest, then
returns an image with those tiles ready.
* Computations will use many threads if {@linkplain #getExecutionMode()
execution mode} is parallel.
*
- * <h4>Properties used</h4>
- * This operation uses the following properties in addition to method
parameters:
+ * <p>This operation uses the following properties in addition to method
parameters:</p>
* <ul>
* <li>{@linkplain #getExecutionMode() Execution mode} (parallel or
sequential).</li>
* <li>{@linkplain #getErrorHandler() Error handler} (whether to fail if
an exception is thrown).</li>
@@ -1310,7 +1423,7 @@ public class ImageProcessor implements Cloneable {
* There is no guarantee about the number of bands in returned image or
about which formula is used for converting
* floating point values to integer values.</p>
*
- * <h4>How to specify colors</h4>
+ * <h4>How to specify image colors</h4>
* The image colors can be controlled by the {@link Colorizer} set on this
image processor.
* It is possible to {@linkplain Colorizer#forInstance(ColorModel) specify
explicitly} the
* {@link ColorModel} to use, but this approach is unsafe because it
depends on the pixel values
@@ -1372,8 +1485,7 @@ public class ImageProcessor implements Cloneable {
* The {@link Color} arrays may have any length; colors will be
interpolated as needed for fitting
* the ranges of values in the destination image.
*
- * <h4>Properties used</h4>
- * This operation uses the following properties in addition to method
parameters:
+ * <p>This operation uses the following properties in addition to method
parameters:</p>
* <ul>
* <li>{@linkplain #getColorizer() Colorizer} for customizing the
rendered image color model.</li>
* </ul>
@@ -1410,8 +1522,7 @@ public class ImageProcessor implements Cloneable {
* There is no guarantee about the number of bands in returned image or
about which formula is used for converting
* floating point values to integer values.</p>
*
- * <h4>Properties used</h4>
- * This operation uses the following properties in addition to method
parameters:
+ * <p>This operation uses the following properties in addition to method
parameters:</p>
* <ul>
* <li>{@linkplain #getInterpolation() Interpolation method} (nearest
neighbor, bilinear, <i>etc</i>).</li>
* <li>{@linkplain #getFillValues() Fill values} for pixels outside
source image.</li>
@@ -1465,8 +1576,7 @@ public class ImageProcessor implements Cloneable {
* and values are the isolines at the associated level.
* If there are no isolines for a given level, there will be no
corresponding entry in the map.
*
- * <h4>Properties used</h4>
- * This operation uses the following properties in addition to method
parameters:
+ * <p>This operation uses the following properties in addition to method
parameters:</p>
* <ul>
* <li>{@linkplain #getExecutionMode() Execution mode} (parallel or
sequential).</li>
* </ul>
@@ -1514,6 +1624,7 @@ public class ImageProcessor implements Cloneable {
final Mode executionMode;
final ErrorHandler errorHandler;
final Interpolation interpolation;
+ final Aggregation aggregation;
final Number[] fillValues;
final ImageLayout layout;
final Colorizer colorizer;
@@ -1522,19 +1633,21 @@ public class ImageProcessor implements Cloneable {
executionMode = this.executionMode;
errorHandler = this.errorHandler;
interpolation = this.interpolation;
+ aggregation = this.aggregation;
fillValues = this.fillValues;
layout = this.layout;
colorizer = this.colorizer;
positionalAccuracyHints = this.positionalAccuracyHints;
}
synchronized (other) {
- return layout.equals(other.layout) &&
- errorHandler.equals(other.errorHandler) &&
- executionMode.equals(other.executionMode) &&
- interpolation.equals(other.interpolation) &&
- Objects.equals(colorizer, other.colorizer) &&
- Arrays.equals(fillValues, other.fillValues) &&
- Arrays.equals(positionalAccuracyHints,
other.positionalAccuracyHints);
+ return layout.equals(other.layout)
+ && errorHandler .equals(other.errorHandler)
+ && executionMode .equals(other.executionMode)
+ && interpolation .equals(other.interpolation)
+ && aggregation .equals(other.aggregation)
+ && Objects.equals(colorizer, other.colorizer)
+ && Arrays.equals(fillValues, other.fillValues)
+ && Arrays.equals(positionalAccuracyHints,
other.positionalAccuracyHints);
}
}
return false;
@@ -1547,7 +1660,7 @@ public class ImageProcessor implements Cloneable {
*/
@Override
public synchronized int hashCode() {
- return Objects.hash(getClass(), errorHandler, executionMode,
colorizer, interpolation, layout)
+ return Objects.hash(getClass(), errorHandler, executionMode,
colorizer, interpolation, aggregation, layout)
+ 37 * Arrays.hashCode(fillValues)
+ 39 * Arrays.hashCode(positionalAccuracyHints);
}
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Interpolation.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Interpolation.java
index 7b8011b10f..cbceff357e 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Interpolation.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Interpolation.java
@@ -23,9 +23,10 @@ import java.nio.DoubleBuffer;
/**
- * Algorithm for image interpolation (resampling). Interpolations are
performed by sampling on a regular grid
- * of pixels using a local neighborhood. The sampling is performed by the
{@link ResampledImage} class, which
- * gives the sample values to the {@code interpolate(…)} method of this
interpolation.
+ * Algorithm for image resampling based on interpolation methods.
+ * Interpolations are performed by sampling on a regular grid of pixels using
a local neighborhood.
+ * The sampling is performed by the {@link ResampledImage} class, which gives
the sample values to
+ * the {@code interpolate(…)} method of this interpolation.
*
* <p>All methods in this class shall be safe for concurrent use in
multi-threading context.
* For example, interpolations may be executed in a different thread for each
tile in an image.</p>
@@ -36,11 +37,15 @@ import java.nio.DoubleBuffer;
* @author Martin Desruisseaux (Geomatys)
* @author Johann Sorel (Geomatys)
* @version 1.2
+ *
+ * @see ResampledImage
+ * @see Aggregation
+ *
* @since SIS 1.1
*/
public abstract class Interpolation {
/**
- * Creates a new interpolation.
+ * Creates a new interpolation method.
*/
protected Interpolation() {
}
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/MultiSourcePrefetch.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/MultiSourcePrefetch.java
index d0aa7605bf..80ffd235a5 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/MultiSourcePrefetch.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/MultiSourcePrefetch.java
@@ -114,7 +114,7 @@ final class MultiSourcePrefetch implements Disposable {
for (int i=0; i<count; i++) {
final PlanarImage source = sources[i];
final Rectangle r = tileIndices[i];
- if (parallel) {
+ if (workers != null) {
Callable<Disposable> worker = () -> source.prefetch(r);
workers[i] = CommonExecutor.instance().submit(worker);
} else {
@@ -128,7 +128,7 @@ final class MultiSourcePrefetch implements Disposable {
* Block until all background threads finished their work. This is
needed because `PrefetchedImage`
* will start to query tiles after this method returned, so the source
images need to be ready.
*/
- if (parallel) {
+ if (workers != null) {
for (final Future<Disposable> worker : workers) try {
final Disposable cleaner = worker.get();
if (cleaner != null) {
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ResampledImage.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ResampledImage.java
index 675ddf9bc0..be79cf01d4 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ResampledImage.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ResampledImage.java
@@ -212,7 +212,7 @@ public class ResampledImage extends ComputedImage {
* @param minTile indices of the first tile ({@code minTileX},
{@code minTileY}), or {@code null} for (0,0).
* @param bounds domain of pixel coordinates of this resampled
image.
* @param toSource conversion of pixel coordinates of this image to
pixel coordinates of {@code source} image.
- * @param interpolation the object to use for performing interpolations.
+ * @param interpolation the method to use for performing interpolations.
* @param fillValues the values to use for pixels in this image that
cannot be mapped to pixels in source image.
* May be {@code null} or contain {@code null}
elements, and may have any length
* (see above for more details).
@@ -224,9 +224,14 @@ public class ResampledImage extends ComputedImage {
*
* @see ImageProcessor#resample(RenderedImage, Rectangle, MathTransform)
*/
- protected ResampledImage(final RenderedImage source, final SampleModel
sampleModel, final Point minTile,
- final Rectangle bounds, final MathTransform toSource,
Interpolation interpolation,
- final Number[] fillValues, final Quantity<?>[] accuracy)
+ protected ResampledImage(final RenderedImage source,
+ final SampleModel sampleModel,
+ final Point minTile,
+ final Rectangle bounds,
+ final MathTransform toSource,
+ Interpolation interpolation,
+ final Number[] fillValues,
+ final Quantity<?>[] accuracy)
{
super(sampleModel, source);
if ((source.getWidth() | source.getHeight()) <= 0) {
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/FillValues.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/FillValues.java
index 1c24f092e1..bdf467f389 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/FillValues.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/FillValues.java
@@ -119,6 +119,7 @@ public final class FillValues {
*
* @see #isFullyZero
*/
+ @SuppressWarnings("SuspiciousSystemArraycopy")
public void fill(final WritableRaster tile) {
final int xmin = tile.getMinX();
final int width = tile.getWidth();
@@ -200,6 +201,8 @@ public final class FillValues {
/**
* Returns a hash code for the fill values.
+ *
+ * @return a hash code for this fill values container.
*/
@Override
public int hashCode() {
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/TileOpExecutor.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/TileOpExecutor.java
index 6b2731adbe..4b42d9b0c9 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/TileOpExecutor.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/TileOpExecutor.java
@@ -22,6 +22,7 @@ import java.util.stream.Collector;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.awt.Point;
@@ -950,9 +951,10 @@ public class TileOpExecutor {
final Collector<? super Raster, A, R> collector, final
TileErrorHandler errorHandler)
{
final Cursor<RenderedImage,A> cursor = executor.new
Cursor<>(source, collector, errorHandler.isThrow());
- final Future<?>[] workers = new Future<?>[cursor.getNumWorkers()];
+ final var workers = new Future<?>[cursor.getNumWorkers()];
+ final ExecutorService background = CommonExecutor.instance();
for (int i=0; i<workers.length; i++) {
- workers[i] = CommonExecutor.instance().submit(new
ReadWork<>(cursor, collector));
+ workers[i] = background.submit(new ReadWork<>(cursor,
collector));
}
final ReadWork<A> worker = new ReadWork<>(cursor, collector);
worker.run();
@@ -1008,11 +1010,12 @@ public class TileOpExecutor {
final Collector<? super WritableRaster,A,R> collector, final
TileErrorHandler errorHandler)
{
final Cursor<WritableRenderedImage,A> cursor = executor.new
Cursor<>(target, collector, false);
- final Future<?>[] workers = new Future<?>[cursor.getNumWorkers()];
+ final var workers = new Future<?>[cursor.getNumWorkers()];
+ final ExecutorService background = CommonExecutor.instance();
for (int i=0; i<workers.length; i++) {
- workers[i] = CommonExecutor.instance().submit(new
WriteWork<>(cursor, collector));
+ workers[i] = background.submit(new WriteWork<>(cursor,
collector));
}
- final WriteWork<A> worker = new WriteWork<>(cursor, collector);
+ final var worker = new WriteWork<A>(cursor, collector);
worker.run();
return cursor.finish(workers, collector, errorHandler);
}
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/processing/TiledProcess.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/processing/TiledProcess.java
index b137afc77d..bab02b3b6d 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/processing/TiledProcess.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/processing/TiledProcess.java
@@ -20,6 +20,7 @@ import java.awt.Rectangle;
import java.awt.image.RenderedImage;
import java.util.concurrent.Future;
import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.sis.system.CommonExecutor;
@@ -192,9 +193,10 @@ public abstract class TiledProcess<R> {
public final Future<R> execute() {
@SuppressWarnings({"rawtypes", "unchecked"})
final Future<R>[] components = new Future[tasks.length];
+ final ExecutorService executor = CommonExecutor.instance();
while (taskIndex < components.length) {
- final Task task = createSubTask();
- components[taskIndex++] = CommonExecutor.instance().submit(task);
+ final Task task = createSubTask(); // Need to be before
`taskIndex++`.
+ components[taskIndex++] = executor.submit(task);
}
iterators = null; // Clear only after all tasks have been
created.
return CompoundFuture.create(components);
diff --git
a/endorsed/src/org.apache.sis.storage.sql/main/org/apache/sis/storage/sql/feature/InfoStatements.java
b/endorsed/src/org.apache.sis.storage.sql/main/org/apache/sis/storage/sql/feature/InfoStatements.java
index 8e060dba35..06db8634e2 100644
---
a/endorsed/src/org.apache.sis.storage.sql/main/org/apache/sis/storage/sql/feature/InfoStatements.java
+++
b/endorsed/src/org.apache.sis.storage.sql/main/org/apache/sis/storage/sql/feature/InfoStatements.java
@@ -653,7 +653,7 @@ public class InfoStatements implements Localized,
AutoCloseable {
}
database.cacheOfSRID.put(crs, result.srid);
}
- CommonExecutor.instance().submit((Runnable) result);
+ CommonExecutor.submit(result);
return result.srid;
}
@@ -701,7 +701,7 @@ public class InfoStatements implements Localized,
AutoCloseable {
/**
* Invoked in a background thread for opportunistically caching the
<abbr>SRID</abbr> → <abbr>CRS</abbr>
* mapping. This is done in a background thread because this is not
the information asked by the user,
- * by the information for the reverse operation.
+ * but the information needed for the reverse operation.
*/
@Override
public void run() {
@@ -896,6 +896,7 @@ public class InfoStatements implements Localized,
AutoCloseable {
* @throws DataStoreReferencingException if the given CRS cannot be
encoded in at least one supported format.
* @throws SQLException if an error occurred while executing the SQL
statement.
*/
+ @SuppressWarnings("UseSpecificCatch")
private int addCRS(final SRID search, final Set<Integer> sridFounInUse)
throws Exception {
final SpatialSchema schema = database.getSpatialSchema().orElseThrow();
final var sql = builder().append(SQLBuilder.INSERT);
diff --git
a/endorsed/src/org.apache.sis.storage/main/org/apache/sis/storage/folder/ConcurrentCloser.java
b/endorsed/src/org.apache.sis.storage/main/org/apache/sis/storage/folder/ConcurrentCloser.java
index eaf4b00c8a..217dc177cb 100644
---
a/endorsed/src/org.apache.sis.storage/main/org/apache/sis/storage/folder/ConcurrentCloser.java
+++
b/endorsed/src/org.apache.sis.storage/main/org/apache/sis/storage/folder/ConcurrentCloser.java
@@ -75,7 +75,7 @@ public abstract class ConcurrentCloser<R> {
*/
public final void closeAll(final Collection<? extends R> resources) throws
DataStoreException {
final ExecutorService executor = CommonExecutor.instance();
- final Future<?>[] results = new Future<?>[resources.size()];
+ final var results = new Future<?>[resources.size()];
int n = 0;
for (final R r : resources) {
final Callable<?> c = closer(r);
diff --git
a/endorsed/src/org.apache.sis.util/main/org/apache/sis/system/CommonExecutor.java
b/endorsed/src/org.apache.sis.util/main/org/apache/sis/system/CommonExecutor.java
index 36773645ea..49ab2beece 100644
---
a/endorsed/src/org.apache.sis.util/main/org/apache/sis/system/CommonExecutor.java
+++
b/endorsed/src/org.apache.sis.util/main/org/apache/sis/system/CommonExecutor.java
@@ -66,7 +66,7 @@ public final class CommonExecutor extends AtomicInteger
implements ThreadFactory
*/
private static final ThreadPoolExecutor INSTANCE;
static {
- final ThreadPoolExecutor executor = new
ThreadPoolExecutor(PARALLELISM, PARALLELISM, 2, TimeUnit.MINUTES,
+ final var executor = new ThreadPoolExecutor(PARALLELISM, PARALLELISM,
2, TimeUnit.MINUTES,
new LinkedBlockingQueue<>(1000000), // Arbitrary limit
against excessive queue expansion.
new CommonExecutor());
executor.allowCoreThreadTimeOut(true);
@@ -74,14 +74,23 @@ public final class CommonExecutor extends AtomicInteger
implements ThreadFactory
}
/**
- * Returns the executor service shared by SIS modules for most costly
calculations.
+ * Returns the executor service shared by <abbr>SIS</abbr> modules for
most costly calculations.
*
- * @return the executor service for SIS tasks to run in background.
+ * @return the executor service for <abbr>SIS</abbr> tasks to run in
background.
*/
public static ExecutorService instance() {
return INSTANCE;
}
+ /**
+ * Submit a task for execution in a background thread.
+ *
+ * @param task the task to run in a background thread.
+ */
+ public static void submit(final Runnable task) {
+ INSTANCE.submit(task);
+ }
+
/**
* If the given task has been scheduled for execution but its execution
did not yet started,
* removes it from the scheduled list. Otherwise does nothing. The given
task should be one
@@ -122,7 +131,7 @@ public final class CommonExecutor extends AtomicInteger
implements ThreadFactory
*/
@Override
public Thread newThread(final Runnable r) {
- final Thread t = new Thread(Threads.SIS, r, "Background worker #" +
incrementAndGet());
+ final var t = new Thread(Threads.SIS, r, "Background worker #" +
incrementAndGet());
t.setPriority(Thread.NORM_PRIORITY - 2);
t.setDaemon(true);
return t;
diff --git
a/endorsed/src/org.apache.sis.util/main/org/apache/sis/system/Shutdown.java
b/endorsed/src/org.apache.sis.util/main/org/apache/sis/system/Shutdown.java
index 70fabf7124..6a9dcd2f77 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/system/Shutdown.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/system/Shutdown.java
@@ -206,6 +206,8 @@ public final class Shutdown extends Thread {
log(caller, e);
}
}
+ // Shutdown shared executor last in case the above sent some last
cleanup background tasks.
+ CommonExecutor.instance().shutdown();
if (exception != null) {
throw exception;
}
diff --git
a/optional/src/org.apache.sis.gui/main/org/apache/sis/gui/internal/BackgroundThreads.java
b/optional/src/org.apache.sis.gui/main/org/apache/sis/gui/internal/BackgroundThreads.java
index 2b70e8cf03..93ed51254d 100644
---
a/optional/src/org.apache.sis.gui/main/org/apache/sis/gui/internal/BackgroundThreads.java
+++
b/optional/src/org.apache.sis.gui/main/org/apache/sis/gui/internal/BackgroundThreads.java
@@ -38,7 +38,7 @@ import static org.apache.sis.gui.internal.LogHandler.LOGGER;
/**
* Provides the thread pool for JavaFX application. This thread pool is
different than the pool used by
- * the {@link org.apache.sis.system.CommonExecutor} shared by the rest of
Apache SIS library.
+ * the {@link org.apache.sis.system.CommonExecutor} shared by the rest of
Apache <abbr>SIS</abbr> library.
* Contrary to {@code CommonExecutor}, this {@code BackgroundThreads} class
always allocates threads
* to new tasks immediately (no queuing of tasks), no matter if all processors
are already busy or not.
* The intent is to have quicker responsiveness to user actions, even at the
cost of lower throughput.