Java Code Examples for org.opengis.referencing.cs.CoordinateSystem#getDimension()

The following examples show how to use org.opengis.referencing.cs.CoordinateSystem#getDimension() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GeometryUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
/**
 * @param val the value
 * @param crs
 * @param axis the coordinate axis
 * @return
 */
private static double clipRange(
    final double val,
    final CoordinateReferenceSystem crs,
    final int axis) {
  final CoordinateSystem coordinateSystem = crs.getCoordinateSystem();
  if (coordinateSystem.getDimension() > axis) {
    final CoordinateSystemAxis coordinateAxis = coordinateSystem.getAxis(axis);
    if (val < coordinateAxis.getMinimumValue()) {
      return coordinateAxis.getMinimumValue();
    } else if (val > coordinateAxis.getMaximumValue()) {
      return coordinateAxis.getMaximumValue();
    }
  }
  return val;
}
 
Example 2
Source File: AxisDirections.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the dimension of an axis having the given direction or its opposite.
 * If more than one axis has the given direction, only the first occurrence is returned.
 * If both the given direction and its opposite exist, then the dimension for the given
 * direction has precedence over the opposite direction.
 *
 * @param  cs         the coordinate system to inspect, or {@code null}.
 * @param  direction  the direction of the axis to search.
 * @return the dimension of the axis using the given direction or its opposite, or -1 if none.
 */
public static int indexOfColinear(final CoordinateSystem cs, final AxisDirection direction) {
    int fallback = -1;
    if (cs != null) {
        final int dimension = cs.getDimension();
        for (int i=0; i<dimension; i++) {
            final AxisDirection d = cs.getAxis(i).getDirection();
            if (direction.equals(d)) {
                return i;
            }
            if (fallback < 0 && d.equals(opposite(direction))) {
                fallback = i;
            }
        }
    }
    return fallback;
}
 
Example 3
Source File: GeometryUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
private static Coordinate[] toPolygonCoordinates(final CoordinateSystem coordinateSystem) {
  final Coordinate[] coordinates =
      new Coordinate[(int) Math.pow(2, coordinateSystem.getDimension()) + 1];
  final BitSet greyCode = new BitSet(coordinateSystem.getDimension());
  final BitSet mask = getGreyCodeMask(coordinateSystem.getDimension());
  for (int i = 0; i < coordinates.length; i++) {
    coordinates[i] =
        new Coordinate(
            getValue(greyCode, coordinateSystem.getAxis(0), 0),
            getValue(greyCode, coordinateSystem.getAxis(1), 1),
            coordinateSystem.getDimension() > 2
                ? getValue(greyCode, coordinateSystem.getAxis(2), 2)
                : Double.NaN);

    grayCode(greyCode, mask);
  }
  return coordinates;
}
 
Example 4
Source File: TransformCommand.java    From sis with Apache License 2.0 6 votes vote down vote up
private void printAxes(final CoordinateSystem cs) {
    final int targetDim = cs.getDimension();
    for (int i=0; i<targetDim; i++) {
        if (i != 0) {
            out.print(',');
        }
        final CoordinateSystemAxis axis = cs.getAxis(i);
        String name =  axis.getName().getCode();
        name = Transliterator.DEFAULT.toShortAxisName(cs, axis.getDirection(), name);
        final String unit = axis.getUnit().toString();
        if (!unit.isEmpty()) {
            name = name + " (" + unit + ')';
        }
        printQuotedText(name, coordinateWidth, X364.FOREGROUND_CYAN);
    }
}
 
Example 5
Source File: TransformCommand.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Computes the suggested precision for printing values in the given units.
 *
 * @throws IncommensurableException should never happen.
 */
private void computeNumFractionDigits(final CoordinateSystem cs) throws IncommensurableException {
    final int dimension = cs.getDimension();
    numFractionDigits = new int[dimension];
    thresholdForScientificNotation = new double[dimension];
    for (int i=0; i<dimension; i++) {
        final Unit<?> unit = cs.getAxis(0).getUnit();
        final Unit<?> source;
        double precision;
        if (Units.isLinear(unit)) {
            precision = Formulas.LINEAR_TOLERANCE;
            source = Units.METRE;
        } else if (Units.isAngular(unit)) {
            precision = Formulas.ANGULAR_TOLERANCE;
            source = Units.DEGREE;
        } else {
            precision = 0.001;
            source = unit;
        }
        precision = source.getConverterToAny(unit).convert(precision);
        if (precision > 0) {
            numFractionDigits[i] = Math.max(DecimalFunctions.fractionDigitsForDelta(precision, false) + 1, 0);
        }
        thresholdForScientificNotation[i] = MathFunctions.pow10(coordinateWidth - 1 - numFractionDigits[i]);
    }
}
 
Example 6
Source File: AxisDirections.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the angular unit of the specified coordinate system.
 * The preference will be given to the longitude axis, if found.
 *
 * @param  cs        the coordinate system from which to get the angular unit, or {@code null}.
 * @param  fallback  the default unit to return if no angular unit is found.
 * @return the angular unit, of {@code unit} if no angular unit was found.
 *
 * @see org.apache.sis.internal.referencing.ReferencingUtilities#getUnit(CoordinateSystem)
 *
 * @since 0.6
 */
public static Unit<Angle> getAngularUnit(final CoordinateSystem cs, Unit<Angle> fallback) {
    if (cs != null) {
        for (int i = cs.getDimension(); --i>=0;) {
            final CoordinateSystemAxis axis = cs.getAxis(i);
            if (axis != null) {                                                     // Paranoiac check.
                final Unit<?> candidate = axis.getUnit();
                if (Units.isAngular(candidate)) {
                    fallback = candidate.asType(Angle.class);
                    if (AxisDirection.EAST.equals(absolute(axis.getDirection()))) {
                        break;                                                      // Found the longitude axis.
                    }
                }
            }
        }
    }
    return fallback;
}
 
Example 7
Source File: EllipsoidalHeightCombiner.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the coordinate system if the given CRS is a two-dimensional geographic or projected CRS,
 * or {@code null} otherwise. The returned coordinate system is either ellipsoidal or Cartesian;
 * no other type is returned.
 */
private static CoordinateSystem getCsIfHorizontal2D(final CoordinateReferenceSystem crs) {
    final boolean isProjected = (crs instanceof ProjectedCRS);
    if (isProjected || crs instanceof GeodeticCRS) {
        final CoordinateSystem cs = crs.getCoordinateSystem();
        if (cs.getDimension() == 2 && (isProjected || cs instanceof EllipsoidalCS)) {
            /*
             * ProjectedCRS are guaranteed to be associated to CartesianCS, so we do not test that.
             * GeodeticCRS may be associated to either CartesianCS or EllipsoidalCS, but this method
             * shall accept only EllipsoidalCS. Actually we should accept only GeographicCRS, but we
             * relax this condition by accepting GeodeticCRS with EllipsoidalCS.
             */
            return cs;
        }
    }
    return null;
}
 
Example 8
Source File: GeoWaveRasterReader.java    From geowave with Apache License 2.0 5 votes vote down vote up
private static int indexOf(
    final CoordinateReferenceSystem crs,
    final Set<AxisDirection> direction) {
  final CoordinateSystem cs = crs.getCoordinateSystem();
  for (int index = 0; index < cs.getDimension(); index++) {
    final CoordinateSystemAxis axis = cs.getAxis(index);
    if (direction.contains(axis.getDirection())) {
      return index;
    }
  }
  return -1;
}
 
Example 9
Source File: ArgumentChecks.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures that the given CRS, if non-null, has the expected number of dimensions.
 * This method does nothing if the given coordinate reference system is null.
 *
 * @param  name      the name of the argument to be checked. Used only if an exception is thrown.
 * @param  expected  the expected number of dimensions.
 * @param  crs       the coordinate reference system to check for its dimension, or {@code null}.
 * @throws MismatchedDimensionException if the given coordinate reference system is non-null
 *         and does not have the expected number of dimensions.
 */
public static void ensureDimensionMatches(final String name, final int expected,
        final CoordinateReferenceSystem crs) throws MismatchedDimensionException
{
    if (crs != null) {
        final CoordinateSystem cs = crs.getCoordinateSystem();
        if (cs != null) {                                       // Should never be null, but let be safe.
            final int dimension = cs.getDimension();
            if (dimension != expected) {
                throw new MismatchedDimensionException(Errors.format(
                        Errors.Keys.MismatchedDimension_3, name, expected, dimension));
            }
        }
    }
}
 
Example 10
Source File: WraparoundAdjustment.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Computes a position with coordinates equivalent to the given {@code pointOfInterest}, but
 * potentially shifted to interior of the domain of validity specified at construction time.
 * The dimensions that may be shifted are the ones having an axis with wraparound meaning.
 * In order to perform this operation, the position may be temporarily converted to a geographic CRS
 * and converted back to its original CRS.
 *
 * <p>The coordinate reference system should be specified in the {@code pointOfInterest},
 * or (as a fallback) in the {@code domainOfValidity} specified at construction time.</p>
 *
 * @param  pointOfInterest  the position to potentially shift to domain of validity interior.
 *         If a shift is needed, then the given position will be replaced by a new position;
 *         the given position will not be modified.
 * @return position potentially shifted to the domain of validity interior.
 * @throws TransformException if a coordinate conversion failed.
 */
public DirectPosition shift(DirectPosition pointOfInterest) throws TransformException {
    if (setIfNonNull(pointOfInterest.getCoordinateReferenceSystem())) {
        DirectPosition shifted;
        if (replaceCRS()) {
            shifted = geographicToAOI.inverse().transform(pointOfInterest, null);
        } else {
            shifted = pointOfInterest;              // To be replaced by a copy of 'pointOfInterest' when first needed.
        }
        final CoordinateSystem cs = crs.getCoordinateSystem();
        for (int i=cs.getDimension(); --i >= 0;) {
            final double period = range(cs, i);
            if (period > 0) {
                transformDomainToAOI();
                final double x = shifted.getOrdinate(i);
                double delta = domainOfValidity.getMinimum(i) - x;
                if (delta > 0) {                                        // Test for point before domain of validity.
                    delta = Math.ceil(delta / period);
                } else {
                    delta = domainOfValidity.getMaximum(i) - x;
                    if (delta < 0) {                                    // Test for point after domain of validity.
                        delta = Math.floor(delta / period);
                    } else {
                        continue;
                    }
                }
                if (delta != 0) {
                    isResultTransformed = true;
                    if (shifted == pointOfInterest) {
                        shifted = new GeneralDirectPosition(pointOfInterest);
                    }
                    pointOfInterest = shifted;                         // 'shifted' may have been set before the loop.
                    shifted.setOrdinate(i, x + delta * period);        // TODO: use Math.fma in JDK9.
                }
            }
        }
    }
    return toFinal().transform(pointOfInterest, null);
}
 
Example 11
Source File: EPSGFactoryTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests creation of deprecated coordinate systems.
 *
 * @throws FactoryException if an error occurred while querying the factory.
 */
@Test
public void testDeprecatedCoordinateSystems() throws FactoryException {
    final EPSGFactory factory = TestFactorySource.factory;
    assumeNotNull(factory);
    for (final Map.Entry<Integer,Integer> entry : EPSGDataAccess.deprecatedCS().entrySet()) {
        final CoordinateSystem expected = factory.createEllipsoidalCS(entry.getValue().toString());
        loggings.assertNoUnexpectedLog();
        final String code = entry.getKey().toString();
        final CoordinateSystem deprecated;
        try {
            deprecated = factory.createEllipsoidalCS(code);
        } catch (FactoryException e) {
            final String m = e.getMessage();
            if (m.contains("9115") || m.contains("9116") || m.contains("9117") ||
                m.contains("9118") || m.contains("9119") || m.contains("9120"))
            {
                // Unit "9116" to "9120" are known to be unsupported.
                continue;
            }
            throw e;
        }
        loggings.assertNextLogContains(code);
        final int dimension = expected.getDimension();
        assertEquals("dimension", dimension, deprecated.getDimension());
        for (int i=0; i<dimension; i++) {
            final CoordinateSystemAxis ref  = expected.getAxis(i);
            final CoordinateSystemAxis axis = deprecated.getAxis(i);
            assertEquals("name",         ref.getName(),                 axis.getName());
            assertEquals("alias",        ref.getAlias(),                axis.getAlias());
            assertEquals("direction",    ref.getDirection(),            axis.getDirection());
            assertEquals("rangeMeaning", ref.getRangeMeaning(),         axis.getRangeMeaning());
            assertEquals("unit",         ref.getUnit().getSystemUnit(), axis.getUnit().getSystemUnit());
        }
    }
}
 
Example 12
Source File: CRS.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * If the given CRS would qualify as horizontal except for its number of dimensions, returns that number.
 * Otherwise returns 0. The number of dimensions can only be 2 or 3.
 */
private static int horizontalCode(final CoordinateReferenceSystem crs) {
    /*
     * In order to determine if the CRS is geographic, checking the CoordinateSystem type is more reliable
     * then checking if the CRS implements the GeographicCRS interface.  This is because the GeographicCRS
     * type did not existed in ISO 19111:2007, so a CRS could be standard-compliant without implementing
     * the GeographicCRS interface.
     */
    boolean isEngineering = false;
    final boolean isGeodetic = (crs instanceof GeodeticCRS);
    if (isGeodetic || crs instanceof ProjectedCRS || (isEngineering = (crs instanceof EngineeringCRS))) {
        final CoordinateSystem cs = crs.getCoordinateSystem();
        final int dim = cs.getDimension();
        if ((dim & ~1) == 2 && (!isGeodetic || (cs instanceof EllipsoidalCS))) {
            if (isEngineering) {
                int n = 0;
                for (int i=0; i<dim; i++) {
                    if (AxisDirections.isCompass(cs.getAxis(i).getDirection())) n++;
                }
                // If we don't have exactly 2 east, north, etc. directions, consider as non-horizontal.
                if (n != 2) return 0;
            }
            return dim;
        }
    }
    return 0;
}
 
Example 13
Source File: AbstractCS.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the axes of the given coordinate system.
 */
private static CoordinateSystemAxis[] getAxes(final CoordinateSystem cs) {
    final CoordinateSystemAxis[] axes = new CoordinateSystemAxis[cs.getDimension()];
    for (int i=0; i<axes.length; i++) {
        axes[i] = cs.getAxis(i);
    }
    return axes;
}
 
Example 14
Source File: Normalizer.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a coordinate system with the same axes than the given CS, except that the wraparound axes
 * are shifted to a range of positive values. This method can be used in order to shift between the
 * [-180 … +180]° and [0 … 360]° ranges of longitude values.
 *
 * <p>This method shifts the axis {@linkplain CoordinateSystemAxis#getMinimumValue() minimum} and
 * {@linkplain CoordinateSystemAxis#getMaximumValue() maximum} values by a multiple of half the range
 * (typically 180°). This method does not change the meaning of coordinate values. For example a longitude
 * of -60° still locate the same point in the old and the new coordinate system. But the preferred way to
 * locate that point become the 300° value if the longitude range has been shifted to positive values.</p>
 *
 * @return a coordinate system using the given kind of longitude range, or {@code null} if no change is needed.
 */
private static AbstractCS shiftAxisRange(final CoordinateSystem cs) {
    boolean changed = false;
    final CoordinateSystemAxis[] axes = new CoordinateSystemAxis[cs.getDimension()];
    for (int i=0; i<axes.length; i++) {
        CoordinateSystemAxis axis = cs.getAxis(i);
        if (RangeMeaning.WRAPAROUND.equals(axis.getRangeMeaning())) {
            double min = axis.getMinimumValue();
            if (min < 0) {
                double max = axis.getMaximumValue();
                double offset = (max - min) / 2;
                offset *= Math.floor(min/offset + Numerics.COMPARISON_THRESHOLD);
                min -= offset;
                max -= offset;
                if (min < max) { // Paranoiac check, but also a way to filter NaN values when offset is infinite.
                    axis = forRange(axis, min, max);
                    changed = true;
                }
            }
        }
        axes[i] = axis;
    }
    if (!changed) {
        return null;
    }
    return castOrCopy(cs).createForAxes(IdentifiedObjects.getProperties(cs, EXCLUDES), axes);
}
 
Example 15
Source File: DefaultCoordinateSystemAxis.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@code ORDER[…]} element for the given axis in the given coordinate system.
 * If this method does not found exactly one instance of the given axis in the given coordinate system,
 * then returns {@code null}. In the later case, it is caller's responsibility to declare the WKT as invalid.
 *
 * <p>This method is a little bit inefficient since the enclosing {@link AbstractCS#formatTo(Formatter)}
 * method already know this axis index. But there is currently no API in {@link Formatter} for carrying
 * this information, and we are a little bit reluctant to introduce such API since it would force us to
 * introduce lists in a model which is, for everything else, purely based on trees.</p>
 *
 * @se <a href="https://issues.apache.org/jira/browse/SIS-163">SIS-163</a>
 */
static Order create(final CoordinateSystem cs, final DefaultCoordinateSystemAxis axis) {
    Order order = null;
    final int dimension = cs.getDimension();
    for (int i=0; i<dimension;) {
        if (cs.getAxis(i++) == axis) {
            if (order == null) {
                order = new Order(i);
            } else {
                return null;
            }
        }
    }
    return order;
}
 
Example 16
Source File: Angle.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the angular value of the axis having the given direction.
 * This helper method is used for subclass constructors expecting a {@link DirectPosition} argument.
 *
 * @param  position  the position from which to get an angular value.
 * @param  positive  axis direction of positive values.
 * @param  negative  axis direction of negative values.
 * @return angular value in degrees.
 * @throws IllegalArgumentException if the given coordinate it not associated to a CRS,
 *         or if no axis oriented toward the given directions is found, or if that axis
 *         does not use {@linkplain Units#isAngular angular units}.
 */
static double valueOf(final DirectPosition position, final AxisDirection positive, final AxisDirection negative) {
    final CoordinateReferenceSystem crs = position.getCoordinateReferenceSystem();
    if (crs == null) {
        throw new IllegalArgumentException(Errors.format(Errors.Keys.UnspecifiedCRS));
    }
    final CoordinateSystem cs = crs.getCoordinateSystem();
    final int dimension = cs.getDimension();
    IncommensurableException cause = null;
    for (int i=0; i<dimension; i++) {
        final CoordinateSystemAxis axis = cs.getAxis(i);
        final AxisDirection dir = axis.getDirection();
        final boolean isPositive = dir.equals(positive);
        if (isPositive || dir.equals(negative)) {
            double value = position.getOrdinate(i);
            if (!isPositive) value = -value;
            final Unit<?> unit = axis.getUnit();
            if (unit != Units.DEGREE) try {
                value = unit.getConverterToAny(Units.DEGREE).convert(value);
            } catch (IncommensurableException e) {
                cause = e;
                break;
            }
            return value;
        }
    }
    throw new IllegalArgumentException(Errors.format(Errors.Keys.IllegalCRSType_1,
            Classes.getLeafInterfaces(crs.getClass(), CoordinateReferenceSystem.class)[0]), cause);
}
 
Example 17
Source File: FeatureDataUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static String getAxis(final CoordinateReferenceSystem crs) {
  // Some geometries do not have a CRS provided. Thus we default to
  // urn:ogc:def:crs:EPSG::4326
  final CoordinateSystem cs = crs == null ? null : crs.getCoordinateSystem();
  if ((cs != null) && (cs.getDimension() > 0)) {
    return cs.getAxis(0).getDirection().name().toString();
  }
  return "EAST";
}
 
Example 18
Source File: CoordinateSystemTransform.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
 * Implementation of {@link DefaultMathTransformFactory#createCoordinateSystemChange(CoordinateSystem,
 * CoordinateSystem, Ellipsoid)}, defined here for reducing the {@code DefaultMathTransformFactory}
 * weight in the common case where the conversions handled by this class are not needed.
 */
static MathTransform create(final MathTransformFactory factory, final CoordinateSystem source,
        final CoordinateSystem target) throws FactoryException
{
    int passthrough = 0;
    CoordinateSystemTransform kernel = null;
    if (source instanceof CartesianCS) {
        if (target instanceof SphericalCS) {
            kernel = CartesianToSpherical.INSTANCE;
        } else if (target instanceof PolarCS) {
            kernel = CartesianToPolar.INSTANCE;
        } else if (target instanceof CylindricalCS) {
            kernel = CartesianToPolar.INSTANCE;
            passthrough = 1;
        }
    } else if (target instanceof CartesianCS) {
        if (source instanceof SphericalCS) {
            kernel = SphericalToCartesian.INSTANCE;
        } else if (source instanceof PolarCS) {
            kernel = PolarToCartesian.INSTANCE;
        } else if (source instanceof CylindricalCS) {
            kernel = PolarToCartesian.INSTANCE;
            passthrough = 1;
        }
    }
    Exception cause = null;
    try {
        if (kernel == null) {
            return factory.createAffineTransform(CoordinateSystems.swapAndScaleAxes(source, target));
        } else if (source.getDimension() == kernel.getSourceDimensions() + passthrough &&
                   target.getDimension() == kernel.getTargetDimensions() + passthrough)
        {
            final MathTransform tr = (passthrough == 0)
                    ? kernel.completeTransform(factory)
                    : kernel.passthrough(factory);
            final MathTransform before = factory.createAffineTransform(
                    CoordinateSystems.swapAndScaleAxes(source,
                    CoordinateSystems.replaceAxes(source, AxesConvention.NORMALIZED)));
            final MathTransform after = factory.createAffineTransform(
                    CoordinateSystems.swapAndScaleAxes(
                    CoordinateSystems.replaceAxes(target, AxesConvention.NORMALIZED), target));
            return factory.createConcatenatedTransform(before,
                   factory.createConcatenatedTransform(tr, after));
        }
    } catch (IllegalArgumentException | IncommensurableException e) {
        cause = e;
    }
    throw new OperationNotFoundException(Resources.format(Resources.Keys.CoordinateOperationNotFound_2,
            WKTUtilities.toType(CoordinateSystem.class, source.getClass()),
            WKTUtilities.toType(CoordinateSystem.class, target.getClass())), cause);
}
 
Example 19
Source File: CoordinateSystems.java    From sis with Apache License 2.0 3 votes vote down vote up
/**
 * Returns the axis directions for the specified coordinate system.
 * This method guarantees that the returned array is non-null and does not contain any null direction.
 *
 * @param  cs  the coordinate system.
 * @return the axis directions for the specified coordinate system.
 * @throws NullArgumentException if {@code cs} is null, or one of its axes is null,
 *         or a value returned by {@link CoordinateSystemAxis#getDirection()} is null.
 *
 * @since 0.8
 */
public static AxisDirection[] getAxisDirections(final CoordinateSystem cs) {
    ArgumentChecks.ensureNonNull("cs", cs);
    final AxisDirection[] directions = new AxisDirection[cs.getDimension()];
    for (int i=0; i<directions.length; i++) {
        final CoordinateSystemAxis axis = cs.getAxis(i);
        ArgumentChecks.ensureNonNullElement("cs", i, cs);
        ArgumentChecks.ensureNonNullElement("cs[#].direction", i, directions[i] = axis.getDirection());
    }
    return directions;
}
 
Example 20
Source File: ArgumentChecks.java    From sis with Apache License 2.0 3 votes vote down vote up
/**
 * Ensures that the given coordinate system, if non-null, has the expected number of dimensions.
 * This method does nothing if the given coordinate system is null.
 *
 * @param  name      the name of the argument to be checked. Used only if an exception is thrown.
 * @param  expected  the expected number of dimensions.
 * @param  cs        the coordinate system to check for its dimension, or {@code null}.
 * @throws MismatchedDimensionException if the given coordinate system is non-null
 *         and does not have the expected number of dimensions.
 *
 * @since 0.6
 */
public static void ensureDimensionMatches(final String name, final int expected,
        final CoordinateSystem cs) throws MismatchedDimensionException
{
    if (cs != null) {
        final int dimension = cs.getDimension();
        if (dimension != expected) {
            throw new MismatchedDimensionException(Errors.format(
                    Errors.Keys.MismatchedDimension_3, name, expected, dimension));
        }
    }
}