You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sis.apache.org by de...@apache.org on 2019/03/09 22:59:16 UTC

[sis] branch geoapi-4.0 updated (0218c71 -> f17de4b)

This is an automated email from the ASF dual-hosted git repository.

desruisseaux pushed a change to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git.


    from 0218c71  Take in account the case where the temporal origin of a dataset has fractional seconds.
     new 6ec2776  Replace some !isInfinite(x) && !isNaN(x) pairs by isFinite(x).
     new 88aa2b2  Rename a the localization keys of a few error messages.
     new 4e26b79  Consolidation of error messages related to duplicated values or key collision. Addition of an ArgumentChecks.ensureNonEmpty(…) method which also check against duplicated values.
     new 141af47  Tests against some integer overflows.
     new f17de4b  First draft of the use of linearizers in LinearTransformBuilder. https://issues.apache.org/jira/browse/SIS-446

The 5 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../org/apache/sis/feature/NamedFeatureType.java   |   3 +-
 .../apache/sis/internal/simple/SimpleCitation.java |   3 +-
 .../apache/sis/internal/simple/SimpleFormat.java   |   3 +-
 .../apache/sis/io/wkt/GeodeticObjectParser.java    |   3 +-
 .../metadata/iso/identification/OperationName.java |   3 +-
 .../sis/metadata/iso/quality/AbstractElement.java  |   2 +-
 .../apache/sis/util/iso/DefaultRecordSchema.java   |   3 +-
 .../src/main/java/org/apache/sis/xml/Pooled.java   |   3 +-
 .../org/apache/sis/coverage/grid/GridExtent.java   |  11 +-
 .../java/org/apache/sis/geometry/Envelopes.java    |   4 +-
 .../java/org/apache/sis/geometry/Shapes2D.java     |   2 +-
 .../referencing/provider/MapProjection.java        |   2 +-
 .../sis/internal/referencing/provider/NTv2.java    |   2 +-
 .../org/apache/sis/parameter/TensorParameters.java |  11 +-
 .../sis/parameter/UninitializedParameter.java      |   3 +-
 .../factory/sql/InstallationScriptProvider.java    |   4 +-
 .../apache/sis/referencing/operation/CRSPair.java  |   3 +-
 .../operation/builder/LinearTransformBuilder.java  | 467 +++++++++++++++++----
 .../operation/builder/LocalizationGridBuilder.java |   5 +
 .../operation/builder/ProjectedTransformTry.java   | 324 ++++++++++++++
 .../operation/builder/TransformBuilder.java        |   6 +
 .../operation/transform/AbstractMathTransform.java |   2 +-
 .../builder/LinearTransformBuilderTest.java        |  37 +-
 .../operation/builder/NonLinearTransform.java}     |  41 +-
 .../projection/MapProjectionTestCase.java          |   2 +-
 .../java/org/apache/sis/internal/util/Strings.java |  26 +-
 .../main/java/org/apache/sis/math/ArrayVector.java |   8 +-
 .../main/java/org/apache/sis/math/Fraction.java    |   7 +-
 .../src/main/java/org/apache/sis/math/Plane.java   |   4 +
 .../src/main/java/org/apache/sis/math/Vector.java  |   2 +-
 .../java/org/apache/sis/util/ArgumentChecks.java   |  88 +++-
 .../main/java/org/apache/sis/util/ArraysExt.java   |  86 +++-
 .../src/main/java/org/apache/sis/util/Version.java |   5 +-
 .../sis/util/collection/DefaultTreeTable.java      |   5 +-
 .../sis/util/collection/TreeTableFormat.java       |   4 +-
 .../java/org/apache/sis/util/resources/Errors.java |  43 +-
 .../apache/sis/util/resources/Errors.properties    |  19 +-
 .../apache/sis/util/resources/Errors_fr.properties |  25 +-
 .../org/apache/sis/util/resources/Vocabulary.java  |   5 +
 .../sis/util/resources/Vocabulary.properties       |   1 +
 .../sis/util/resources/Vocabulary_fr.properties    |   1 +
 .../org/apache/sis/internal/util/CitationMock.java |   2 +-
 .../org/apache/sis/util/ArgumentChecksTest.java    |  16 +-
 .../java/org/apache/sis/util/ArraysExtTest.java    |  19 +
 ide-project/NetBeans/nbproject/genfiles.properties |   2 +-
 ide-project/NetBeans/nbproject/project.xml         |   2 +
 .../org/apache/sis/storage/gdal/Proj4Parser.java   |   2 +-
 .../java/org/apache/sis/internal/netcdf/Axis.java  |   2 +-
 .../org/apache/sis/internal/netcdf/CRSBuilder.java |   2 +-
 .../apache/sis/internal/netcdf/NamedElement.java   |   3 +-
 .../org/apache/sis/internal/netcdf/Variable.java   |  11 +-
 51 files changed, 1127 insertions(+), 212 deletions(-)
 create mode 100644 core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/builder/ProjectedTransformTry.java
 copy core/{sis-feature/src/test/java/org/apache/sis/internal/feature/Java2DTest.java => sis-referencing/src/test/java/org/apache/sis/referencing/operation/builder/NonLinearTransform.java} (54%)


[sis] 05/05: First draft of the use of linearizers in LinearTransformBuilder. https://issues.apache.org/jira/browse/SIS-446

Posted by de...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

desruisseaux pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git

commit f17de4bf788c413ef76cd8cb2474bb6b7ca4219c
Author: Martin Desruisseaux <ma...@geomatys.com>
AuthorDate: Sat Mar 9 23:52:51 2019 +0100

    First draft of the use of linearizers in LinearTransformBuilder.
    https://issues.apache.org/jira/browse/SIS-446
---
 .../operation/builder/LinearTransformBuilder.java  | 467 +++++++++++++++++----
 .../operation/builder/LocalizationGridBuilder.java |   5 +
 .../operation/builder/ProjectedTransformTry.java   | 324 ++++++++++++++
 .../operation/builder/TransformBuilder.java        |   6 +
 .../operation/transform/AbstractMathTransform.java |   2 +-
 .../builder/LinearTransformBuilderTest.java        |  37 +-
 .../operation/builder/NonLinearTransform.java      |  51 +++
 .../java/org/apache/sis/internal/util/Strings.java |  26 +-
 .../src/main/java/org/apache/sis/math/Plane.java   |   4 +
 .../main/java/org/apache/sis/util/ArraysExt.java   |   8 +-
 .../org/apache/sis/util/resources/Vocabulary.java  |   5 +
 .../sis/util/resources/Vocabulary.properties       |   1 +
 .../sis/util/resources/Vocabulary_fr.properties    |   1 +
 ide-project/NetBeans/nbproject/genfiles.properties |   2 +-
 ide-project/NetBeans/nbproject/project.xml         |   2 +
 15 files changed, 852 insertions(+), 89 deletions(-)

diff --git a/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/builder/LinearTransformBuilder.java b/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/builder/LinearTransformBuilder.java
index 4138d69..6aa38a4 100644
--- a/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/builder/LinearTransformBuilder.java
+++ b/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/builder/LinearTransformBuilder.java
@@ -17,8 +17,15 @@
 package org.apache.sis.referencing.operation.builder;
 
 import java.util.Map;
+import java.util.List;
+import java.util.Queue;
 import java.util.Arrays;
+import java.util.ArrayList;
+import java.util.ArrayDeque;
+import java.util.Collections;
 import java.util.NoSuchElementException;
+import java.util.Optional;
+import java.text.NumberFormat;
 import java.io.IOException;
 import java.io.UncheckedIOException;
 import org.opengis.util.FactoryException;
@@ -27,6 +34,7 @@ import org.opengis.geometry.DirectPosition;
 import org.opengis.geometry.MismatchedDimensionException;
 import org.opengis.geometry.coordinate.Position;
 import org.opengis.referencing.operation.Matrix;
+import org.opengis.referencing.operation.MathTransform;
 import org.opengis.referencing.operation.MathTransformFactory;
 import org.apache.sis.geometry.GeneralEnvelope;
 import org.apache.sis.io.TableAppender;
@@ -60,9 +68,23 @@ import org.apache.sis.util.Classes;
  * Otherwise a builder created by the {@link #LinearTransformBuilder()} constructor will be able to handle
  * randomly distributed coordinates.
  *
- * <p>The transform coefficients are determined using a <cite>least squares</cite> estimation method,
+ * <p>Builders can be used only once;
+ * points can not be added or modified after {@link #create(MathTransformFactory)} has been invoked.
+ * The transform coefficients are determined using a <cite>least squares</cite> estimation method,
  * with the assumption that source positions are exact and all the uncertainty is in the target positions.</p>
  *
+ * <div class="section">Linearizers</div>
+ * Consider the following situation (commonly found with {@linkplain org.apache.sis.storage.netcdf netCDF files}):
+ * the <i>sources</i> coordinates are pixel indices and the <i>targets</i> are (longitude, latitude) coordinates,
+ * but we suspect that the <i>sources to targets</i> transform is some undetermined map projection, maybe Mercator.
+ * A linear approximation between those coordinates will give poor results; the results would be much better if all
+ * (longitude, latitude) coordinates were converted to the right projection first. However that map projection may
+ * not be known, but we can try to guess it by trials-and-errors using a set of plausible projections.
+ * That set can be specified by {@link #addLinearizers(Map, int...)}.
+ * If the {@link #create(MathTransformFactory)} method finds that one of the specified projections seems a good fit,
+ * it will automatically convert all target coordinates to that projection.
+ * That selected projection is given by {@link #linearizer()}.
+ *
  * @author  Martin Desruisseaux (Geomatys)
  * @version 1.0
  *
@@ -103,6 +125,12 @@ public class LinearTransformBuilder extends TransformBuilder {
      * This layout allows to create only a few (typically two) large arrays instead of a multitude of small arrays.
      * Example: {x[], y[], z[]}.
      * This is {@code null} if not yet specified.
+     *
+     * <div class="note"><b>Implementation note:</b>
+     * we could use a flat array with (x₀, y₀), (x₁, y₁), (x₂, y₂), <i>etc.</i> coordinate tuples instead.
+     * Such flat array would be more convenient for some coordinate conversions with {@link MathTransform}.
+     * But using array of arrays is more convenient for other calculations working on one dimension at time,
+     * make data more local for CPU, and also allows handling of more points.</div>
      */
     private double[][] targets;
 
@@ -122,8 +150,25 @@ public class LinearTransformBuilder extends TransformBuilder {
     private int numPoints;
 
     /**
+     * If the user suspects that the transform may be linear when the target is another space than the space of
+     * {@link #targets} coordinates, projections toward spaces to try. The {@link #create(MathTransformFactory)}
+     * method will try to apply those transforms on {@link #targets} and check if they produce better fits.
+     *
+     * @see #addLinearizers(Map, int[])
+     * @see #linearizer()
+     */
+    private List<ProjectedTransformTry> linearizers;
+
+    /**
+     * If one of the {@linkplain #linearizers} have been applied, that linearizer. Otherwise {@code null}.
+     *
+     * @see #linearizer()
+     */
+    private transient ProjectedTransformTry appliedLinearizer;
+
+    /**
      * The transform created by the last call to {@link #create(MathTransformFactory)}.
-     * This is reset to {@code null} when coordinates are modified.
+     * A non-null value means that this builder became unmodifiable.
      */
     private transient LinearTransform transform;
 
@@ -131,7 +176,24 @@ public class LinearTransformBuilder extends TransformBuilder {
      * An estimation of the Pearson correlation coefficient for each target dimension.
      * This is {@code null} if not yet computed.
      */
-    private transient double[] correlation;
+    private transient double[] correlations;
+
+    /**
+     * Creates a temporary builder with all source fields from the given builder and no target arrays.
+     * Calculated fields, namely {@link #correlations} and {@link #transform}, are left uninitialized.
+     * Arrays are copied by references and their content shall not be modified. The new builder should
+     * not be made accessible to users since changes in this builder would be reflected in the source
+     * values or original builder. This constructor is reserved to {@link #create(MathTransformFactory)}
+     * internal usage.
+     *
+     * @param original  the builder from which to take array references of source values.
+     */
+    private LinearTransformBuilder(final LinearTransformBuilder original) {
+        gridSize   = original.gridSize;
+        sources    = original.sources;
+        gridLength = original.gridLength;
+        numPoints  = original.numPoints;
+    }
 
     /**
      * Creates a new linear transform builder for randomly distributed positions.
@@ -326,6 +388,14 @@ search: for (int j=numPoints; --j >= 0;) {
     }
 
     /**
+     * Returns the error message to be given to {@link IllegalStateException}
+     * when this builder can not be modified anymore.
+     */
+    private static String unmodifiable() {
+        return Errors.format(Errors.Keys.UnmodifiableObject_1, LinearTransformBuilder.class);
+    }
+
+    /**
      * Returns the number of dimensions in the source grid, or -1 if this builder is not backed by a grid.
      * Contrarily to the other {@code get*Dimensions()} methods, this method does not throw exception.
      *
@@ -391,12 +461,14 @@ search: for (int j=numPoints; --j >= 0;) {
             }
             return envelope;
         } else {
-            return envelope(sources);
+            return envelope(sources, numPoints);
         }
     }
 
     /**
      * Returns the envelope of target points. The lower and upper values are inclusive.
+     * If a {@linkplain #linearizer() linearizer has been applied}, then coordinates of
+     * the returned envelope are projected by that linearizer.
      *
      * @return the envelope of target points.
      * @throws IllegalStateException if the target points are not yet known.
@@ -404,22 +476,24 @@ search: for (int j=numPoints; --j >= 0;) {
      * @since 1.0
      */
     public Envelope getTargetEnvelope() {
-        return envelope(targets);
+        return envelope(targets, (gridLength != 0) ? gridLength : numPoints);
     }
 
     /**
      * Implementation of {@link #getSourceEnvelope()} and {@link #getTargetEnvelope()}.
      */
-    private static Envelope envelope(final double[][] points) {
+    private static Envelope envelope(final double[][] points, final int numPoints) {
         if (points == null) {
             throw new IllegalStateException(noData());
         }
         final int dim = points.length;
         final GeneralEnvelope envelope = new GeneralEnvelope(dim);
         for (int i=0; i<dim; i++) {
+            final double[] values = points[i];
             double lower = Double.POSITIVE_INFINITY;
             double upper = Double.NEGATIVE_INFINITY;
-            for (final double value : points[i]) {
+            for (int j=0; j<numPoints; j++) {
+                final double value = values[j];
                 if (value < lower) lower = value;
                 if (value > upper) upper = value;
             }
@@ -447,7 +521,7 @@ search: for (int j=numPoints; --j >= 0;) {
      *
      * <p>All source positions shall have the same number of dimensions (the <cite>source dimension</cite>),
      * and all target positions shall have the same number of dimensions (the <cite>target dimension</cite>).
-     * However the source dimension does not need to be the same the target dimension.
+     * However the source dimension does not need to be the same than the target dimension.
      * Apache SIS currently supports only one- or two-dimensional source positions,
      * together with arbitrary target dimension.</p>
      *
@@ -459,6 +533,7 @@ search: for (int j=numPoints; --j >= 0;) {
      *
      * @param  sourceToTarget  a map of source positions to target positions.
      *         Source positions are assumed precise and target positions are assumed uncertain.
+     * @throws IllegalStateException if {@link #create(MathTransformFactory) create(…)} has already been invoked.
      * @throws IllegalArgumentException if the given positions contain NaN or infinite coordinate values.
      * @throws IllegalArgumentException if this builder has been {@linkplain #LinearTransformBuilder(int...)
      *         created for a grid} but some source coordinates are not indices in that grid.
@@ -469,14 +544,15 @@ search: for (int j=numPoints; --j >= 0;) {
     public void setControlPoints(final Map<? extends Position, ? extends Position> sourceToTarget)
             throws MismatchedDimensionException
     {
+        if (transform != null) {
+            throw new IllegalStateException(unmodifiable());
+        }
         ArgumentChecks.ensureNonNull("sourceToTarget", sourceToTarget);
-        transform   = null;
-        correlation = null;
-        sources     = null;
-        targets     = null;
-        numPoints   = 0;
-        int srcDim  = 0;
-        int tgtDim  = 0;
+        sources    = null;
+        targets    = null;
+        numPoints  = 0;
+        int srcDim = 0;
+        int tgtDim = 0;
         for (final Map.Entry<? extends Position, ? extends Position> entry : sourceToTarget.entrySet()) {
             final DirectPosition src = position(entry.getKey());   if (src == null) continue;
             final DirectPosition tgt = position(entry.getValue()); if (tgt == null) continue;
@@ -543,6 +619,10 @@ search: for (int j=numPoints; --j >= 0;) {
      * The map is unmodifiable and is guaranteed to contain only non-null keys and values.
      * The map is a view: changes in this builder are immediately reflected in the returned map.
      *
+     * <p>If {@link #linearizer()} returns a non-empty value,
+     * then the values in the returned map are projected using that linearizer.
+     * This may happen only after {@link #create(MathTransformFactory) create(…)} has been invoked.</p>
+     *
      * @return all control points in this builder.
      *
      * @since 1.0
@@ -788,6 +868,7 @@ search:         for (int j=domain(); --j >= 0;) {
      *                 then for every index <var>i</var> the {@code source[i]} value shall be in the [0 … {@code gridSize[i]}-1] range inclusive.
      *                 If this builder has been created with the {@link #LinearTransformBuilder()} constructor, then no constraint apply.
      * @param  target  the target coordinates, assumed uncertain.
+     * @throws IllegalStateException if {@link #create(MathTransformFactory) create(…)} has already been invoked.
      * @throws IllegalArgumentException if this builder has been {@linkplain #LinearTransformBuilder(int...) created for a grid}
      *         but some source coordinates are out of index range, or if {@code target} contains NaN of infinite numbers.
      * @throws MismatchedDimensionException if the source or target position does not have the expected number of dimensions.
@@ -795,6 +876,9 @@ search:         for (int j=domain(); --j >= 0;) {
      * @since 0.8
      */
     public void setControlPoint(final int[] source, final double[] target) {
+        if (transform != null) {
+            throw new IllegalStateException(unmodifiable());
+        }
         ArgumentChecks.ensureNonNull("source", source);
         ArgumentChecks.ensureNonNull("target", target);
         verifySourceDimension(source.length);
@@ -809,6 +893,9 @@ search:         for (int j=domain(); --j >= 0;) {
             if (targets == null) {
                 allocate(tgtDim);
             }
+            if (Double.isNaN(targets[0][index])) {
+                numPoints++;
+            }
         } else {
             /*
              * Case of randomly distributed points. Algorithm used below is inefficient, but Javadoc
@@ -836,10 +923,11 @@ search:         for (int j=domain(); --j >= 0;) {
         for (int i=0; i<tgtDim; i++) {
             isValid &= Double.isFinite(targets[i][index] = target[i]);
         }
-        transform   = null;
-        correlation = null;
         if (!isValid) {
-            if (gridSize == null) numPoints--;
+            numPoints--;
+            for (int i=0; i<tgtDim; i++) {
+                targets[i][index] = Double.NaN;
+            }
             throw new IllegalArgumentException(Errors.format(Errors.Keys.IllegalMapping_2,
                                                source, new DirectPositionView.Double(target)));
         }
@@ -850,6 +938,9 @@ search:         for (int j=domain(); --j >= 0;) {
      * This method can be used for retrieving points set by previous calls to
      * {@link #setControlPoint(int[], double[])} or {@link #setControlPoints(Map)}.
      *
+     * <p>If {@link #linearizer()} returns a non-empty value, then the returned values are projected using that linearizer.
+     * This may happen only if this method is invoked after {@link #create(MathTransformFactory) create(…)}.</p>
+     *
      * <div class="note"><b>Performance note:</b>
      * current implementation is efficient for builders {@linkplain #LinearTransformBuilder(int...) created for a grid}
      * but inefficient for builders {@linkplain #LinearTransformBuilder() created for randomly distributed points}.</div>
@@ -900,9 +991,13 @@ search:         for (int j=domain(); --j >= 0;) {
      * <i>etc.</i>. Coordinates are stored in row-major order (column index varies faster, followed by row index).
      *
      * @param  coordinates coordinates in each target dimensions, stored in row-major order.
+     * @throws IllegalStateException if {@link #create(MathTransformFactory) create(…)} has already been invoked.
      */
-    final void setControlPoints(final Vector... coordinates) {
+    final void setControlPoints(final Vector[] coordinates) {
         assert gridSize != null;
+        if (transform != null) {
+            throw new IllegalStateException(unmodifiable());
+        }
         final int tgtDim = coordinates.length;
         final double[][] result = new double[tgtDim][];
         for (int i=0; i<tgtDim; i++) {
@@ -917,9 +1012,8 @@ search:         for (int j=domain(); --j >= 0;) {
             }
             throw new IllegalArgumentException(Errors.format(Errors.Keys.UnexpectedArrayLength_2, gridLength, size));
         }
-        targets     = result;
-        transform   = null;
-        correlation = null;
+        targets = result;
+        numPoints = gridLength;
     }
 
     /**
@@ -955,8 +1049,12 @@ search:         for (int j=domain(); --j >= 0;) {
      *                    Value can be from 0 inclusive to {@link #getSourceDimensions()} exclusive.
      *                    The recommended direction is the direction of most stable values, typically 1 (rows) for longitudes.
      * @param  period     that wraparound range (typically 360° for longitudes).
+     * @throws IllegalStateException if {@link #create(MathTransformFactory) create(…)} has already been invoked.
      */
     final void resolveWraparoundAxis(final int dimension, final int direction, final double period) {
+        if (transform != null) {
+            throw new IllegalStateException(unmodifiable());
+        }
         final double[] coordinates = targets[dimension];
         int stride = 1;
         for (int i=0; i<direction; i++) {
@@ -1014,8 +1112,56 @@ search:         for (int j=domain(); --j >= 0;) {
     }
 
     /**
+     * Adds transforms to potentially apply on target coordinates before to compute the linear transform.
+     * This method can be invoked if one suspects that the <cite>source to target</cite> transform may be
+     * more linear when the target is another space than the current space of {@linkplain #getTargetEnvelope()
+     * target coordinates}. If linearizers have been specified, then the {@link #create(MathTransformFactory)}
+     * method will try to apply each transform on target coordinates and check which one results in the best
+     * {@linkplain #correlation() correlation} coefficients. It may be none.
+     *
+     * <p>The linearizers are specified as {@link MathTransform}s from current target coordinates to other spaces
+     * where <cite>sources to new targets</cite> transforms may be more linear. The keys in the map are arbitrary
+     * identifiers used in {@link #toString()} for analysis or debugging purpose.
+     * The {@code dimensions} argument specifies which target dimensions to project and can be null or omitted
+     * if the projections shall be applied on all target coordinates. It is possible to invoke this method many
+     * times with different {@code dimensions} argument values.</p>
+     *
+     * @param  projections  projections from current target coordinates to other spaces which may result in more linear transforms.
+     * @param  dimensions   the target dimensions to project, or null or omitted for projecting all target dimensions.
+     *                      If non-null and non-empty, then all transforms in the {@code projections} map shall have a
+     *                      number of source and target dimensions equals to the length of this array.
+     * @throws IllegalStateException if {@link #create(MathTransformFactory) create(…)} has already been invoked.
+     *
+     * @see #linearizer()
+     * @see #correlation()
+     *
+     * @since 1.0
+     */
+    public void addLinearizers(final Map<String,MathTransform> projections, int... dimensions) {
+        if (transform != null) {
+            throw new IllegalStateException(unmodifiable());
+        }
+        final int tgtDim = getTargetDimensions();
+        if (dimensions == null || dimensions.length == 0) {
+            dimensions = ArraysExt.sequence(0, tgtDim);
+        }
+        if (linearizers == null) {
+            linearizers = new ArrayList<>();
+        }
+        for (final Map.Entry<String,MathTransform> entry : projections.entrySet()) {
+            ProjectedTransformTry t = new ProjectedTransformTry(entry.getKey(), entry.getValue(), dimensions, tgtDim);
+            if (!t.projection.isIdentity()) {
+                linearizers.add(t);
+            }
+        }
+    }
+
+    /**
      * Creates a linear transform approximation from the source positions to the target positions.
      * This method assumes that source positions are precise and that all uncertainty is in the target positions.
+     * If {@linkplain #addLinearizers linearizers have been specified}, then this method may project all target
+     * coordinates using one of those linearizers in order to get a more linear transform.
+     * If such projection is applied, then {@link #linearizer()} will return a non-empty value after this method call.
      *
      * @param  factory  the factory to use for creating the transform, or {@code null} for the default factory.
      *                  The {@link MathTransformFactory#createAffineTransform(Matrix)} method of that factory
@@ -1027,68 +1173,129 @@ search:         for (int j=domain(); --j >= 0;) {
      * @since 0.8
      */
     @Override
-    @SuppressWarnings("serial")
     public LinearTransform create(final MathTransformFactory factory) throws FactoryException {
         if (transform == null) {
-            final double[][] sources = this.sources;                    // Protect from changes.
-            final double[][] targets = this.targets;
-            if (targets == null) {
-                throw new InvalidGeodeticParameterException(noData());
-            }
-            final int sourceDim = (sources != null) ? sources.length : gridSize.length;
-            final int targetDim = targets.length;
-            correlation = new double[targetDim];
-            final MatrixSIS matrix = Matrices.create(targetDim + 1, sourceDim + 1,  ExtendedPrecisionMatrix.ZERO);
-            matrix.setElement(targetDim, sourceDim, 1);
-            for (int j=0; j < targetDim; j++) {
-                final double c;
-                switch (sourceDim) {
-                    case 1: {
-                        final int row = j;
-                        final Line line = new Line() {
-                            @Override public void setEquation(final Number slope, final Number y0) {
-                                super.setEquation(slope, y0);
-                                matrix.setNumber(row, 0, slope);    // Preserve the extended precision (double-double).
-                                matrix.setNumber(row, 1, y0);
-                            }
-                        };
-                        if (sources != null) {
-                            c = line.fit(vector(sources[0]), vector(targets[j]));
+            MatrixSIS matrix = fit();
+            if (linearizers != null) {
+                /*
+                 * We are going to try to project target coordinates in an attempt to find a more linear transform.
+                 * If a projection allows better results than unprojected coordinates, the following variables will
+                 * be set to values to assign to this 'LinearTransformBuilder' after the loop. We do not assign new
+                 * values to this 'LinearTransformBuilder' directly (as we find them) in the loop because the checks
+                 * for a better transform require the original values.
+                 */
+                double     bestCorrelation   = average(correlations);
+                double[]   bestCorrelations  = null;
+                MatrixSIS  bestTransform     = null;
+                double[][] transformedArrays = null;
+                /*
+                 * Store the correlation when using no conversions, only for this.toString() purpose. We copy
+                 * 'ProjectedTransformTry' list in an array both for excluding the dummy entry, and also for
+                 * avoiding ConcurrentModificationException if a debugger invokes toString() during the loop.
+                 */
+                final ProjectedTransformTry[] alternatives = linearizers.toArray(new ProjectedTransformTry[linearizers.size()]);
+                linearizers.add(new ProjectedTransformTry((float) bestCorrelation));
+                /*
+                 * 'tmp' and 'pool' are temporary objects for this computation only. We use a pool because the
+                 * 'double[]' arrays may be large (e.g. megabytes) and we want to avoid creating new arrays of
+                 * such size for each projection to try.
+                 */
+                final Queue<double[]> pool = new ArrayDeque<>();
+                final int n = (gridLength != 0) ? gridLength : numPoints;
+                final LinearTransformBuilder tmp = new LinearTransformBuilder(this);
+                for (final ProjectedTransformTry alt : alternatives) {
+                    if ((tmp.targets = alt.transform(targets, n, pool)) != null) {
+                        final MatrixSIS altTransform    = tmp.fit();
+                        final double[]  altCorrelations = alt.replace(correlations, tmp.correlations);
+                        final double    altCorrelation  = average(altCorrelations);
+                        alt.correlation = (float) altCorrelation;
+                        if (altCorrelation > bestCorrelation) {
+                            ProjectedTransformTry.recycle(transformedArrays, pool);
+                            transformedArrays = tmp.targets;
+                            bestCorrelation   = altCorrelation;
+                            bestCorrelations  = altCorrelations;
+                            bestTransform     = alt.replace(matrix, altTransform);
+                            appliedLinearizer = alt;
                         } else {
-                            c = line.fit(Vector.createSequence(0, 1, gridSize[0]),
-                                         Vector.create(targets[j]));
+                            ProjectedTransformTry.recycle(tmp.targets, pool);
                         }
-                        break;
                     }
-                    case 2: {
-                        final int row = j;
-                        final Plane plan = new Plane() {
-                            @Override public void setEquation(final Number sx, final Number sy, final Number z0) {
-                                super.setEquation(sx, sy, z0);
-                                matrix.setNumber(row, 0, sx);       // Preserve the extended precision (double-double).
-                                matrix.setNumber(row, 1, sy);
-                                matrix.setNumber(row, 2, z0);
-                            }
-                        };
-                        if (sources != null) {
-                            c = plan.fit(vector(sources[0]), vector(sources[1]), vector(targets[j]));
-                        } else try {
-                            c = plan.fit(gridSize[0], gridSize[1], Vector.create(targets[j]));
-                        } catch (IllegalArgumentException e) {
-                            // This may happen if the z vector still contain some "NaN" values.
-                            throw new InvalidGeodeticParameterException(noData(), e);
+                }
+                if (bestTransform != null) {
+                    matrix       = bestTransform;
+                    targets      = transformedArrays;
+                    correlations = bestCorrelations;
+                }
+            }
+            transform = (LinearTransform) nonNull(factory).createAffineTransform(matrix);
+        }
+        return transform;
+    }
+
+    /**
+     * Computes the matrix of the linear approximation. This is the implementation of {@link #create(MathTransformFactory)}
+     * without the step creating the {@link LinearTransform} from a matrix. The {@link #correlations} field is set as a side
+     * effect of this method call.
+     */
+    @SuppressWarnings("serial")
+    private MatrixSIS fit() throws FactoryException {
+        final double[][] sources = this.sources;                    // Protect from changes.
+        final double[][] targets = this.targets;
+        if (targets == null) {
+            throw new InvalidGeodeticParameterException(noData());
+        }
+        final int sourceDim = (sources != null) ? sources.length : gridSize.length;
+        final int targetDim = targets.length;
+        correlations = new double[targetDim];
+        final MatrixSIS matrix = Matrices.create(targetDim + 1, sourceDim + 1,  ExtendedPrecisionMatrix.ZERO);
+        matrix.setElement(targetDim, sourceDim, 1);
+        for (int j=0; j < targetDim; j++) {
+            final double c;
+            switch (sourceDim) {
+                case 1: {
+                    final int row = j;
+                    final Line line = new Line() {
+                        @Override public void setEquation(final Number slope, final Number y0) {
+                            super.setEquation(slope, y0);
+                            matrix.setNumber(row, 0, slope);    // Preserve the extended precision (double-double).
+                            matrix.setNumber(row, 1, y0);
                         }
-                        break;
+                    };
+                    if (sources != null) {
+                        c = line.fit(vector(sources[0]), vector(targets[j]));
+                    } else {
+                        c = line.fit(Vector.createSequence(0, 1, gridSize[0]),
+                                     Vector.create(targets[j]));
                     }
-                    default: {
-                        throw new FactoryException(Errors.format(Errors.Keys.ExcessiveNumberOfDimensions_1, sourceDim));
+                    break;
+                }
+                case 2: {
+                    final int row = j;
+                    final Plane plan = new Plane() {
+                        @Override public void setEquation(final Number sx, final Number sy, final Number z0) {
+                            super.setEquation(sx, sy, z0);
+                            matrix.setNumber(row, 0, sx);       // Preserve the extended precision (double-double).
+                            matrix.setNumber(row, 1, sy);
+                            matrix.setNumber(row, 2, z0);
+                        }
+                    };
+                    if (sources != null) {
+                        c = plan.fit(vector(sources[0]), vector(sources[1]), vector(targets[j]));
+                    } else try {
+                        c = plan.fit(gridSize[0], gridSize[1], Vector.create(targets[j]));
+                    } catch (IllegalArgumentException e) {
+                        // This may happen if the z vector still contain some "NaN" values.
+                        throw new InvalidGeodeticParameterException(noData(), e);
                     }
+                    break;
+                }
+                default: {
+                    throw new FactoryException(Errors.format(Errors.Keys.ExcessiveNumberOfDimensions_1, sourceDim));
                 }
-                correlation[j] = c;
             }
-            transform = (LinearTransform) nonNull(factory).createAffineTransform(matrix);
+            correlations[j] = c;
         }
-        return transform;
+        return matrix;
     }
 
     /**
@@ -1102,43 +1309,137 @@ search:         for (int j=domain(); --j >= 0;) {
     }
 
     /**
-     * Returns the correlation coefficients of the last transform created by {@link #create create(…)},
-     * or {@code null} if none. If non-null, the array length is equals to the number of target
-     * dimensions.
+     * Returns a global estimation of correlation by computing the average of absolute values.
+     * We don't use {@link org.apache.sis.math.MathFunctions#magnitude(double...)} because it
+     * would result in values greater than 1.
+     */
+    private static double average(final double[] correlations) {
+        double sum = 0;
+        for (int i=0; i<correlations.length; i++) {
+            sum += Math.abs(correlations[i]);
+        }
+        return sum / correlations.length;
+    }
+
+    /**
+     * If all target coordinates have been projected to another space, returns the projection applied.
+     * This method returns a non-empty value only if all the following conditions are met:
      *
-     * @return estimation of correlation coefficients for each target dimension, or {@code null}.
+     * <ol>
+     *   <li>{@link #addLinearizers(Map, int...)} has been invoked.</li>
+     *   <li>{@link #create(MathTransformFactory)} has been invoked.</li>
+     *   <li>The {@code create(…)} method at step 2 found that projecting target coordinates using
+     *       one of the linearizers specified at step 1 results in a more linear transform.</li>
+     * </ol>
+     *
+     * If this method returns a non-empty value, then the envelope returned by {@link #getTargetEnvelope()}
+     * and all control points returned by {@link #getControlPoint(int[])} are projected by this transform.
+     *
+     * @return the projection applied on target coordinates before to compute a linear transform.
+     *
+     * @since 1.0
+     */
+    public Optional<MathTransform> linearizer() {
+        return (appliedLinearizer != null) ? Optional.of(appliedLinearizer.projection) : Optional.empty();
+    }
+
+    /**
+     * Returns the Pearson correlation coefficients of the transform created by {@link #create create(…)}.
+     * The closer those coefficients are to +1 or -1, the better the fit.
+     * This method returns {@code null} if {@code create(…)} has not yet been invoked.
+     * If non-null, the array length is equal to the number of target dimensions.
+     *
+     * @return estimation of Pearson correlation coefficients for each target dimension,
+     *         or {@code null} if {@code create(…)} has not been invoked yet.
      */
     public double[] correlation() {
-        return (correlation != null) ? correlation.clone() : null;
+        return (correlations != null) ? correlations.clone() : null;
     }
 
     /**
      * Returns a string representation of this builder for debugging purpose.
+     * Current implementation shows the following information:
+     *
+     * <ul>
+     *   <li>Number of points.</li>
+     *   <li>Linearizers and their correlation coefficients (if available).</li>
+     *   <li>The linear transform (if already computed).</li>
+     * </ul>
+     *
+     * The string representation may change in any future version.
      *
      * @return a string representation of this builder.
      */
     @Override
     public String toString() {
-        final StringBuilder buffer = new StringBuilder(Classes.getShortClassName(this)).append('[');
-        if (sources != null) {
-            buffer.append(sources[0].length).append(" points");
+        final StringBuilder buffer = new StringBuilder(Classes.getShortClassName(this))
+                .append('[').append(numPoints).append(" points");
+        if (gridSize != null) {
+            String separator = " on ";
+            for (final int size : gridSize) {
+                buffer.append(separator).append(size);
+                separator = " × ";
+            }
+            buffer.append(" grid");
         }
         buffer.append(']');
+        final String lineSeparator = System.lineSeparator();
+        /*
+         * Example (from LinearTransformBuilderTest):
+         * ┌────────────┬─────────────┐
+         * │ Conversion │ Correlation │
+         * ├────────────┼─────────────┤
+         * │ x³ y²      │ 1.000000    │
+         * │ x² y³      │ 0.997437    │
+         * │ Identité   │ 0.995969    │
+         * └────────────┴─────────────┘
+         */
+        if (linearizers != null) {
+            buffer.append(':').append(lineSeparator);
+            Collections.sort(linearizers);
+            NumberFormat nf = null;
+            final TableAppender table = new TableAppender(buffer, " │ ");
+            table.appendHorizontalSeparator();
+            table.append(Vocabulary.format(Vocabulary.Keys.Conversion)).nextColumn();
+            table.append(Vocabulary.format(Vocabulary.Keys.Correlation)).nextLine();
+            table.appendHorizontalSeparator();
+            for (final ProjectedTransformTry alt : linearizers) {
+                nf = alt.summarize(table, nf);
+            }
+            table.appendHorizontalSeparator();
+            try {
+                table.flush();
+            } catch (IOException e) {
+                throw new UncheckedIOException(e);      // Should never happen since we wrote into a StringBuilder.
+            }
+        }
+        /*
+         * Example:
+         * Result:
+         * ┌               ┐                 ┌        ┐
+         * │ 2.0  0    3.0 │   Correlation = │ 0.9967 │
+         * │ 0    1.0  1.0 │                 │ 0.9950 │
+         * │ 0    0    1   │                 └        ┘
+         * └               ┘
+         */
         if (transform != null) {
-            final String lineSeparator = System.lineSeparator();
+            if (linearizers != null) {
+                buffer.append(Vocabulary.format(Vocabulary.Keys.Result));
+            }
             buffer.append(':').append(lineSeparator);
             final TableAppender table = new TableAppender(buffer, " ");
             table.setMultiLinesCells(true);
             table.append(Matrices.toString(transform.getMatrix())).nextColumn();
             table.append(lineSeparator).append("  ")
                  .append(Vocabulary.format(Vocabulary.Keys.Correlation)).append(" =").nextColumn();
-            table.append(Matrices.create(correlation.length, 1, correlation).toString());
+            table.append(Matrices.create(correlations.length, 1, correlations).toString());
             try {
                 table.flush();
             } catch (IOException e) {
                 throw new UncheckedIOException(e);      // Should never happen since we wrote into a StringBuilder.
             }
         }
+        Strings.insertLineInLeftMargin(buffer, lineSeparator);
         return buffer.toString();
     }
 }
diff --git a/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/builder/LocalizationGridBuilder.java b/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/builder/LocalizationGridBuilder.java
index b3fb15a..a035ec9 100644
--- a/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/builder/LocalizationGridBuilder.java
+++ b/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/builder/LocalizationGridBuilder.java
@@ -61,6 +61,9 @@ import static org.apache.sis.referencing.operation.builder.ResidualGrid.SOURCE_D
  *   <li>Create a {@link InterpolatedTransform} with the above shift grid.</li>
  * </ol>
  *
+ * Builders can be used only once;
+ * points can not be added or modified after {@link #create(MathTransformFactory)} has been invoked.
+ *
  * @author  Martin Desruisseaux (Geomatys)
  * @version 1.0
  *
@@ -351,6 +354,7 @@ public class LocalizationGridBuilder extends TransformBuilder {
      * <i>etc.</i>. Coordinates are stored in row-major order (column index varies faster, followed by row index).
      *
      * @param  coordinates coordinates in each target dimensions, stored in row-major order.
+     * @throws IllegalStateException if {@link #create(MathTransformFactory) create(…)} has already been invoked.
      *
      * @since 1.0
      */
@@ -369,6 +373,7 @@ public class LocalizationGridBuilder extends TransformBuilder {
      * @param  gridX   the column index in the grid where to store the given target position.
      * @param  gridY   the row index in the grid where to store the given target position.
      * @param  target  the target coordinates, assumed uncertain.
+     * @throws IllegalStateException if {@link #create(MathTransformFactory) create(…)} has already been invoked.
      * @throws IllegalArgumentException if the {@code x} or {@code y} coordinate value is out of grid range.
      * @throws MismatchedDimensionException if the target position does not have the expected number of dimensions.
      */
diff --git a/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/builder/ProjectedTransformTry.java b/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/builder/ProjectedTransformTry.java
new file mode 100644
index 0000000..5065b8f
--- /dev/null
+++ b/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/builder/ProjectedTransformTry.java
@@ -0,0 +1,324 @@
+/*
+ * 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.referencing.operation.builder;
+
+import java.util.Queue;
+import java.util.Arrays;
+import java.text.NumberFormat;
+import org.opengis.geometry.MismatchedDimensionException;
+import org.opengis.referencing.operation.MathTransform;
+import org.opengis.referencing.operation.TransformException;
+import org.apache.sis.referencing.operation.matrix.MatrixSIS;
+import org.apache.sis.internal.referencing.Resources;
+import org.apache.sis.io.TableAppender;
+import org.apache.sis.util.ArraysExt;
+import org.apache.sis.util.resources.Vocabulary;
+
+
+/**
+ * Information about an attempt to transform coordinates to some projection before to compute a linear approximation.
+ * This class contains only the projection to be attempted and a summary of the result. We do not keep new coordinates
+ * in order to avoid consuming too much memory when many attempts are made; {@link LinearTransformBuilder} needs only
+ * to keep the best attempt.
+ *
+ * <div class="note">
+ * <p><b>Purpose:</b> localization grids in netCDF files contain (<var>longitude</var>, <var>latitude</var>) values for all pixels.
+ * {@link LocalizationGridBuilder} first computes a linear (affine) approximation of a localization grid, then stores the residuals.
+ * This approach works well when the residuals are small. However if the localization grid is non-linear, then the affine transform
+ * is a poor approximation of that grid and the residuals are high. High residuals make inverse transforms hard to compute, which
+ * sometime cause a {@link TransformException} with <cite>"no convergence"</cite> error message.</p>
+ *
+ * <p>In practice, localization grids in netCDF files are often used for storing the results of a map projection, e.g. Mercator.
+ * This class allows {@link LocalizationGridBuilder} to try to transform the grid using a given list of map projections and see
+ * if one of those projections results in a grid closer to an affine transform. In other words, we use this class for trying to
+ * guess what the projection may be. It is okay if the guess is not a perfect match; if the residuals become smalls enough,
+ * it will resolve the "no convergence" errors.</p>
+ * </div>
+ *
+ * @author  Martin Desruisseaux (Geomatys)
+ * @version 1.0
+ * @since   1.0
+ * @module
+ */
+final class ProjectedTransformTry implements Comparable<ProjectedTransformTry> {
+    /**
+     * Number of points in the temporary buffer used for transforming data.
+     * The buffer length will be this capacity multiplied by the number of dimensions.
+     *
+     * @see org.apache.sis.referencing.operation.transform.AbstractMathTransform#MAXIMUM_BUFFER_SIZE
+     */
+    private static final int BUFFER_CAPACITY = 512;
+
+    /**
+     * A name by witch this projection attempt is identified.
+     */
+    private String name;
+
+    /**
+     * A conversion from a non-linear grid (typically with longitude and latitude values) to
+     * something that may be more linear (typically, but not necessarily, a map projection).
+     */
+    final MathTransform projection;
+
+    /**
+     * Maps {@link #projection} dimensions to {@link LinearTransformBuilder} target dimensions.
+     * For example if this array is {@code {2,1}}, then dimensions 0 and 1 of {@code projection}
+     * map dimensions 2 and 1 of {@link LinearTransformBuilder#targets} respectively. The length
+     * of this array shall be equal to the number of {@link #projection} source dimensions.
+     */
+    private final int[] dimensions;
+
+    /**
+     * A global correlation factor, stored for information purpose only.
+     */
+    float correlation;
+
+    /**
+     * If an error occurred during coordinate operations, the error. Otherwise {@code null}.
+     */
+    private TransformException error;
+
+    /**
+     * Creates a new instance with only the given correlation coefficient. This instance can not be used for
+     * computation purpose. Its sole purpose is to hold the given coefficient when no projection is applied.
+     */
+    ProjectedTransformTry(final float corr) {
+        projection  = null;
+        dimensions  = null;
+        correlation = corr;
+    }
+
+    /**
+     * Prepares a new attempt to project a localization grid.
+     * All arguments are stored as-is (arrays are not cloned).
+     *
+     * @param name               a name by witch this projection attempt is identified, or {@code null}.
+     * @param projection         conversion from non-linear grid to something that may be more linear.
+     * @param dimensions         maps {@code projection} dimensions to {@link LinearTransformBuilder} target dimensions.
+     * @param expectedDimension  number of {@link LinearTransformBuilder} target dimensions.
+     */
+    ProjectedTransformTry(final String name, final MathTransform projection, final int[] dimensions, int expectedDimension) {
+        this.name       = name;
+        this.projection = projection;
+        this.dimensions = dimensions;
+        int side = 0;                           // 0 = problem with source dimensions, 1 = problem with target dimensions.
+        int actual = projection.getSourceDimensions();
+        if (actual <= expectedDimension) {
+            expectedDimension = dimensions.length;
+            if (actual == expectedDimension) {
+                actual = projection.getTargetDimensions();
+                if (actual == expectedDimension) {
+                    return;
+                }
+                side = 1;
+            }
+        }
+        throw new MismatchedDimensionException(Resources.format(
+                Resources.Keys.MismatchedTransformDimension_3, side, expectedDimension, actual));
+    }
+
+    /**
+     * Transforms target coordinates of a localization grid. The {@code coordinates} argument is the value
+     * of {@link LinearTransformBuilder#targets}, without clone (this method will only read those arrays).
+     * Only arrays at indices given by {@link #dimensions} will be read; the other arrays will be ignored.
+     * The coordinate operation result will be stored in arrays of size {@code [numDimensions][numPoints]}
+     * where {@code numDimensions} is the length of the {@link #dimensions} array. Indices are as below,
+     * with 0 ≦ <var>d</var> ≦ {@code numDimensions}:
+     *
+     * <ol>
+     *   <li>{@code results[d]}    contains the coordinates in dimension <var>d</var>.</li>
+     *   <li>{@code results[d][i]} is a coordinate of the point at index <var>i</var>.</li>
+     * </ol>
+     *
+     * The {@code pool} queue is initially empty. Arrays created by this method and later discarded will be added to
+     * that queue, for recycling if this method is invoked again for another {@code ProjectedTransformTry} instance.
+     *
+     * @param  coordinates  the {@link LinearTransformBuilder#targets} arrays of coordinates to transform.
+     * @param  numPoints    number of points to transform: {@code numPoints} ≦ {@code coordinates[i].length}.
+     * @param  pool         pre-allocated arrays of length {@code numPoints} that can be recycled.
+     * @return results of coordinate operations (see method javadoc), or {@code null} if an error occurred.
+     */
+    final double[][] transform(final double[][] coordinates, final int numPoints, final Queue<double[]> pool) {
+        final int numDimensions = dimensions.length;
+        final double[][] results = new double[numDimensions][];
+        for (int i=0; i<numDimensions; i++) {
+            if ((results[i] = pool.poll()) == null) {
+                results[i] = new double[numPoints];
+            }
+        }
+        /*
+         * Allocate the destination arrays for coordinates to transform as (x₀,y₀), (x₁,y₁), (x₂,y₂)… tuples.
+         * In the particular case of one-dimensional transforms (not necessarily one-dimensional coordinates)
+         * we can transform arrays directly without the need for a temporary buffer.
+         */
+        try {
+            if (numDimensions == 1) {
+                projection.transform(coordinates[dimensions[0]], 0, results[0], 0, numPoints);
+            } else {
+                final int bufferCapacity = Math.min(numPoints, BUFFER_CAPACITY);                 // In number of points.
+                final double[] buffer = new double[bufferCapacity * numDimensions];
+                int dataOffset = 0;
+                while (dataOffset < numPoints) {
+                    final int start = dataOffset;
+                    final int stop = Math.min(start + bufferCapacity, numPoints);
+                    /*
+                     * Copies coordinates in a single interleaved array before to transform them.
+                     * Coordinates start at index 0 and the number of valid points is stop - start.
+                     */
+                    for (int d=0; d<numDimensions; d++) {
+                        final double[] data = coordinates[dimensions[d]];
+                        dataOffset = start;
+                        int dst = d;
+                        do {
+                            buffer[dst] = data[dataOffset];
+                            dst += numDimensions;
+                        } while (++dataOffset < stop);
+                    }
+                    /*
+                     * Transform coordinates and save the result.
+                     */
+                    projection.transform(buffer, 0, buffer, 0, stop - start);
+                    for (int d=0; d<numDimensions; d++) {
+                        @SuppressWarnings("MismatchedReadAndWriteOfArray")
+                        final double[] data = results[d];
+                        dataOffset = start;
+                        int dst = d;
+                        do {
+                            data[dataOffset] = buffer[dst];
+                            dst += numDimensions;
+                        } while (++dataOffset < stop);
+                    }
+                }
+            }
+        } catch (TransformException e) {
+            error = e;
+            recycle(results, pool);         // Make arrays available for other transforms.
+            return null;
+        }
+        return results;
+    }
+
+    /**
+     * Makes the given arrays available for reuse by other transforms.
+     */
+    static void recycle(final double[][] arrays, final Queue<double[]> pool) {
+        if (arrays != null) {
+            pool.addAll(Arrays.asList(arrays));
+        }
+    }
+
+    /**
+     * Replaces old correlation values by new values in a copy of the given array.
+     * May return {@code newValues} directly if suitable.
+     *
+     * @param  correlations  the original correlation values. This array will not be modified.
+     * @param  newValues     correlations computed by {@link LinearTransformBuilder} for the dimensions specified at construction time.
+     * @return a copy of the given {@code correlation} array with new values overwriting the old values.
+     */
+    final double[] replace(double[] correlations, final double[] newValues) {
+        if (newValues.length == correlations.length && ArraysExt.isSequence(0, dimensions)) {
+            return newValues;
+        }
+        correlations = correlations.clone();
+        for (int j=0; j<dimensions.length; j++) {
+            correlations[dimensions[j]] = newValues[j];
+        }
+        return correlations;
+    }
+
+    /**
+     * Replaces old transform coefficients by new values in a copy of the given matrix.
+     * May return {@code newValues} directly if suitable.
+     *
+     * @param  transform  the original affine transform. This matrix will not be modified.
+     * @param  newValues  coefficients computed by {@link LinearTransformBuilder} for the dimensions specified at construction time.
+     * @return a copy of the given {@code transform} matrix with new coefficients overwriting the old values.
+     */
+    final MatrixSIS replace(MatrixSIS transform, final MatrixSIS newValues) {
+        /*
+         * The two matrices shall have the same number of columns because they were computed with
+         * LinearTransformBuilder instances having the same sources. However the two matrices may
+         * have a different number of rows since the number of target dimensions may differ.
+         */
+        assert newValues.getNumCol() == transform.getNumCol();
+        if (newValues.getNumRow() == transform.getNumRow() && ArraysExt.isSequence(0, dimensions)) {
+            return newValues;
+        }
+        transform = transform.clone();
+        for (int j=0; j<dimensions.length; j++) {
+            final int d = dimensions[j];
+            for (int i=transform.getNumRow(); --i >= 0;) {
+                transform.setNumber(d, i, newValues.getNumber(j, i));
+            }
+        }
+        return transform;
+    }
+
+    /**
+     * Order by the inverse of correlation coefficients. Highest coefficients (best correlations)
+     * are first, lower coefficients are next, {@link Float#NaN} values are last.
+     */
+    @Override
+    public int compareTo(final ProjectedTransformTry other) {
+        return Float.compare(-correlation, -other.correlation);
+    }
+
+    /**
+     * Formats a summary of this projection attempt. This method formats the following columns:
+     *
+     * <ol>
+     *   <li>The projection name.</li>
+     *   <li>The corelation coefficient, or the error message if an error occurred.</li>
+     * </ol>
+     *
+     * @param  table  the table where to write a row.
+     * @param  nf     format to use for writing coefficients, or {@code null} if not yet created.
+     * @return format used for writing coefficients, or {@code null}.
+     */
+    final NumberFormat summarize(final TableAppender table, NumberFormat nf) {
+        if (name == null) {
+            name = Vocabulary.format(projection == null ? Vocabulary.Keys.Identity : Vocabulary.Keys.Unnamed);
+        }
+        table.append(name).nextColumn();
+        String message = "";
+        if (error != null) {
+            message = error.getMessage();
+            if (message == null) {
+                message = error.getClass().getSimpleName();
+            }
+        } else if (correlation > 0) {
+            if (nf == null) {
+                nf = NumberFormat.getInstance();
+                nf.setMinimumFractionDigits(6);         // Math.ulp(1f) ≈ 1.2E-7
+                nf.setMaximumFractionDigits(6);
+            }
+            message = nf.format(correlation);
+        }
+        table.append(message).nextLine();
+        return nf;
+    }
+
+    /**
+     * Returns a string representation of this projection attempt for debugging purpose.
+     */
+    @Override
+    public String toString() {
+        final TableAppender buffer = new TableAppender("  ");
+        summarize(buffer, null);
+        return buffer.toString();
+    }
+}
diff --git a/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/builder/TransformBuilder.java b/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/builder/TransformBuilder.java
index ef621d7..3a60ed1 100644
--- a/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/builder/TransformBuilder.java
+++ b/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/builder/TransformBuilder.java
@@ -28,6 +28,9 @@ import org.apache.sis.referencing.operation.transform.DefaultMathTransformFactor
  * The transform may be a linear approximation the minimize the errors in a <cite>least square</cite> sense,
  * or a more accurate transform using a localization grid.
  *
+ * <p>Builders can be used only once;
+ * points can not be added or modified after {@link #create(MathTransformFactory)} has been invoked.</p>
+ *
  * @author  Martin Desruisseaux (Geomatys)
  * @version 0.8
  * @since   0.8
@@ -42,6 +45,9 @@ public abstract class TransformBuilder {
 
     /**
      * Creates a transform from the source points to the target points.
+     * Invoking this method puts the builder in an unmodifiable state.
+     * Invoking this method more than once returns the same transform
+     * (the transform is not recomputed).
      *
      * @param  factory  the factory to use for creating the transform, or {@code null} for the default factory.
      * @return the transform from source to target points.
diff --git a/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/transform/AbstractMathTransform.java b/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/transform/AbstractMathTransform.java
index 3ac113d..5664883 100644
--- a/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/transform/AbstractMathTransform.java
+++ b/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/transform/AbstractMathTransform.java
@@ -581,7 +581,7 @@ public abstract class AbstractMathTransform extends FormattableObject
             } catch (TransformException exception) {
                 /*
                  * If an exception occurred but the transform nevertheless declares having been
-                 * able to process all coordinate points (setting to NaN those that can't be
+                 * able to process all coordinate points (setting to NaN those that can not be
                  * transformed), we will keep the first exception (to be propagated at the end
                  * of this method) and continue. Otherwise we will stop immediately.
                  */
diff --git a/core/sis-referencing/src/test/java/org/apache/sis/referencing/operation/builder/LinearTransformBuilderTest.java b/core/sis-referencing/src/test/java/org/apache/sis/referencing/operation/builder/LinearTransformBuilderTest.java
index 1deb313..582eaa1 100644
--- a/core/sis-referencing/src/test/java/org/apache/sis/referencing/operation/builder/LinearTransformBuilderTest.java
+++ b/core/sis-referencing/src/test/java/org/apache/sis/referencing/operation/builder/LinearTransformBuilderTest.java
@@ -19,9 +19,12 @@ package org.apache.sis.referencing.operation.builder;
 import java.util.Map;
 import java.util.HashMap;
 import java.util.Random;
+import java.util.Collections;
 import java.awt.geom.AffineTransform;
 import org.opengis.util.FactoryException;
+import org.opengis.geometry.DirectPosition;
 import org.opengis.referencing.operation.Matrix;
+import org.apache.sis.referencing.operation.matrix.Matrix3;
 import org.apache.sis.geometry.DirectPosition1D;
 import org.apache.sis.geometry.DirectPosition2D;
 import org.apache.sis.test.DependsOnMethod;
@@ -30,7 +33,6 @@ import org.apache.sis.test.TestCase;
 import org.junit.Test;
 
 import static org.apache.sis.test.Assert.*;
-import org.opengis.geometry.DirectPosition;
 
 
 /**
@@ -406,4 +408,37 @@ public final strictfp class LinearTransformBuilderTest extends TestCase {
         assertTrue (actual.containsValue(t00));
         assertMapEquals(expected, actual);
     }
+
+    /**
+     * Tests the effect of {@link LinearTransformBuilder#addLinearizers(Map, int...)}.
+     *
+     * @throws FactoryException if the transform can not be created.
+     */
+    @Test
+    public void testLinearizers() throws FactoryException {
+        final int width  = 3;
+        final int height = 4;
+        final LinearTransformBuilder builder = new LinearTransformBuilder(width, height);
+        for (int y=0; y<height; y++) {
+            final int[]    source = new int[2];
+            final double[] target = new double[2];
+            for (int x=0; x<width; x++) {
+                source[0] = x;
+                source[1] = y;
+                target[0] = StrictMath.cbrt(3 + x*2);
+                target[1] = StrictMath.sqrt(1 + y);
+                builder.setControlPoint(source, target);
+            }
+        }
+        final NonLinearTransform x2y3 = new NonLinearTransform();
+        final NonLinearTransform x3y2 = new NonLinearTransform();
+        builder.addLinearizers(Collections.singletonMap("x² y³", x2y3));
+        builder.addLinearizers(Collections.singletonMap("x³ y²", x3y2), 1, 0);
+        final Matrix m = builder.create(null).getMatrix();
+        assertSame("linearizer", x3y2, builder.linearizer().get());
+        assertMatrixEquals("linear",
+                new Matrix3(2, 0, 3,
+                            0, 1, 1,
+                            0, 0, 1), m, 1E-15);
+    }
 }
diff --git a/core/sis-referencing/src/test/java/org/apache/sis/referencing/operation/builder/NonLinearTransform.java b/core/sis-referencing/src/test/java/org/apache/sis/referencing/operation/builder/NonLinearTransform.java
new file mode 100644
index 0000000..4dea19b
--- /dev/null
+++ b/core/sis-referencing/src/test/java/org/apache/sis/referencing/operation/builder/NonLinearTransform.java
@@ -0,0 +1,51 @@
+/*
+ * 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.referencing.operation.builder;
+
+import org.opengis.referencing.operation.Matrix;
+import org.apache.sis.referencing.operation.transform.AbstractMathTransform2D;
+
+
+/**
+ * A two-dimensional non-linear transform for {@link LinearTransformBuilderTest} purpose.
+ *
+ * @author  Martin Desruisseaux (Geomatys)
+ * @version 1.0
+ * @since   1.0
+ * @module
+ */
+final strictfp class NonLinearTransform extends AbstractMathTransform2D {
+    /**
+     * Creates a new instance of this class.
+     */
+    NonLinearTransform() {
+    }
+
+    /**
+     * Applies an arbitrary non-linear transform.
+     */
+    @Override
+    public Matrix transform(final double[] srcPts, int srcOff,
+                            final double[] dstPts, int dstOff, boolean derivate)
+    {
+        final double x = srcPts[srcOff++];
+        final double y = srcPts[srcOff  ];
+        dstPts[dstOff++] = x * x;
+        dstPts[dstOff  ] = y * y * y;
+        return null;
+    }
+}
diff --git a/core/sis-utility/src/main/java/org/apache/sis/internal/util/Strings.java b/core/sis-utility/src/main/java/org/apache/sis/internal/util/Strings.java
index 117dcb0..19b4cef 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/internal/util/Strings.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/internal/util/Strings.java
@@ -184,10 +184,31 @@ public final class Strings extends Static {
     }
 
     /**
+     * Inserts a continuation character after each line separator except the last one.
+     * The intent is to show that a block of lines are part of the same element.
+     * The characters are the same than {@link org.apache.sis.util.logging.MonolineFormatter}.
+     *
+     * @param buffer         the buffer where to insert a continuation character in the left margin.
+     * @param lineSeparator  the line separator.
+     */
+    public static void insertLineInLeftMargin(final StringBuilder buffer, final String lineSeparator) {
+        char c = '╹';
+        int i = CharSequences.skipTrailingWhitespaces(buffer, 0, buffer.length());
+        while ((i = buffer.lastIndexOf(lineSeparator, i - 1)) >= 0) {
+            buffer.insert(i + lineSeparator.length(), c);
+            c = '┃';
+        }
+    }
+
+    /**
      * Returns a string representation of an instance of the given class having the given properties.
      * This is a convenience method for implementation of {@link Object#toString()} methods that are
      * used mostly for debugging purpose.
      *
+     * <p>The content is specified by (<var>key</var>=<var>value</var>) pairs. If a value is {@code null},
+     * the whole entry is omitted. If a key is {@code null}, the value is written without the {@code "key="}
+     * part. The later happens typically when the first value is the object name.</p>
+     *
      * @param  classe      the class to format.
      * @param  properties  the (<var>key</var>=<var>value</var>) pairs.
      * @return a string representation of an instance of the given class having the given properties.
@@ -201,7 +222,10 @@ public final class Strings extends Static {
                 if (isNext) {
                     buffer.append(", ");
                 }
-                buffer.append(properties[i-1]).append('=');
+                final Object name = properties[i-1];
+                if (name != null) {
+                    buffer.append(name).append('=');
+                }
                 final boolean isText = (value instanceof CharSequence);
                 if (isText) buffer.append('“');
                 buffer.append(value);
diff --git a/core/sis-utility/src/main/java/org/apache/sis/math/Plane.java b/core/sis-utility/src/main/java/org/apache/sis/math/Plane.java
index 1dd05ae..e8e6b2e 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/math/Plane.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/math/Plane.java
@@ -242,6 +242,7 @@ public class Plane implements Cloneable, Serializable {
      * @param  y  vector of <var>y</var> coordinates.
      * @param  z  vector of <var>z</var> values.
      * @return an estimation of the Pearson correlation coefficient.
+     *         The closer this coefficient is to +1 or -1, the better the fit.
      * @throws IllegalArgumentException if <var>x</var>, <var>y</var> and <var>z</var> do not have the same length.
      */
     public double fit(final double[] x, final double[] y, final double[] z) {
@@ -263,6 +264,7 @@ public class Plane implements Cloneable, Serializable {
      * @param  y  vector of <var>y</var> coordinates.
      * @param  z  vector of <var>z</var> values.
      * @return an estimation of the Pearson correlation coefficient.
+     *         The closer this coefficient is to +1 or -1, the better the fit.
      * @throws IllegalArgumentException if <var>x</var>, <var>y</var> and <var>z</var> do not have the same length.
      *
      * @since 0.8
@@ -311,6 +313,7 @@ public class Plane implements Cloneable, Serializable {
      * @param  ny  number of rows.
      * @param  z   values of a matrix of {@code nx} columns by {@code ny} rows organized in a row-major fashion.
      * @return an estimation of the Pearson correlation coefficient.
+     *         The closer this coefficient is to +1 or -1, the better the fit.
      * @throws IllegalArgumentException if <var>z</var> does not have the expected length or if a <var>z</var>
      *         value is {@link Double#NaN}.
      *
@@ -340,6 +343,7 @@ public class Plane implements Cloneable, Serializable {
      *
      * @param  points  the three-dimensional points.
      * @return an estimation of the Pearson correlation coefficient.
+     *         The closer this coefficient is to +1 or -1, the better the fit.
      * @throws MismatchedDimensionException if a point is not three-dimensional.
      */
     public double fit(final Iterable<? extends DirectPosition> points) {
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/ArraysExt.java b/core/sis-utility/src/main/java/org/apache/sis/util/ArraysExt.java
index a6dd7a7..26079ae 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/ArraysExt.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/ArraysExt.java
@@ -1259,7 +1259,7 @@ public final class ArraysExt extends Static {
     }
 
     /**
-     * Returns a finite arithmetic progression of the given length. Each value is increased by 1.
+     * Returns a finite arithmetic progression of the given length and common difference of 1.
      * For example {@code sequence(-1, 4)} returns {@code {-1, 0, 1, 2}}.
      *
      * <div class="note"><b>Purpose:</b>
@@ -1302,7 +1302,8 @@ public final class ArraysExt extends Static {
     }
 
     /**
-     * Returns {@code true} if the given array is a finite arithmetic progression starting at the given value.
+     * Returns {@code true} if the given array is a finite arithmetic progression starting at the given value
+     * and having a common difference of 1.
      * More specifically:
      *
      * <ul>
@@ -1318,6 +1319,9 @@ public final class ArraysExt extends Static {
      * {@code isSequence(1, array)} returns {@code true} if the given array is {@code {1, 2, 3, 4}}
      * but {@code false} if the array is {@code {1, 2, 4}} (missing 3).</div>
      *
+     * This method is useful when {@code array} is an argument specified to another method, and determining that the
+     * argument values are {@code start}, {@code start}+1, {@code start}+2, <i>etc.</i> allows some optimizations.
+     *
      * @param  start  first value expected in the given {@code array}.
      * @param  array  the array to test, or {@code null}.
      * @return {@code true} if the given array is non-null and equal to
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Vocabulary.java b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Vocabulary.java
index 5f20a54..c3f14cf 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Vocabulary.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Vocabulary.java
@@ -682,6 +682,11 @@ public final class Vocabulary extends IndexedResourceBundle {
         public static final short Resolution = 153;
 
         /**
+         * Result
+         */
+        public static final short Result = 164;
+
+        /**
          * Root
          */
         public static final short Root = 90;
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Vocabulary.properties b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Vocabulary.properties
index b3ff71a..e5c62c0 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Vocabulary.properties
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Vocabulary.properties
@@ -139,6 +139,7 @@ Remarks                 = Remarks
 RemoteConfiguration     = Remote configuration
 RepresentativeValue     = Representative value
 Resolution              = Resolution
+Result                  = Result
 Root                    = Root
 RootMeanSquare          = Root Mean Square
 SampleDimensions        = Sample dimensions
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Vocabulary_fr.properties b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Vocabulary_fr.properties
index 5c4f7d5..30d2755 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Vocabulary_fr.properties
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Vocabulary_fr.properties
@@ -146,6 +146,7 @@ Remarks                 = Remarques
 RemoteConfiguration     = Configuration distante
 RepresentativeValue     = Valeur repr\u00e9sentative
 Resolution              = R\u00e9solution
+Result                  = R\u00e9sultat
 Root                    = Racine
 RootMeanSquare          = Moyenne quadratique
 SampleDimensions        = Dimensions d\u2019\u00e9chantillonnage
diff --git a/ide-project/NetBeans/nbproject/genfiles.properties b/ide-project/NetBeans/nbproject/genfiles.properties
index ec9b777..35088b0 100644
--- a/ide-project/NetBeans/nbproject/genfiles.properties
+++ b/ide-project/NetBeans/nbproject/genfiles.properties
@@ -3,6 +3,6 @@
 build.xml.data.CRC32=58e6b21c
 build.xml.script.CRC32=462eaba0
 build.xml.stylesheet.CRC32=28e38971@1.53.1.46
-nbproject/build-impl.xml.data.CRC32=80e7865b
+nbproject/build-impl.xml.data.CRC32=6673fb19
 nbproject/build-impl.xml.script.CRC32=a7689f96
 nbproject/build-impl.xml.stylesheet.CRC32=3a2fa800@1.89.1.48
diff --git a/ide-project/NetBeans/nbproject/project.xml b/ide-project/NetBeans/nbproject/project.xml
index 3d5b601..e24aedb 100644
--- a/ide-project/NetBeans/nbproject/project.xml
+++ b/ide-project/NetBeans/nbproject/project.xml
@@ -99,6 +99,8 @@
             <word>initially</word>
             <word>javadoc</word>
             <word>kilometre</word>
+            <word>linearizer</word>
+            <word>linearizers</word>
             <word>loggings</word>
             <word>maintainance</word>
             <word>marshallable</word>


[sis] 04/05: Tests against some integer overflows.

Posted by de...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

desruisseaux pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git

commit 141af4766b5317672ee530c0ad1deb6ec6302611
Author: Martin Desruisseaux <ma...@geomatys.com>
AuthorDate: Fri Mar 8 15:06:54 2019 +0100

    Tests against some integer overflows.
---
 .../org/apache/sis/coverage/grid/GridExtent.java   |  4 +-
 .../main/java/org/apache/sis/math/ArrayVector.java |  8 +--
 .../main/java/org/apache/sis/math/Fraction.java    |  7 +-
 .../src/main/java/org/apache/sis/math/Vector.java  |  2 +-
 .../main/java/org/apache/sis/util/ArraysExt.java   | 82 ++++++++++++++++++++--
 .../java/org/apache/sis/util/resources/Errors.java |  5 ++
 .../apache/sis/util/resources/Errors.properties    |  1 +
 .../apache/sis/util/resources/Errors_fr.properties |  1 +
 .../java/org/apache/sis/util/ArraysExtTest.java    | 19 +++++
 .../java/org/apache/sis/internal/netcdf/Axis.java  |  2 +-
 .../org/apache/sis/internal/netcdf/CRSBuilder.java |  2 +-
 .../org/apache/sis/internal/netcdf/Variable.java   | 11 ++-
 12 files changed, 125 insertions(+), 19 deletions(-)

diff --git a/core/sis-raster/src/main/java/org/apache/sis/coverage/grid/GridExtent.java b/core/sis-raster/src/main/java/org/apache/sis/coverage/grid/GridExtent.java
index d16598b..2dd3bf1 100644
--- a/core/sis-raster/src/main/java/org/apache/sis/coverage/grid/GridExtent.java
+++ b/core/sis-raster/src/main/java/org/apache/sis/coverage/grid/GridExtent.java
@@ -995,7 +995,9 @@ public class GridExtent implements Serializable {
                 final int j = i + m;
                 long low  = coordinates[i];
                 long size = coordinates[j] - low + 1;                                             // Result is an unsigned number.
-                if (size == 0) throw new ArithmeticException("long overflow");
+                if (size == 0) {
+                    throw new ArithmeticException(Errors.format(Errors.Keys.IntegerOverflow_1, Long.SIZE));
+                }
                 long r = Long.divideUnsigned(size, s);
                 if (r*s == size) r--;                           // Make inclusive if the division did not already rounded toward 0.
                 sub.coordinates[i] = low /= s;
diff --git a/core/sis-utility/src/main/java/org/apache/sis/math/ArrayVector.java b/core/sis-utility/src/main/java/org/apache/sis/math/ArrayVector.java
index d5dd4a2..8f66146 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/math/ArrayVector.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/math/ArrayVector.java
@@ -919,7 +919,7 @@ abstract class ArrayVector<E extends Number> extends Vector implements CheckedCo
         @Override public long longValue(final int index) {
             final long value = super.longValue(index);
             if (value >= 0) return value;
-            throw new ArithmeticException();
+            throw new ArithmeticException(Errors.format(Errors.Keys.IntegerOverflow_1, Long.SIZE));
         }
 
         /** Returns the string representation at the given index. */
@@ -960,7 +960,7 @@ abstract class ArrayVector<E extends Number> extends Vector implements CheckedCo
         @Override public int       intValue(int index) {
             final int value = super.intValue(index);
             if (value >= 0) return value;
-            throw new ArithmeticException();
+            throw new ArithmeticException(Errors.format(Errors.Keys.IntegerOverflow_1, Integer.SIZE));
         }
 
         /** Uses a larger type if the value exceed integer capacity. */
@@ -1016,7 +1016,7 @@ abstract class ArrayVector<E extends Number> extends Vector implements CheckedCo
         @Override public short   shortValue(int index) {
             final short value = super.shortValue(index);
             if (value >= 0) return value;
-            throw new ArithmeticException();
+            throw new ArithmeticException(Errors.format(Errors.Keys.IntegerOverflow_1, Short.SIZE));
         }
 
         /** Uses a larger type if the value exceed short integer capacity. */
@@ -1073,7 +1073,7 @@ abstract class ArrayVector<E extends Number> extends Vector implements CheckedCo
         @Override public byte     byteValue(int index) {
             final byte value = super.byteValue(index);
             if (value >= 0) return value;
-            throw new ArithmeticException();
+            throw new ArithmeticException(Errors.format(Errors.Keys.IntegerOverflow_1, Byte.SIZE));
         }
 
         /** Uses a larger type if the value exceed integer capacity. */
diff --git a/core/sis-utility/src/main/java/org/apache/sis/math/Fraction.java b/core/sis-utility/src/main/java/org/apache/sis/math/Fraction.java
index 92846f5..e33eb30 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/math/Fraction.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/math/Fraction.java
@@ -18,6 +18,7 @@ package org.apache.sis.math;
 
 import java.io.Serializable;
 import org.apache.sis.util.ArgumentChecks;
+import org.apache.sis.util.resources.Errors;
 import org.apache.sis.util.collection.WeakHashSet;
 
 
@@ -115,7 +116,7 @@ public final class Fraction extends Number implements Comparable<Fraction>, Seri
      */
     private Fraction simplify(long num, long den) {
         if (num == Long.MIN_VALUE || den == Long.MIN_VALUE) {
-            throw new ArithmeticException();
+            throw new ArithmeticException(Errors.format(Errors.Keys.IntegerOverflow_1, Long.SIZE));
         }
         if (num == 0) {
             den = Long.signum(den);             // Simplify  0/x  as  0/±1 or 0/0.
@@ -357,7 +358,7 @@ public final class Fraction extends Number implements Comparable<Fraction>, Seri
     public short shortValue() {
         final int n = intValue();
         if ((n & ~0xFFFF) == 0) return (short) n;
-        throw new ArithmeticException();
+        throw new ArithmeticException(Errors.format(Errors.Keys.IntegerOverflow_1, Short.SIZE));
     }
 
     /**
@@ -370,7 +371,7 @@ public final class Fraction extends Number implements Comparable<Fraction>, Seri
     public byte byteValue() {
         final int n = intValue();
         if ((n & ~0xFF) == 0) return (byte) n;
-        throw new ArithmeticException();
+        throw new ArithmeticException(Errors.format(Errors.Keys.IntegerOverflow_1, Byte.SIZE));
     }
 
     /**
diff --git a/core/sis-utility/src/main/java/org/apache/sis/math/Vector.java b/core/sis-utility/src/main/java/org/apache/sis/math/Vector.java
index f25ed0d..abce606 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/math/Vector.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/math/Vector.java
@@ -687,7 +687,7 @@ search:     for (;;) {
         final long inc = a - b;
         // The sign of the difference shall be the same than the sign of Long.compare(…).
         if ((((isUnsigned() ? Long.compareUnsigned(a, b) : Long.compare(a, b)) ^ inc) & Long.MIN_VALUE) != 0) {
-            throw new ArithmeticException();
+            throw new ArithmeticException(Errors.format(Errors.Keys.IntegerOverflow_1, Long.SIZE));
         }
         return inc;
     }
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/ArraysExt.java b/core/sis-utility/src/main/java/org/apache/sis/util/ArraysExt.java
index 51c80b0..a6dd7a7 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/ArraysExt.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/ArraysExt.java
@@ -20,6 +20,7 @@ import java.util.Arrays;
 import java.util.Objects;
 import java.util.Comparator;
 import java.lang.reflect.Array;
+import org.apache.sis.util.resources.Errors;
 
 
 /**
@@ -1258,22 +1259,89 @@ public final class ArraysExt extends Static {
     }
 
     /**
-     * Returns a sequence of increasing values of the given length. Each value is increased by 1.
-     * For example {@code sequence(-1, 4)} returns {@code {-1, 0, 1, 2}}. This method is a convenience for
-     * enumerating a subset of dimensions in a coordinate reference system or a subset of bands in an image.
+     * Returns a finite arithmetic progression of the given length. Each value is increased by 1.
+     * For example {@code sequence(-1, 4)} returns {@code {-1, 0, 1, 2}}.
+     *
+     * <div class="note"><b>Purpose:</b>
+     * this method is convenient for enumerating dimensions in a coordinate reference system or bands in an image.
+     * Some methods in the Java library or in Apache SIS want dimensions or bands to be specified by their indices.
+     * An example in the Java library is the {@code bankIndices} argument in
+     * <code>{@linkplain java.awt.image.Raster#createBandedRaster(int, int, int, int, int[], int[], java.awt.Point)
+     * Raster.createBandedRaster}(…, bankIndices, …)</code>.
+     * An example in Apache SIS is the {@code range} argument in
+     * <code>{@linkplain org.apache.sis.storage.GridCoverageResource#read GridCoverageResource.read}(…, range)</code>.</div>
+     *
+     * For any array returned by this method, <code>{@linkplain #isSequence(int, int[]) isSequence}(start, array)</code>
+     * is guaranteed to return {@code true}.
      *
      * @param  start   first value in the array to return.
      * @param  length  number of values to return.
      * @return a sequence of increasing integers starting at {@code start} and having {@code length} values.
+     * @throws ArithmeticException if {@code start + length} overflows 32 bits integer.
+     *
+     * @see java.util.stream.IntStream#range(int, int)
      *
      * @since 1.0
      */
     public static int[] sequence(final int start, final int length) {
-        final int[] array = new int[length];
-        for (int i=0; i<length; i++) {
-            array[i] = start + i;
+        if (length > 0) {
+            if (start + (length - 1) >= start) {
+                final int[] array = new int[length];
+                for (int i=0; i<length; i++) {
+                    array[i] = start + i;
+                }
+                return array;
+            } else {
+                throw new ArithmeticException(Errors.format(Errors.Keys.IntegerOverflow_1, Integer.SIZE));
+            }
+        } else if (length == 0) {
+            return EMPTY_INT;
+        } else {
+            throw new NegativeArraySizeException(Errors.format(Errors.Keys.NegativeArgument_2, "length", length));
         }
-        return array;
+    }
+
+    /**
+     * Returns {@code true} if the given array is a finite arithmetic progression starting at the given value.
+     * More specifically:
+     *
+     * <ul>
+     *   <li>If {@code array} is {@code null}, then return {@code false}.</li>
+     *   <li>Otherwise if {@code array} is empty, then return {@code true} for consistency
+     *       with <code>{@linkplain #sequence(int, int) sequence}(start, 0)</code>.</li>
+     *   <li>Otherwise for any index 0 ≦ <var>i</var> {@literal <} {@code array.length}, if {@code array[i]}
+     *       is equal to {@code start + i} (computed as if no overflow occurs), then return {@code true}.</li>
+     *   <li>Otherwise return {@code false}.</li>
+     * </ul>
+     *
+     * <div class="note"><b>Example:</b>
+     * {@code isSequence(1, array)} returns {@code true} if the given array is {@code {1, 2, 3, 4}}
+     * but {@code false} if the array is {@code {1, 2, 4}} (missing 3).</div>
+     *
+     * @param  start  first value expected in the given {@code array}.
+     * @param  array  the array to test, or {@code null}.
+     * @return {@code true} if the given array is non-null and equal to
+     *         <code>{@linkplain #sequence(int, int) sequence}(start, array.length)</code>.
+     *
+     * @see #sequence(int, int)
+     *
+     * @since 1.0
+     */
+    public static boolean isSequence(final int start, final int[] array) {
+        if (array == null) {
+            return false;
+        }
+        if (array.length != 0) {
+            if (start + (array.length - 1) < start) {
+                return false;                               // Overflow.
+            }
+            for (int i=0; i<array.length; i++) {
+                if (array[i] != start + i) {
+                    return false;
+                }
+            }
+        }
+        return true;
     }
 
     /**
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java
index 7ca6176..52589b4 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java
@@ -489,6 +489,11 @@ public final class Errors extends IndexedResourceBundle {
         public static final short InfiniteArgumentValue_1 = 73;
 
         /**
+         * Integer overflow during {0} bits arithmetic operation.
+         */
+        public static final short IntegerOverflow_1 = 188;
+
+        /**
          * “{0}” is an invalid version identifier.
          */
         public static final short InvalidVersionIdentifier_1 = 179;
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties
index 75be8f1..6007f78 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties
@@ -108,6 +108,7 @@ InconsistentUnitsForCS_1          = Unit of measurement \u201c{0}\u201d is incon
 IndexOutOfBounds_1                = Index {0} is out of bounds.
 IndicesOutOfBounds_2              = Indices ({0}, {1}) are out of bounds.
 InfiniteArgumentValue_1           = Argument \u2018{0}\u2019 can not take an infinite value.
+IntegerOverflow_1                 = Integer overflow during {0} bits arithmetic operation.
 InvalidVersionIdentifier_1        = \u201c{0}\u201d is an invalid version identifier.
 KeyCollision_1                    = Key \u201c{0}\u201d is associated twice to different values.
 MandatoryAttribute_2              = Attribute \u201c{0}\u201d is mandatory for an object of type \u2018{1}\u2019.
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties
index f87e89b..fe58d55 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties
@@ -105,6 +105,7 @@ InconsistentUnitsForCS_1          = L\u2019unit\u00e9 de mesure \u00ab\u202f{0}\
 IndexOutOfBounds_1                = L\u2019index {0} est en dehors des limites permises.
 IndicesOutOfBounds_2              = Les index ({0}, {1}) sont en dehors des limites permises.
 InfiniteArgumentValue_1           = L\u2019argument \u2018{0}\u2019 ne peut pas prendre une valeur infinie.
+IntegerOverflow_1                 = D\u00e9passement d\u2019entier lors d\u2019une op\u00e9ration arithm\u00e9tique sur {0} bits.
 InvalidVersionIdentifier_1        = \u00ab\u202f{0}\u202f\u00bb n\u2019est pas un identifiant de version valide.
 KeyCollision_1                    = La cl\u00e9 \u00ab\u202f{0}\u202f\u00bb est associ\u00e9e deux fois \u00e0 des valeurs diff\u00e9rentes.
 MandatoryAttribute_2              = L\u2019attribut \u00ab\u202f{0}\u202f\u00bb est obligatoire pour un objet de type \u2018{1}\u2019.
diff --git a/core/sis-utility/src/test/java/org/apache/sis/util/ArraysExtTest.java b/core/sis-utility/src/test/java/org/apache/sis/util/ArraysExtTest.java
index 295eb80..df015a2 100644
--- a/core/sis-utility/src/test/java/org/apache/sis/util/ArraysExtTest.java
+++ b/core/sis-utility/src/test/java/org/apache/sis/util/ArraysExtTest.java
@@ -58,6 +58,25 @@ public final strictfp class ArraysExtTest extends TestCase {
     }
 
     /**
+     * Tests {@link ArraysExt#sequence(int, int)} and {@link ArraysExt#isSequence(int, int[])}.
+     */
+    @Test
+    public void testSequence() {
+        int[] sequence = ArraysExt.sequence(-1, 4);
+        assertArrayEquals("sequence", new int[] {-1, 0, 1, 2}, sequence);
+        assertTrue ("isSequence", ArraysExt.isSequence(-1, sequence));
+        assertFalse("isSequence", ArraysExt.isSequence(-2, sequence));
+        assertTrue ("isSequence", ArraysExt.isSequence(1, new int[] {1, 2, 3, 4}));
+        assertFalse("isSequence", ArraysExt.isSequence(1, new int[] {1, 2,    4}));
+        try {
+            ArraysExt.sequence(Integer.MAX_VALUE - 10, 12);
+            fail("Expected ArithmeticException.");
+        } catch (ArithmeticException e) {
+            assertNotNull(e.getMessage());
+        }
+    }
+
+    /**
      * Tests {@link ArraysExt#unionOfSorted(int[], int[])}.
      */
     @Test
diff --git a/storage/sis-netcdf/src/main/java/org/apache/sis/internal/netcdf/Axis.java b/storage/sis-netcdf/src/main/java/org/apache/sis/internal/netcdf/Axis.java
index 84879da..9f24ba7 100644
--- a/storage/sis-netcdf/src/main/java/org/apache/sis/internal/netcdf/Axis.java
+++ b/storage/sis-netcdf/src/main/java/org/apache/sis/internal/netcdf/Axis.java
@@ -349,7 +349,7 @@ public final class Axis extends NamedElement {
     private int getSize(final int i) {
         final int n = sourceSizes[i];
         if (n >= 0) return n;
-        throw new ArithmeticException("signed integer overflow");
+        throw new ArithmeticException(coordinates.errors().getString(Errors.Keys.IntegerOverflow_1, Integer.SIZE));
     }
 
     /**
diff --git a/storage/sis-netcdf/src/main/java/org/apache/sis/internal/netcdf/CRSBuilder.java b/storage/sis-netcdf/src/main/java/org/apache/sis/internal/netcdf/CRSBuilder.java
index a2367f4..4c2579a 100644
--- a/storage/sis-netcdf/src/main/java/org/apache/sis/internal/netcdf/CRSBuilder.java
+++ b/storage/sis-netcdf/src/main/java/org/apache/sis/internal/netcdf/CRSBuilder.java
@@ -235,7 +235,7 @@ previous:   for (int i=components.size(); --i >= 0;) {
      */
     private void add(final Axis axis) throws DataStoreContentException {
         if (dimension == Byte.MAX_VALUE) {
-            throw new DataStoreContentException(Errors.getResources(getFirstAxis().coordinates.getLocale())
+            throw new DataStoreContentException(getFirstAxis().coordinates.errors()
                     .getString(Errors.Keys.ExcessiveListSize_2, "axes", (short) (Byte.MAX_VALUE + 1)));
         }
         if (dimension >= axes.length) {
diff --git a/storage/sis-netcdf/src/main/java/org/apache/sis/internal/netcdf/Variable.java b/storage/sis-netcdf/src/main/java/org/apache/sis/internal/netcdf/Variable.java
index 1438698..19f7d4a 100644
--- a/storage/sis-netcdf/src/main/java/org/apache/sis/internal/netcdf/Variable.java
+++ b/storage/sis-netcdf/src/main/java/org/apache/sis/internal/netcdf/Variable.java
@@ -882,6 +882,15 @@ public abstract class Variable extends NamedElement {
     }
 
     /**
+     * Returns the resources to use for error messages.
+     *
+     * @return the resources for error messages using the locales specified to the decoder.
+     */
+    final Errors errors() {
+        return Errors.getResources(getLocale());
+    }
+
+    /**
      * Reports a warning to the listeners specified at construction time.
      * This method is for Apache SIS internal purpose only since resources may change at any time.
      *
@@ -904,7 +913,7 @@ public abstract class Variable extends NamedElement {
      * @param  arguments  values to be formatted in the {@link java.text.MessageFormat} pattern.
      */
     final void error(final Class<?> caller, final String method, final Exception exception, final short key, final Object... arguments) {
-        warning(decoder.listeners, caller, method, exception, Errors.getResources(getLocale()), key, arguments);
+        warning(decoder.listeners, caller, method, exception, errors(), key, arguments);
     }
 
     /**


[sis] 03/05: Consolidation of error messages related to duplicated values or key collision. Addition of an ArgumentChecks.ensureNonEmpty(…) method which also check against duplicated values.

Posted by de...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

desruisseaux pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git

commit 4e26b7959320332e4065c8a39014248c029db19a
Author: Martin Desruisseaux <ma...@geomatys.com>
AuthorDate: Tue Mar 5 19:14:39 2019 +0100

    Consolidation of error messages related to duplicated values or key collision.
    Addition of an ArgumentChecks.ensureNonEmpty(…) method which also check against duplicated values.
---
 .../org/apache/sis/feature/NamedFeatureType.java   |  3 +-
 .../apache/sis/internal/simple/SimpleCitation.java |  3 +-
 .../apache/sis/internal/simple/SimpleFormat.java   |  3 +-
 .../apache/sis/io/wkt/GeodeticObjectParser.java    |  3 +-
 .../metadata/iso/identification/OperationName.java |  3 +-
 .../apache/sis/util/iso/DefaultRecordSchema.java   |  3 +-
 .../src/main/java/org/apache/sis/xml/Pooled.java   |  3 +-
 .../org/apache/sis/coverage/grid/GridExtent.java   |  7 +-
 .../sis/internal/referencing/provider/NTv2.java    |  2 +-
 .../org/apache/sis/parameter/TensorParameters.java | 11 ++-
 .../sis/parameter/UninitializedParameter.java      |  3 +-
 .../factory/sql/InstallationScriptProvider.java    |  4 +-
 .../apache/sis/referencing/operation/CRSPair.java  |  3 +-
 .../java/org/apache/sis/util/ArgumentChecks.java   | 82 ++++++++++++++++++++++
 .../src/main/java/org/apache/sis/util/Version.java |  5 +-
 .../sis/util/collection/DefaultTreeTable.java      |  5 +-
 .../sis/util/collection/TreeTableFormat.java       |  4 +-
 .../java/org/apache/sis/util/resources/Errors.java | 12 +++-
 .../apache/sis/util/resources/Errors.properties    |  4 +-
 .../apache/sis/util/resources/Errors_fr.properties | 10 +--
 .../org/apache/sis/internal/util/CitationMock.java |  2 +-
 .../org/apache/sis/util/ArgumentChecksTest.java    | 16 ++++-
 .../org/apache/sis/storage/gdal/Proj4Parser.java   |  2 +-
 .../apache/sis/internal/netcdf/NamedElement.java   |  3 +-
 24 files changed, 150 insertions(+), 46 deletions(-)

diff --git a/core/sis-feature/src/main/java/org/apache/sis/feature/NamedFeatureType.java b/core/sis-feature/src/main/java/org/apache/sis/feature/NamedFeatureType.java
index 0caa7cc..6255513 100644
--- a/core/sis-feature/src/main/java/org/apache/sis/feature/NamedFeatureType.java
+++ b/core/sis-feature/src/main/java/org/apache/sis/feature/NamedFeatureType.java
@@ -27,6 +27,7 @@ import org.opengis.feature.PropertyNotFoundException;
 import org.opengis.feature.FeatureInstantiationException;
 import org.opengis.util.GenericName;
 import org.opengis.util.InternationalString;
+import org.apache.sis.internal.util.Strings;
 import org.apache.sis.internal.feature.Resources;
 
 
@@ -150,6 +151,6 @@ final class NamedFeatureType implements FeatureType, Serializable {
      */
     @Override
     public String toString() {
-        return "FeatureType[“" + name + "”]";
+        return Strings.bracket("FeatureType", name);
     }
 }
diff --git a/core/sis-metadata/src/main/java/org/apache/sis/internal/simple/SimpleCitation.java b/core/sis-metadata/src/main/java/org/apache/sis/internal/simple/SimpleCitation.java
index 04fdeec..4b43b97 100644
--- a/core/sis-metadata/src/main/java/org/apache/sis/internal/simple/SimpleCitation.java
+++ b/core/sis-metadata/src/main/java/org/apache/sis/internal/simple/SimpleCitation.java
@@ -31,6 +31,7 @@ import org.opengis.metadata.citation.Series;
 import org.opengis.metadata.identification.BrowseGraphic;
 import org.opengis.util.InternationalString;
 import org.apache.sis.util.iso.SimpleInternationalString;
+import org.apache.sis.internal.util.Strings;
 
 
 /**
@@ -126,6 +127,6 @@ public class SimpleCitation implements Citation, Serializable {
      */
     @Override
     public String toString() {
-        return "Citation[“" + title + "”]";
+        return Strings.bracket("Citation", title);
     }
 }
diff --git a/core/sis-metadata/src/main/java/org/apache/sis/internal/simple/SimpleFormat.java b/core/sis-metadata/src/main/java/org/apache/sis/internal/simple/SimpleFormat.java
index 3e68625..9b61b93 100644
--- a/core/sis-metadata/src/main/java/org/apache/sis/internal/simple/SimpleFormat.java
+++ b/core/sis-metadata/src/main/java/org/apache/sis/internal/simple/SimpleFormat.java
@@ -23,6 +23,7 @@ import org.opengis.metadata.citation.Citation;
 import org.opengis.metadata.distribution.Distributor;
 import org.opengis.metadata.distribution.Format;
 import org.opengis.metadata.distribution.Medium;
+import org.apache.sis.internal.util.Strings;
 
 
 /**
@@ -158,6 +159,6 @@ public class SimpleFormat extends SimpleCitation implements Format {
      */
     @Override
     public String toString() {
-        return "Format[“" + title + "”]";
+        return Strings.bracket("Format", title);
     }
 }
diff --git a/core/sis-metadata/src/main/java/org/apache/sis/io/wkt/GeodeticObjectParser.java b/core/sis-metadata/src/main/java/org/apache/sis/io/wkt/GeodeticObjectParser.java
index b4914a5..ebf45df 100644
--- a/core/sis-metadata/src/main/java/org/apache/sis/io/wkt/GeodeticObjectParser.java
+++ b/core/sis-metadata/src/main/java/org/apache/sis/io/wkt/GeodeticObjectParser.java
@@ -73,6 +73,7 @@ import org.apache.sis.internal.metadata.TransformationAccuracy;
 import org.apache.sis.internal.metadata.EllipsoidalHeightCombiner;
 import org.apache.sis.internal.system.DefaultFactories;
 import org.apache.sis.internal.util.Numerics;
+import org.apache.sis.internal.util.Strings;
 import org.apache.sis.util.CharSequences;
 import org.apache.sis.util.resources.Errors;
 import org.apache.sis.util.iso.DefaultNameSpace;
@@ -1110,7 +1111,7 @@ class GeodeticObjectParser extends MathTransformParser implements Comparator<Coo
         }
         if (axisOrder.put(axis, n) != null) {   // Opportunist check, effective for instances created by SIS factory.
             throw new UnparsableObjectException(errorLocale, Errors.Keys.DuplicatedElement_1,
-                    new Object[] {WKTKeywords.Axis + "[“" + name + "”]"}, element.offset);
+                    new Object[] {Strings.bracket(WKTKeywords.Axis, name)}, element.offset);
         }
         return axis;
     }
diff --git a/core/sis-metadata/src/main/java/org/apache/sis/metadata/iso/identification/OperationName.java b/core/sis-metadata/src/main/java/org/apache/sis/metadata/iso/identification/OperationName.java
index d4eba22..b7eef55 100644
--- a/core/sis-metadata/src/main/java/org/apache/sis/metadata/iso/identification/OperationName.java
+++ b/core/sis-metadata/src/main/java/org/apache/sis/metadata/iso/identification/OperationName.java
@@ -28,6 +28,7 @@ import org.opengis.metadata.identification.DistributedComputingPlatform;
 import org.opengis.metadata.identification.OperationMetadata;
 import org.opengis.parameter.ParameterDescriptor;
 import org.opengis.util.InternationalString;
+import org.apache.sis.internal.util.Strings;
 
 
 /**
@@ -73,7 +74,7 @@ final class OperationName implements OperationMetadata, Serializable {
      */
     @Override
     public String toString() {
-        return "OperationMetadata[“" + operationName + "”]";
+        return Strings.bracket("OperationMetadata", operationName);
     }
 
     /**
diff --git a/core/sis-metadata/src/main/java/org/apache/sis/util/iso/DefaultRecordSchema.java b/core/sis-metadata/src/main/java/org/apache/sis/util/iso/DefaultRecordSchema.java
index 480aeb0..f277308 100644
--- a/core/sis-metadata/src/main/java/org/apache/sis/util/iso/DefaultRecordSchema.java
+++ b/core/sis-metadata/src/main/java/org/apache/sis/util/iso/DefaultRecordSchema.java
@@ -38,6 +38,7 @@ import org.apache.sis.util.collection.WeakValueHashMap;
 import org.apache.sis.internal.system.DefaultFactories;
 import org.apache.sis.internal.simple.SimpleAttributeType;
 import org.apache.sis.internal.converter.SurjectiveConverter;
+import org.apache.sis.internal.util.Strings;
 
 
 /**
@@ -253,6 +254,6 @@ public class DefaultRecordSchema implements RecordSchema {
      */
     @Override
     public String toString() {
-        return "RecordSchema[“" + getSchemaName() + "”]";
+        return Strings.bracket("RecordSchema", getSchemaName());
     }
 }
diff --git a/core/sis-metadata/src/main/java/org/apache/sis/xml/Pooled.java b/core/sis-metadata/src/main/java/org/apache/sis/xml/Pooled.java
index e468a6b..26c40c4 100644
--- a/core/sis-metadata/src/main/java/org/apache/sis/xml/Pooled.java
+++ b/core/sis-metadata/src/main/java/org/apache/sis/xml/Pooled.java
@@ -37,6 +37,7 @@ import org.apache.sis.util.CharSequences;
 import org.apache.sis.util.resources.Errors;
 import org.apache.sis.util.logging.WarningListener;
 import org.apache.sis.internal.util.CollectionsExt;
+import org.apache.sis.internal.util.Strings;
 import org.apache.sis.internal.jaxb.Context;
 import org.apache.sis.internal.xml.LegacyNamespaces;
 import org.apache.sis.internal.jaxb.TypeRegistration;
@@ -323,7 +324,7 @@ abstract class Pooled {
                             if (schema != null) {
                                 if (!(schema instanceof String)) {
                                     throw new PropertyException(Errors.format(Errors.Keys.IllegalPropertyValueClass_2,
-                                            name + "[\"" + key + "\"]", value.getClass()));
+                                            Strings.bracket(name, key), value.getClass()));
                                 }
                                 copy.put(key, (String) schema);
                             }
diff --git a/core/sis-raster/src/main/java/org/apache/sis/coverage/grid/GridExtent.java b/core/sis-raster/src/main/java/org/apache/sis/coverage/grid/GridExtent.java
index 3eaa4ed..d16598b 100644
--- a/core/sis-raster/src/main/java/org/apache/sis/coverage/grid/GridExtent.java
+++ b/core/sis-raster/src/main/java/org/apache/sis/coverage/grid/GridExtent.java
@@ -863,12 +863,7 @@ public class GridExtent implements Serializable {
     static int[] verifyDimensions(int[] dimensions, final int limit) {
         ArgumentChecks.ensureNonNull("dimensions", dimensions);
         final int n = dimensions.length;
-        if (n == 0) {
-            throw new IllegalArgumentException(Errors.format(Errors.Keys.EmptyArgument_1, "dimensions"));
-        }
-        if (n > limit) {
-            throw new IllegalArgumentException(Errors.format(Errors.Keys.TooManyOccurrences_2, limit, "dimension"));
-        }
+        ArgumentChecks.ensureSizeBetween("dimensions", 1, limit, n);
         dimensions = dimensions.clone();
         if (!ArraysExt.isSorted(dimensions, true)) {
             throw new IllegalArgumentException(Resources.format(Resources.Keys.NotStrictlyOrderedDimensions));
diff --git a/core/sis-referencing/src/main/java/org/apache/sis/internal/referencing/provider/NTv2.java b/core/sis-referencing/src/main/java/org/apache/sis/internal/referencing/provider/NTv2.java
index 0003409..f6bdf37 100644
--- a/core/sis-referencing/src/main/java/org/apache/sis/internal/referencing/provider/NTv2.java
+++ b/core/sis-referencing/src/main/java/org/apache/sis/internal/referencing/provider/NTv2.java
@@ -412,7 +412,7 @@ public final class NTv2 extends AbstractProvider {
                 }
                 final Object old = header.put(key, value);
                 if (old != null && !old.equals(value)) {
-                    throw new FactoryException(Errors.format(Errors.Keys.DuplicatedElement_1, key));
+                    throw new FactoryException(Errors.format(Errors.Keys.KeyCollision_1, key));
                 }
                 buffer.position(position += RECORD_LENGTH - KEY_LENGTH);
             }
diff --git a/core/sis-referencing/src/main/java/org/apache/sis/parameter/TensorParameters.java b/core/sis-referencing/src/main/java/org/apache/sis/parameter/TensorParameters.java
index c2e186d..1900bec 100644
--- a/core/sis-referencing/src/main/java/org/apache/sis/parameter/TensorParameters.java
+++ b/core/sis-referencing/src/main/java/org/apache/sis/parameter/TensorParameters.java
@@ -320,13 +320,10 @@ public class TensorParameters<E> implements Serializable {
     public TensorParameters(final Class<E> elementType, final String prefix, final String separator,
             final ParameterDescriptor<Integer>... dimensions)
     {
-        ArgumentChecks.ensureNonNull("elementType", elementType);
-        ArgumentChecks.ensureNonNull("prefix",      prefix);
-        ArgumentChecks.ensureNonNull("separator",   separator);
-        ArgumentChecks.ensureNonNull("dimensions",  dimensions);
-        if (dimensions.length == 0) {
-            throw new IllegalArgumentException(Errors.format(Errors.Keys.EmptyArgument_1, "dimensions"));
-        }
+        ArgumentChecks.ensureNonNull ("elementType", elementType);
+        ArgumentChecks.ensureNonNull ("prefix",      prefix);
+        ArgumentChecks.ensureNonNull ("separator",   separator);
+        ArgumentChecks.ensureNonEmpty("dimensions",  dimensions);
         this.elementType = elementType;
         this.prefix      = prefix;
         this.separator   = separator;
diff --git a/core/sis-referencing/src/main/java/org/apache/sis/parameter/UninitializedParameter.java b/core/sis-referencing/src/main/java/org/apache/sis/parameter/UninitializedParameter.java
index 5e3f78d..4c45685 100644
--- a/core/sis-referencing/src/main/java/org/apache/sis/parameter/UninitializedParameter.java
+++ b/core/sis-referencing/src/main/java/org/apache/sis/parameter/UninitializedParameter.java
@@ -20,6 +20,7 @@ import java.io.Serializable;
 import org.opengis.parameter.GeneralParameterDescriptor;
 import org.opengis.parameter.GeneralParameterValue;
 import org.apache.sis.referencing.IdentifiedObjects;
+import org.apache.sis.internal.util.Strings;
 
 
 /**
@@ -74,6 +75,6 @@ final class UninitializedParameter implements GeneralParameterValue, Serializabl
      */
     @Override
     public String toString() {
-        return "Parameter[\"" + IdentifiedObjects.toString(descriptor.getName()) + "\"]";
+        return Strings.bracket("Parameter", IdentifiedObjects.toString(descriptor.getName()));
     }
 }
diff --git a/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/InstallationScriptProvider.java b/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/InstallationScriptProvider.java
index 99d0a6c..87ab62e 100644
--- a/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/InstallationScriptProvider.java
+++ b/core/sis-referencing/src/main/java/org/apache/sis/referencing/factory/sql/InstallationScriptProvider.java
@@ -332,8 +332,8 @@ public abstract class InstallationScriptProvider extends InstallationResources {
                                 if (name.contains(part)) {
                                     if (found[i] != null) {
                                         log(Errors.getResources(locale)
-                                                  .getLogRecord(Level.WARNING, Errors.Keys.DuplicatedElement_1, part));
-                                        return;                         // Stop the search because of duplicated file.
+                                                  .getLogRecord(Level.WARNING, Errors.Keys.DuplicatedFileReference_1, part));
+                                        return;   // Stop the search because of duplicated file.
                                     }
                                     found[i] = name;
                                 }
diff --git a/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/CRSPair.java b/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/CRSPair.java
index 98b64dc..adc53e9 100644
--- a/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/CRSPair.java
+++ b/core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/CRSPair.java
@@ -23,6 +23,7 @@ import org.opengis.referencing.crs.CoordinateReferenceSystem;
 import org.opengis.referencing.IdentifiedObject;
 import org.apache.sis.referencing.AbstractIdentifiedObject;
 import org.apache.sis.referencing.IdentifiedObjects;
+import org.apache.sis.internal.util.Strings;
 import org.apache.sis.util.CharSequences;
 import org.apache.sis.util.Classes;
 
@@ -116,7 +117,7 @@ final class CRSPair {
                 }
                 name = CharSequences.trimWhitespaces(name, 0, i).toString() + '…';
             }
-            label = label + "[“" + name + "”]";
+            label = Strings.bracket(label, name);
         }
         return label;
     }
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/ArgumentChecks.java b/core/sis-utility/src/main/java/org/apache/sis/util/ArgumentChecks.java
index a171749..ceb6330 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/ArgumentChecks.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/ArgumentChecks.java
@@ -17,11 +17,13 @@
 package org.apache.sis.util;
 
 import java.util.Map;                                               // For javadoc
+import java.util.BitSet;
 import org.opengis.referencing.cs.CoordinateSystem;
 import org.opengis.referencing.crs.CoordinateReferenceSystem;
 import org.opengis.geometry.Envelope;
 import org.opengis.geometry.DirectPosition;
 import org.opengis.geometry.MismatchedDimensionException;
+import org.apache.sis.internal.util.Strings;
 
 import org.apache.sis.util.resources.Errors;
 
@@ -165,6 +167,86 @@ public final class ArgumentChecks extends Static {
     }
 
     /**
+     * Makes sure that an array is non-null and non-empty. If the given {@code array} is null,
+     * then a {@link NullArgumentException} is thrown. Otherwise if the array length is equals
+     * to 0, then an {@link IllegalArgumentException} is thrown.
+     *
+     * @param  name   the name of the argument to be checked. Used only if an exception is thrown.
+     * @param  array  the user argument to check against null value and empty array.
+     * @throws NullArgumentException if {@code array} is null.
+     * @throws IllegalArgumentException if {@code array} is empty.
+     *
+     * @since 1.0
+     */
+    public static void ensureNonEmpty(final String name, final Object[] array)
+            throws NullArgumentException, IllegalArgumentException
+    {
+        if (array == null) {
+            throw new NullArgumentException(Errors.format(Errors.Keys.NullArgument_1, name));
+        }
+        if (array.length == 0) {
+            throw new IllegalArgumentException(Errors.format(Errors.Keys.EmptyArgument_1, name));
+        }
+    }
+
+    /**
+     * Ensures that the given {@code values} array is non-null and non-empty. This method can also ensures that all values
+     * are between the given bounds (inclusive) and are distinct. The distinct values requirement is useful for validating
+     * arrays of spatio-temporal dimension indices, where dimensions can not be repeated.
+     *
+     * <p>Note that a successful call to {@code ensureNonEmpty(name, values, 0, max, true)} implies
+     * 1 ≦ {@code values.length} ≦ {@code max}.</p>
+     *
+     * @param  name      the name of the argument to be checked. Used only if an exception is thrown.
+     * @param  values    integer values to validate.
+     * @param  min       the minimal allowed value (inclusive), or {@link Integer#MIN_VALUE} if none.
+     * @param  max       the maximal allowed value (inclusive), or {@link Integer#MAX_VALUE} if none.
+     * @param  distinct  {@code true} if each value must be unique.
+     * @throws NullArgumentException if {@code values} is null.
+     * @throws IllegalArgumentException if {@code values} is empty, contains a value lower than {@code min},
+     *         contains a value greater than {@code max}, or contains duplicated values while {@code distinct} is {@code true}.
+     *
+     * @since 1.0
+     */
+    public static void ensureNonEmpty(final String name, final int[] values, final int min, final int max, final boolean distinct)
+            throws IllegalArgumentException
+    {
+        if (values == null) {
+            throw new NullArgumentException(Errors.format(Errors.Keys.NullArgument_1, name));
+        }
+        if (values.length == 0) {
+            throw new IllegalArgumentException(Errors.format(Errors.Keys.EmptyArgument_1, name));
+        }
+        long found = 0;                             // Cheap way to check for duplication when (max - min) ≦ 64.
+        BitSet more = null;                         // Used only if above cheap way is not sufficient.
+        for (int i=0; i<values.length; i++) {
+            final int index = values[i];
+            if (index < min || index > max) {
+                throw new IllegalArgumentException(Errors.format(
+                        Errors.Keys.ValueOutOfRange_4, Strings.toIndexed(name, i), min, max, index));
+            }
+            if (distinct) {
+                int flag = index - min;
+                if (flag <= Long.SIZE) {
+                    if (found != (found |= 1L << flag)) {
+                        continue;                               // No collision for current index.
+                    }
+                } else {
+                    flag -= Long.SIZE;
+                    if (more == null) {
+                        more = new BitSet();
+                    }
+                    if (!more.get(flag)) {
+                        more.set(flag);
+                        continue;                               // No collision for current index.
+                    }
+                }
+                throw new IllegalArgumentException(Errors.format(Errors.Keys.DuplicatedNumber_1, index));
+            }
+        }
+    }
+
+    /**
      * Ensures that the specified value is null or an instance assignable to the given type.
      * If this method does not thrown an exception, then the value can be casted to the class
      * represented by {@code expectedType} without throwing a {@link ClassCastException}.
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/Version.java b/core/sis-utility/src/main/java/org/apache/sis/util/Version.java
index ddbe487..09816be 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/Version.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/Version.java
@@ -18,7 +18,6 @@ package org.apache.sis.util;
 
 import java.io.Serializable;
 import java.util.StringTokenizer;
-import org.apache.sis.util.resources.Errors;
 
 import static org.apache.sis.internal.system.Modules.MAJOR_VERSION;
 import static org.apache.sis.internal.system.Modules.MINOR_VERSION;
@@ -122,9 +121,7 @@ public class Version implements CharSequence, Comparable<Version>, Serializable
      * @since 0.4
      */
     public static Version valueOf(final int... components) {
-        if (components.length == 0) {
-            throw new IllegalArgumentException(Errors.format(Errors.Keys.EmptyArgument_1, "components"));
-        }
+        ArgumentChecks.ensureNonEmpty("components", components, Integer.MIN_VALUE, Integer.MAX_VALUE, false);
         final Version version;
         final int major = components[0];
         if (components.length == 1) {
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/collection/DefaultTreeTable.java b/core/sis-utility/src/main/java/org/apache/sis/util/collection/DefaultTreeTable.java
index 9e30788..70515fb 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/collection/DefaultTreeTable.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/collection/DefaultTreeTable.java
@@ -122,10 +122,7 @@ public class DefaultTreeTable implements TreeTable, Cloneable, Serializable {
      * @param  columns  the list of table columns.
      */
     public DefaultTreeTable(TableColumn<?>... columns) {
-        ArgumentChecks.ensureNonNull("columns", columns);
-        if (columns.length == 0) {
-            throw new IllegalArgumentException(Errors.format(Errors.Keys.EmptyArgument_1, "columns"));
-        }
+        ArgumentChecks.ensureNonEmpty("columns", columns);
         /*
          * Copy the array for safety against user changes, and also for forcing the element type
          * to TableColumn, not a subclass, because of the UnmodifiableArrayList.wrap(E[]) contract.
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/collection/TreeTableFormat.java b/core/sis-utility/src/main/java/org/apache/sis/util/collection/TreeTableFormat.java
index 77c3ae4..f730caa 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/collection/TreeTableFormat.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/collection/TreeTableFormat.java
@@ -267,9 +267,7 @@ public class TreeTableFormat extends TabularFormat<TreeTable> {
         if (columns == null) {
             columnIndices = null;
         } else {
-            if (columns.length == 0) {
-                throw new IllegalArgumentException(Errors.format(Errors.Keys.EmptyArgument_1, "columns"));
-            }
+            ArgumentChecks.ensureNonEmpty("columns", columns);
             columnIndices = DefaultTreeTable.createColumnIndices(columns);
         }
     }
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java
index 88705aa..7ca6176 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java
@@ -231,11 +231,21 @@ public final class Errors extends IndexedResourceBundle {
         public static final short DuplicatedElement_1 = 24;
 
         /**
+         * File “{0}” is referenced more than once.
+         */
+        public static final short DuplicatedFileReference_1 = 186;
+
+        /**
          * Name or identifier “{0}” is used more than once.
          */
         public static final short DuplicatedIdentifier_1 = 25;
 
         /**
+         * Value {0,number} is used more than once.
+         */
+        public static final short DuplicatedNumber_1 = 187;
+
+        /**
          * Option “{0}” is duplicated.
          */
         public static final short DuplicatedOption_1 = 26;
@@ -484,7 +494,7 @@ public final class Errors extends IndexedResourceBundle {
         public static final short InvalidVersionIdentifier_1 = 179;
 
         /**
-         * A different value is already associated to the “{0}” key.
+         * Key “{0}” is associated twice to different values.
          */
         public static final short KeyCollision_1 = 75;
 
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties
index 9b8c0fe..75be8f1 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties
@@ -57,7 +57,9 @@ DatabaseUpdateFailure_3           = Failed to {0,choice,0#insert|1#update} recor
 DeadThread_1                      = Thread \u201c{0}\u201d is dead.
 DisposedInstanceOf_1              = This instance of \u2018{0}\u2019 has been disposed.
 DuplicatedElement_1               = Element \u201c{0}\u201d is duplicated.
+DuplicatedFileReference_1         = File \u201c{0}\u201d is referenced more than once.
 DuplicatedIdentifier_1            = Name or identifier \u201c{0}\u201d is used more than once.
+DuplicatedNumber_1                = Value {0,number} is used more than once.
 DuplicatedOption_1                = Option \u201c{0}\u201d is duplicated.
 ElementAlreadyPresent_1           = Element \u201c{0}\u201d is already present.
 ElementNotFound_1                 = Element \u201c{0}\u201d has not been found.
@@ -107,7 +109,7 @@ IndexOutOfBounds_1                = Index {0} is out of bounds.
 IndicesOutOfBounds_2              = Indices ({0}, {1}) are out of bounds.
 InfiniteArgumentValue_1           = Argument \u2018{0}\u2019 can not take an infinite value.
 InvalidVersionIdentifier_1        = \u201c{0}\u201d is an invalid version identifier.
-KeyCollision_1                    = A different value is already associated to the \u201c{0}\u201d key.
+KeyCollision_1                    = Key \u201c{0}\u201d is associated twice to different values.
 MandatoryAttribute_2              = Attribute \u201c{0}\u201d is mandatory for an object of type \u2018{1}\u2019.
 MismatchedArrayLengths            = Mismatched array lengths.
 MismatchedCRS                     = The coordinate reference system must be the same for all objects.
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties
index fcca9be..f87e89b 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties
@@ -53,11 +53,13 @@ DatabaseError_2                   = Erreur de base de donn\u00e9es lors de la cr
 DatabaseUpdateFailure_3           = \u00c9chec lors de {0,choice,0#l\u2019insertion|1#la mise \u00e0 jour} de l\u2019enregistrement \u00ab\u202f{2}\u202f\u00bb dans la table \u00ab\u202f{1}\u202f\u00bb de la base de donn\u00e9es.
 DeadThread_1                      = La t\u00e2che \u00ab\u202f{0}\u202f\u00bb est morte.
 DisposedInstanceOf_1              = Cette instance de \u2018{0}\u2019 a \u00e9t\u00e9 dispos\u00e9e.
-DuplicatedElement_1               = L\u2019\u00e9lement \u00ab\u202f{0}\u202f\u00bb est dupliqu\u00e9.
+DuplicatedElement_1               = L\u2019\u00e9l\u00e9ment \u00ab\u202f{0}\u202f\u00bb est dupliqu\u00e9.
+DuplicatedFileReference_1         = Le fichier \u00ab\u202f{0}\u202f\u00bb est r\u00e9f\u00e9renc\u00e9 plus d\u2019une fois.
 DuplicatedIdentifier_1            = Le nom ou l\u2019identifiant \u00ab\u202f{0}\u202f\u00bb est utilis\u00e9 plus d\u2019une fois.
+DuplicatedNumber_1                = La valeur {0,number} est utilis\u00e9e plus d\u2019une fois.
 DuplicatedOption_1                = L\u2019option \u00ab\u202f{0}\u202f\u00bb est dupliqu\u00e9e.
-ElementAlreadyPresent_1           = L\u2019\u00e9lement \u00ab\u202f{0}\u202f\u00bb est d\u00e9j\u00e0 pr\u00e9sent.
-ElementNotFound_1                 = L\u2019\u00e9lement \u00ab\u202f{0}\u202f\u00bb n\u2019a pas \u00e9t\u00e9 trouv\u00e9.
+ElementAlreadyPresent_1           = L\u2019\u00e9l\u00e9ment \u00ab\u202f{0}\u202f\u00bb est d\u00e9j\u00e0 pr\u00e9sent.
+ElementNotFound_1                 = L\u2019\u00e9l\u00e9ment \u00ab\u202f{0}\u202f\u00bb n\u2019a pas \u00e9t\u00e9 trouv\u00e9.
 EmptyArgument_1                   = L\u2019argument \u2018{0}\u2019 ne doit pas \u00eatre vide.
 EmptyDictionary                   = Le dictionnaire doit contenir au moins une entr\u00e9e.
 EmptyEnvelope2D                   = L\u2019enveloppe doit avoir au moins deux dimensions et ne pas \u00eatre vide.
@@ -104,7 +106,7 @@ IndexOutOfBounds_1                = L\u2019index {0} est en dehors des limites p
 IndicesOutOfBounds_2              = Les index ({0}, {1}) sont en dehors des limites permises.
 InfiniteArgumentValue_1           = L\u2019argument \u2018{0}\u2019 ne peut pas prendre une valeur infinie.
 InvalidVersionIdentifier_1        = \u00ab\u202f{0}\u202f\u00bb n\u2019est pas un identifiant de version valide.
-KeyCollision_1                    = Une valeur diff\u00e9rente est d\u00e9j\u00e0 associ\u00e9e \u00e0 la cl\u00e9 \u00ab\u202f{0}\u202f\u00bb.
+KeyCollision_1                    = La cl\u00e9 \u00ab\u202f{0}\u202f\u00bb est associ\u00e9e deux fois \u00e0 des valeurs diff\u00e9rentes.
 MandatoryAttribute_2              = L\u2019attribut \u00ab\u202f{0}\u202f\u00bb est obligatoire pour un objet de type \u2018{1}\u2019.
 MismatchedArrayLengths            = Les dimensions des tableaux ne correspondent pas.
 MismatchedCRS                     = Le syst\u00e8me de r\u00e9f\u00e9rence des coordonn\u00e9es doit \u00eatre le m\u00eame pour tous les objets.
diff --git a/core/sis-utility/src/test/java/org/apache/sis/internal/util/CitationMock.java b/core/sis-utility/src/test/java/org/apache/sis/internal/util/CitationMock.java
index 5632c55..4a31d4a 100644
--- a/core/sis-utility/src/test/java/org/apache/sis/internal/util/CitationMock.java
+++ b/core/sis-utility/src/test/java/org/apache/sis/internal/util/CitationMock.java
@@ -100,6 +100,6 @@ final strictfp class CitationMock implements Citation, Identifier {
      */
     @Override
     public String toString() {
-        return "Citation[“" + title + "”]";
+        return Strings.bracket("Citation", title);
     }
 }
diff --git a/core/sis-utility/src/test/java/org/apache/sis/util/ArgumentChecksTest.java b/core/sis-utility/src/test/java/org/apache/sis/util/ArgumentChecksTest.java
index a11fbbf..64b2a98 100644
--- a/core/sis-utility/src/test/java/org/apache/sis/util/ArgumentChecksTest.java
+++ b/core/sis-utility/src/test/java/org/apache/sis/util/ArgumentChecksTest.java
@@ -27,7 +27,7 @@ import static org.junit.Assert.*;
  * Tests the {@link ArgumentChecks} static methods.
  *
  * @author  Martin Desruisseaux (Geomatys)
- * @version 0.4
+ * @version 1.0
  * @since   0.4
  * @module
  */
@@ -51,4 +51,18 @@ public final strictfp class ArgumentChecksTest extends TestCase {
             assertTrue(e.getMessage().contains("axes[2].unit"));
         }
     }
+
+    /**
+     * Tests {@link ArgumentChecks#ensureNonEmpty(String, int[], int, int, boolean)}.
+     */
+    @Test
+    public void testEnsureBetweenAndDistinct() {
+        ArgumentChecks.ensureNonEmpty("dimensions", new int[] {2, 3, 0, 1}, 0, 4, true);
+        try {
+            ArgumentChecks.ensureNonEmpty("dimensions", new int[] {2, 3, 3, 1}, 0, 4, true);
+            fail("Expected an IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            assertNotNull(e.getMessage());
+        }
+    }
 }
diff --git a/storage/sis-gdal/src/main/java/org/apache/sis/storage/gdal/Proj4Parser.java b/storage/sis-gdal/src/main/java/org/apache/sis/storage/gdal/Proj4Parser.java
index 733f5c7..785587e 100644
--- a/storage/sis-gdal/src/main/java/org/apache/sis/storage/gdal/Proj4Parser.java
+++ b/storage/sis-gdal/src/main/java/org/apache/sis/storage/gdal/Proj4Parser.java
@@ -93,7 +93,7 @@ final class Proj4Parser {
                 if (!value.isEmpty()) {
                     final String old = parameters.put(keyword, value);
                     if (old != null && !old.equals(value)) {
-                        throw new InvalidGeodeticParameterException(Errors.format(Errors.Keys.DuplicatedElement_1, keyword));
+                        throw new InvalidGeodeticParameterException(Errors.format(Errors.Keys.KeyCollision_1, keyword));
                     }
                 }
             }
diff --git a/storage/sis-netcdf/src/main/java/org/apache/sis/internal/netcdf/NamedElement.java b/storage/sis-netcdf/src/main/java/org/apache/sis/internal/netcdf/NamedElement.java
index 65ebaad..bffb3d8 100644
--- a/storage/sis-netcdf/src/main/java/org/apache/sis/internal/netcdf/NamedElement.java
+++ b/storage/sis-netcdf/src/main/java/org/apache/sis/internal/netcdf/NamedElement.java
@@ -23,6 +23,7 @@ import org.apache.sis.util.Characters;
 import org.apache.sis.util.CharSequences;
 import org.apache.sis.util.logging.WarningListeners;
 import org.apache.sis.internal.system.Modules;
+import org.apache.sis.internal.util.Strings;
 import org.apache.sis.util.resources.IndexedResourceBundle;
 
 
@@ -114,6 +115,6 @@ public abstract class NamedElement {
      */
     @Override
     public String toString() {
-        return getClass().getSimpleName() + "[\"" + getName() + "\"]";
+        return Strings.bracket(getClass().getSimpleName(), getName());
     }
 }


[sis] 02/05: Rename a the localization keys of a few error messages.

Posted by de...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

desruisseaux pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git

commit 88aa2b277013bb0dd7405462681a45a5a97c48f9
Author: Martin Desruisseaux <ma...@geomatys.com>
AuthorDate: Tue Mar 5 12:53:31 2019 +0100

    Rename a the localization keys of a few error messages.
---
 .../sis/metadata/iso/quality/AbstractElement.java  |  2 +-
 .../java/org/apache/sis/util/ArgumentChecks.java   |  6 ++--
 .../java/org/apache/sis/util/resources/Errors.java | 32 ++++++++++++----------
 .../apache/sis/util/resources/Errors.properties    | 14 +++++-----
 .../apache/sis/util/resources/Errors_fr.properties | 14 +++++-----
 5 files changed, 35 insertions(+), 33 deletions(-)

diff --git a/core/sis-metadata/src/main/java/org/apache/sis/metadata/iso/quality/AbstractElement.java b/core/sis-metadata/src/main/java/org/apache/sis/metadata/iso/quality/AbstractElement.java
index ab018cd..1a672f8 100644
--- a/core/sis-metadata/src/main/java/org/apache/sis/metadata/iso/quality/AbstractElement.java
+++ b/core/sis-metadata/src/main/java/org/apache/sis/metadata/iso/quality/AbstractElement.java
@@ -276,7 +276,7 @@ public class AbstractElement extends ISOMetadata implements Element {
                              modCount++;
                     default: if (!it.hasNext()) break;
                              throw new IllegalArgumentException(Errors.format(
-                                     Errors.Keys.ExcessiveArgumentSize_3, "dates", 2, dates.size()));
+                                     Errors.Keys.TooManyCollectionElements_3, "dates", 2, dates.size()));
                 }
             }
             return modCount != c;
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/ArgumentChecks.java b/core/sis-utility/src/main/java/org/apache/sis/util/ArgumentChecks.java
index ae1f680..a171749 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/ArgumentChecks.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/ArgumentChecks.java
@@ -518,7 +518,7 @@ public final class ArgumentChecks extends Static {
     }
 
     /**
-     * Ensures that the given collection size of array length is between the given bounds, inclusive.
+     * Ensures that the given collection size or array length is between the given bounds, inclusive.
      * This method performs the same check than {@link #ensureBetween(String, int, int, int)
      * ensureBetween(…)}, but the error message is different in case of failure.
      *
@@ -539,10 +539,10 @@ public final class ArgumentChecks extends Static {
             if (min == 1) {
                 message = Errors.format(Errors.Keys.EmptyArgument_1, name);
             } else {
-                message = Errors.format(Errors.Keys.InsufficientArgumentSize_3, name, min, size);
+                message = Errors.format(Errors.Keys.TooFewCollectionElements_3, name, min, size);
             }
         } else if (size > max) {
-            message = Errors.format(Errors.Keys.ExcessiveArgumentSize_3, name, max, size);
+            message = Errors.format(Errors.Keys.TooManyCollectionElements_3, name, max, size);
         } else {
             return;
         }
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java
index 91067c6..88705aa 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.java
@@ -281,11 +281,6 @@ public final class Errors extends IndexedResourceBundle {
         public static final short ErrorIn_2 = 34;
 
         /**
-         * Argument ‘{0}’ shall not contain more than {1} elements. A number of {2} is excessive.
-         */
-        public static final short ExcessiveArgumentSize_3 = 35;
-
-        /**
          * A size of {1} elements is excessive for the “{0}” list.
          */
         public static final short ExcessiveListSize_2 = 36;
@@ -484,11 +479,6 @@ public final class Errors extends IndexedResourceBundle {
         public static final short InfiniteArgumentValue_1 = 73;
 
         /**
-         * Argument ‘{0}’ shall contain at least {1} elements. A number of {2} is insufficient.
-         */
-        public static final short InsufficientArgumentSize_3 = 74;
-
-        /**
          * “{0}” is an invalid version identifier.
          */
         public static final short InvalidVersionIdentifier_1 = 179;
@@ -776,22 +766,34 @@ public final class Errors extends IndexedResourceBundle {
         public static final short TableNotFound_1 = 126;
 
         /**
-         * Expected at least {0} argument{0,choice,1#|2#s}, but got {1}.
+         * Expected at least {0,number} argument{0,choice,1#|2#s}, but got {1,number}.
          */
         public static final short TooFewArguments_2 = 127;
 
         /**
-         * Too few occurrences of “{1}”. Expected at least {0} of them.
+         * Collection “{0}” contains only {2,number} element{2,choice,1#|2#s} while at least {1,number}
+         * elements were expected.
+         */
+        public static final short TooFewCollectionElements_3 = 74;
+
+        /**
+         * Too few occurrences of “{1}”. Expected at least {0,number} of them.
          */
         public static final short TooFewOccurrences_2 = 128;
 
         /**
-         * Expected at most {0} argument{0,choice,1#|2#s}, but got {1}.
+         * Expected at most {0,number} argument{0,choice,1#|2#s}, but got {1,number}.
          */
         public static final short TooManyArguments_2 = 129;
 
         /**
-         * Too many occurrences of “{1}”. The maximum is {0}.
+         * Collection “{0}” contains {2,number} elements while at most {1,number} element{1,choice,1#
+         * was|2#s were} expected.
+         */
+        public static final short TooManyCollectionElements_3 = 35;
+
+        /**
+         * Too many occurrences of “{1,number}”. The maximum is {0,number}.
          */
         public static final short TooManyOccurrences_2 = 130;
 
@@ -806,7 +808,7 @@ public final class Errors extends IndexedResourceBundle {
         public static final short UndefinedOrderingForElements_2 = 132;
 
         /**
-         * Expected an array of length {0}, but got {1}.
+         * Expected an array of length {0,number}, but got {1,number}.
          */
         public static final short UnexpectedArrayLength_2 = 133;
 
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties
index 835b4d1..9b8c0fe 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors.properties
@@ -67,7 +67,6 @@ EmptyEnvelope2D                   = Envelope must be at least two-dimensional an
 EmptyProperty_1                   = Property named \u201c{0}\u201d shall not be empty.
 ErrorIn_2                         = Error in \u201c{0}\u201d: {1}
 ErrorInFileAtLine_2               = An error occurred in file \u201c{0}\u201d at line {1}.
-ExcessiveArgumentSize_3           = Argument \u2018{0}\u2019 shall not contain more than {1} elements. A number of {2} is excessive.
 ExcessiveListSize_2               = A size of {1} elements is excessive for the \u201c{0}\u201d list.
 ExcessiveNumberOfDimensions_1     = For this algorithm, {0} is an excessive number of dimensions.
 FactoryNotFound_1                 = No factory of kind \u2018{0}\u2019 found.
@@ -107,7 +106,6 @@ InconsistentUnitsForCS_1          = Unit of measurement \u201c{0}\u201d is incon
 IndexOutOfBounds_1                = Index {0} is out of bounds.
 IndicesOutOfBounds_2              = Indices ({0}, {1}) are out of bounds.
 InfiniteArgumentValue_1           = Argument \u2018{0}\u2019 can not take an infinite value.
-InsufficientArgumentSize_3        = Argument \u2018{0}\u2019 shall contain at least {1} elements. A number of {2} is insufficient.
 InvalidVersionIdentifier_1        = \u201c{0}\u201d is an invalid version identifier.
 KeyCollision_1                    = A different value is already associated to the \u201c{0}\u201d key.
 MandatoryAttribute_2              = Attribute \u201c{0}\u201d is mandatory for an object of type \u2018{1}\u2019.
@@ -166,13 +164,15 @@ RecursiveCreateCallForKey_1       = Recursive call while creating an object for
 RequireDecimalSeparator           = A decimal separator is required.
 StalledThread_1                   = Thread \u201c{0}\u201d seems stalled.
 TableNotFound_1                   = Table \u201c{0}\u201d has not been found.
-TooFewArguments_2                 = Expected at least {0} argument{0,choice,1#|2#s}, but got {1}.
-TooFewOccurrences_2               = Too few occurrences of \u201c{1}\u201d. Expected at least {0} of them.
-TooManyArguments_2                = Expected at most {0} argument{0,choice,1#|2#s}, but got {1}.
-TooManyOccurrences_2              = Too many occurrences of \u201c{1}\u201d. The maximum is {0}.
+TooFewArguments_2                 = Expected at least {0,number} argument{0,choice,1#|2#s}, but got {1,number}.
+TooFewCollectionElements_3        = Collection \u201c{0}\u201d contains only {2,number} element{2,choice,1#|2#s} while at least {1,number} elements were expected.
+TooFewOccurrences_2               = Too few occurrences of \u201c{1}\u201d. Expected at least {0,number} of them.
+TooManyArguments_2                = Expected at most {0,number} argument{0,choice,1#|2#s}, but got {1,number}.
+TooManyCollectionElements_3       = Collection \u201c{0}\u201d contains {2,number} elements while at most {1,number} element{1,choice,1# was|2#s were} expected.
+TooManyOccurrences_2              = Too many occurrences of \u201c{1,number}\u201d. The maximum is {0,number}.
 TreeDepthExceedsMaximum           = Tree depth exceeds the maximum.
 UndefinedOrderingForElements_2    = Ordering between \u201c{0}\u201d and \u201c{1}\u201d elements is undefined.
-UnexpectedArrayLength_2           = Expected an array of length {0}, but got {1}.
+UnexpectedArrayLength_2           = Expected an array of length {0,number}, but got {1,number}.
 UnexpectedChange_1                = Unexpected change in \u2018{0}\u2019.
 UnexpectedCharactersAfter_2       = The \u201c{1}\u201d characters after \u201c{0}\u201d were unexpected.
 UnexpectedCharactersAtBound_4     = Text for \u2018{0}\u2019 was expected to {1,choice,0#begin|1#end} with \u201c{2}\u201d, but found \u201c{3}\u201d.
diff --git a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties
index f5f511f..fcca9be 100644
--- a/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties
+++ b/core/sis-utility/src/main/java/org/apache/sis/util/resources/Errors_fr.properties
@@ -64,7 +64,6 @@ EmptyEnvelope2D                   = L\u2019enveloppe doit avoir au moins deux di
 EmptyProperty_1                   = La propri\u00e9t\u00e9 nomm\u00e9e \u00ab\u202f{0}\u202f\u00bb ne doit pas \u00eatre vide.
 ErrorIn_2                         = Erreur dans \u00ab\u202f{0}\u202f\u00bb\u2008: {1}
 ErrorInFileAtLine_2               = Une erreur est survenue dans le fichier \u00ab\u202f{0}\u202f\u00bb \u00e0 la ligne {1}.
-ExcessiveArgumentSize_3           = L\u2019argument \u2018{0}\u2019 ne peut pas contenir plus de {1} \u00e9l\u00e9ments. Un nombre de {2} est excessif.
 ExcessiveListSize_2               = Une taille de {1} \u00e9l\u00e9ments est excessive pour la liste \u00ab\u202f{0}\u202f\u00bb.
 ExcessiveNumberOfDimensions_1     = Pour cet algorithme, {0} est un trop grand nombre de dimensions.
 FactoryNotFound_1                 = Aucune fabrique de type \u2018{0}\u2019 n\u2019a \u00e9t\u00e9 trouv\u00e9e.
@@ -104,7 +103,6 @@ InconsistentUnitsForCS_1          = L\u2019unit\u00e9 de mesure \u00ab\u202f{0}\
 IndexOutOfBounds_1                = L\u2019index {0} est en dehors des limites permises.
 IndicesOutOfBounds_2              = Les index ({0}, {1}) sont en dehors des limites permises.
 InfiniteArgumentValue_1           = L\u2019argument \u2018{0}\u2019 ne peut pas prendre une valeur infinie.
-InsufficientArgumentSize_3        = L\u2019argument \u2018{0}\u2019 doit contenir au moins {1} \u00e9l\u00e9ments. Un nombre de {2} est insuffisant.
 InvalidVersionIdentifier_1        = \u00ab\u202f{0}\u202f\u00bb n\u2019est pas un identifiant de version valide.
 KeyCollision_1                    = Une valeur diff\u00e9rente est d\u00e9j\u00e0 associ\u00e9e \u00e0 la cl\u00e9 \u00ab\u202f{0}\u202f\u00bb.
 MandatoryAttribute_2              = L\u2019attribut \u00ab\u202f{0}\u202f\u00bb est obligatoire pour un objet de type \u2018{1}\u2019.
@@ -162,13 +160,15 @@ RecursiveCreateCallForKey_1       = Appel r\u00e9cursif lors de la cr\u00e9ation
 RequireDecimalSeparator           = Un s\u00e9parateur d\u00e9cimal est requis.
 StalledThread_1                   = La t\u00e2che \u00ab\u202f{0}\u202f\u00bb semble bloqu\u00e9e.
 TableNotFound_1                   = La table \u00ab\u202f{0}\u202f\u00bb n\u2019a pas \u00e9t\u00e9 trouv\u00e9e.
-TooFewArguments_2                 = Au moins {0} argument{0,choice,1# \u00e9tait attendu|2#s \u00e9taient attendus}, mais seulement {1} {1,choice,1#a \u00e9t\u00e9 sp\u00e9cifi\u00e9|2#ont \u00e9t\u00e9 sp\u00e9cifi\u00e9s}.
-TooFewOccurrences_2               = Trop peu d\u2019occurrences de \u00ab\u202f{1}\u202f\u00bb. Il en faut au moins {0}.
-TooManyArguments_2                = Au plus {0} argument{0,choice,1# \u00e9tait attendu|2#s \u00e9taient attendus}, mais {1} {1,choice,1#a \u00e9t\u00e9 sp\u00e9cifi\u00e9|2#ont \u00e9t\u00e9 sp\u00e9cifi\u00e9s}.
-TooManyOccurrences_2              = Trop d\u2019occurrences de \u00ab\u202f{1}\u202f\u00bb. Le maximum est {0}.
+TooFewArguments_2                 = Au moins {0,number} argument{0,choice,1# \u00e9tait attendu|2#s \u00e9taient attendus}, mais seulement {1,number} {1,choice,1#a \u00e9t\u00e9 sp\u00e9cifi\u00e9|2#ont \u00e9t\u00e9 sp\u00e9cifi\u00e9s}.
+TooFewCollectionElements_3        = L\u2019ensemble \u00ab\u202f{0}\u202f\u00bb ne contient que {2,number} \u00e9l\u00e9ment{2,choice,1#|2#s} alors qu\u2019au moins {1,number} \u00e9l\u00e9ments \u00e9taient attendus.
+TooFewOccurrences_2               = Trop peu d\u2019occurrences de \u00ab\u202f{1}\u202f\u00bb. Il en faut au moins {0,number}.
+TooManyArguments_2                = Au plus {0,number} argument{0,choice,1# \u00e9tait attendu|2#s \u00e9taient attendus}, mais {1,number} {1,choice,1#a \u00e9t\u00e9 sp\u00e9cifi\u00e9|2#ont \u00e9t\u00e9 sp\u00e9cifi\u00e9s}.
+TooManyCollectionElements_3       = L\u2019ensemble \u00ab\u202f{0}\u202f\u00bb contient {2,number} \u00e9l\u00e9ments alors qu\u2019au plus {1,number} \u00e9l\u00e9ment{1,choice,1# \u00e9tait attendu|2#s \u00e9taient attendus}.
+TooManyOccurrences_2              = Trop d\u2019occurrences de \u00ab\u202f{1}\u202f\u00bb. Le maximum est {0,number}.
 TreeDepthExceedsMaximum           = La profondeur de l\u2019arbre exc\u00e8de le maximum.
 UndefinedOrderingForElements_2    = L\u2019ordre entre les \u00e9l\u00e9ments \u00ab\u202f{0}\u202f\u00bb et \u00ab\u202f{1}\u202f\u00bb n\u2019est pas d\u00e9fini.
-UnexpectedArrayLength_2           = Un tableau de longueur {0} \u00e9tait attendu, mais le tableau re\u00e7u est de longueur {1}.
+UnexpectedArrayLength_2           = Un tableau de longueur {0} \u00e9tait attendu, mais le tableau re\u00e7u est de longueur {1,number}.
 UnexpectedChange_1                = Changement inattendu dans \u2018{0}\u2019.
 UnexpectedCharactersAfter_2       = Les caract\u00e8res \u00ab\u202f{1}\u202f\u00bb apr\u00e8s \u00ab\u202f{0}\u202f\u00bb sont inattendus.
 UnexpectedCharactersAtBound_4     = Le texte pour \u2018{0}\u2019 devait {1,choice,0#commencer|1#finir} par \u00ab\u202f{2}\u202f\u00bb, mais on a trouv\u00e9 \u00ab\u202f{3}\u202f\u00bb.


[sis] 01/05: Replace some !isInfinite(x) && !isNaN(x) pairs by isFinite(x).

Posted by de...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

desruisseaux pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git

commit 6ec2776f7ee13659e5c1e3f9f7f86d4ac7ccd67e
Author: Martin Desruisseaux <ma...@geomatys.com>
AuthorDate: Sat Mar 2 15:43:14 2019 +0100

    Replace some !isInfinite(x) && !isNaN(x) pairs by isFinite(x).
---
 .../src/main/java/org/apache/sis/geometry/Envelopes.java              | 4 ++--
 .../src/main/java/org/apache/sis/geometry/Shapes2D.java               | 2 +-
 .../org/apache/sis/internal/referencing/provider/MapProjection.java   | 2 +-
 .../sis/referencing/operation/projection/MapProjectionTestCase.java   | 2 +-
 4 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/core/sis-referencing/src/main/java/org/apache/sis/geometry/Envelopes.java b/core/sis-referencing/src/main/java/org/apache/sis/geometry/Envelopes.java
index f224383..3bb6332 100644
--- a/core/sis-referencing/src/main/java/org/apache/sis/geometry/Envelopes.java
+++ b/core/sis-referencing/src/main/java/org/apache/sis/geometry/Envelopes.java
@@ -742,7 +742,7 @@ poles:  for (int i=0; i<dimension; i++, dimensionBitMask <<= 1) {
             boolean testMax = false;            // Tells if we are testing the minimal or maximal value.
             do {
                 final double extremum = testMax ? axis.getMaximumValue() : axis.getMinimumValue();
-                if (Double.isInfinite(extremum) || Double.isNaN(extremum)) {
+                if (!Double.isFinite(extremum)) {
                     /*
                      * The axis is unbounded. It should always be the case when the target CRS is
                      * a map projection, in which case this loop will finish soon and this method
@@ -983,7 +983,7 @@ poles:  for (int i=0; i<dimension; i++, dimensionBitMask <<= 1) {
         int dimension = envelope.getDimension();
         while (dimension != 0) {
             final double length = envelope.getSpan(dimension - 1);
-            if (!Double.isNaN(length) && !Double.isInfinite(length)) {
+            if (Double.isFinite(length)) {
                 break;
             }
             dimension--;
diff --git a/core/sis-referencing/src/main/java/org/apache/sis/geometry/Shapes2D.java b/core/sis-referencing/src/main/java/org/apache/sis/geometry/Shapes2D.java
index 9814dde..6280a06 100644
--- a/core/sis-referencing/src/main/java/org/apache/sis/geometry/Shapes2D.java
+++ b/core/sis-referencing/src/main/java/org/apache/sis/geometry/Shapes2D.java
@@ -475,7 +475,7 @@ public final class Shapes2D extends Static {
                 continue;
             }
             final double extremum = (border & 1) == 0 ? axis.getMinimumValue() : axis.getMaximumValue();
-            if (Double.isInfinite(extremum) || Double.isNaN(extremum)) {
+            if (!Double.isFinite(extremum)) {
                 continue;
             }
             if (targetPt == null) {
diff --git a/core/sis-referencing/src/main/java/org/apache/sis/internal/referencing/provider/MapProjection.java b/core/sis-referencing/src/main/java/org/apache/sis/internal/referencing/provider/MapProjection.java
index 378cb6a..f83a469 100644
--- a/core/sis-referencing/src/main/java/org/apache/sis/internal/referencing/provider/MapProjection.java
+++ b/core/sis-referencing/src/main/java/org/apache/sis/internal/referencing/provider/MapProjection.java
@@ -192,7 +192,7 @@ public abstract class MapProjection extends AbstractProvider {
     public static void validate(final ParameterDescriptor<? extends Number> descriptor, final double value)
             throws IllegalArgumentException
     {
-        if (Double.isNaN(value) || Double.isInfinite(value)) {
+        if (!Double.isFinite(value)) {
             throw new IllegalArgumentException(Resources.format(Resources.Keys.IllegalParameterValue_2,
                     descriptor.getName(), value));
         }
diff --git a/core/sis-referencing/src/test/java/org/apache/sis/referencing/operation/projection/MapProjectionTestCase.java b/core/sis-referencing/src/test/java/org/apache/sis/referencing/operation/projection/MapProjectionTestCase.java
index 074024f..46e8e99 100644
--- a/core/sis-referencing/src/test/java/org/apache/sis/referencing/operation/projection/MapProjectionTestCase.java
+++ b/core/sis-referencing/src/test/java/org/apache/sis/referencing/operation/projection/MapProjectionTestCase.java
@@ -154,7 +154,7 @@ abstract strictfp class MapProjectionTestCase extends MathTransformTestCase {
         coordinate[1] = φ;
         ((NormalizedProjection) transform).transform(coordinate, 0, coordinate, 0, false);
         final double y = coordinate[1];
-        if (!isNaN(y) && !Double.isInfinite(y)) {
+        if (Double.isFinite(y)) {
             assertEquals(0, coordinate[0], tolerance);
         }
         return y;