org.opengis.geometry.MismatchedDimensionException Java Examples

The following examples show how to use org.opengis.geometry.MismatchedDimensionException. 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: ProjectedTransformTry.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * 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 projToGrid         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[] projToGrid, int expectedDimension) {
    ArgumentChecks.ensureNonNull("name", name);
    ArgumentChecks.ensureNonNull("projection", projection);
    this.name       = name;
    this.projection = projection;
    this.projToGrid = projToGrid;
    int side = 0;                           // 0 = problem with source dimensions, 1 = problem with target dimensions.
    int actual = projection.getSourceDimensions();
    if (actual <= expectedDimension) {
        expectedDimension = projToGrid.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));
}
 
Example #2
Source File: SearchByPointCommand.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
private double calculateLayerScale(Crs mapCrs, Crs layerCrs, Bbox mapBounds, double mapScale)
		throws GeomajasException {
	double layerScale = mapScale;

	try {
		// We don't necessarily need to split into same CRS and different CRS cases, the latter implementation uses
		// identity transform if CRSs are equal for map and layer but might introduce bugs in rounding and/or
		// conversions.
		if (!mapCrs.equals(layerCrs)) {

			// Translate the map coordinates to layer coordinates, assumes equal x-y orientation
			Bbox layerBounds = geoService.transform(mapBounds, mapCrs, layerCrs);
			layerScale = mapBounds.getWidth() * mapScale / layerBounds.getWidth();
		}
	} catch (MismatchedDimensionException e) {
		throw new GeomajasException(e, ExceptionCode.RENDER_DIMENSION_MISMATCH);
	}
	return layerScale;
}
 
Example #3
Source File: AbstractDerivedCRS.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a derived CRS from a defining conversion.
 * The properties given in argument follow the same rules than for the
 * {@linkplain AbstractCRS#AbstractCRS(Map, CoordinateSystem) super-class constructor}.
 *
 * @param  properties  the properties to be given to the new derived CRS object.
 * @param  baseCRS     coordinate reference system to base the derived CRS on.
 * @param  conversion  the defining conversion from a normalized base to a normalized derived CRS.
 * @param  derivedCS   the coordinate system for the derived CRS. The number of axes must match
 *                     the target dimension of the {@code baseToDerived} transform.
 * @throws MismatchedDimensionException if the source and target dimensions of {@code baseToDerived}
 *         do not match the dimensions of {@code base} and {@code derivedCS} respectively.
 */
AbstractDerivedCRS(final Map<String,?>    properties,
                   final SingleCRS        baseCRS,
                   final Conversion       conversion,
                   final CoordinateSystem derivedCS)
        throws MismatchedDimensionException
{
    super(properties, derivedCS);
    ArgumentChecks.ensureNonNull("baseCRS", baseCRS);
    ArgumentChecks.ensureNonNull("conversion", conversion);
    final MathTransform baseToDerived = conversion.getMathTransform();
    if (baseToDerived != null) {
        ArgumentChecks.ensureDimensionMatches("baseCRS",   baseToDerived.getSourceDimensions(), baseCRS);
        ArgumentChecks.ensureDimensionMatches("derivedCS", baseToDerived.getTargetDimensions(), derivedCS);
    }
    conversionFromBase = createConversionFromBase(properties, baseCRS, conversion);
}
 
Example #4
Source File: RasterUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
private static Coordinate[] getWorldCoordinates(
    final double minX,
    final double minY,
    final double maxX,
    final double maxY,
    final int numPointsPerSegment,
    final MathTransform gridToCRS) throws MismatchedDimensionException, TransformException {
  final Point2D[] gridCoordinates =
      getGridCoordinates(minX, minY, maxX, maxY, numPointsPerSegment);
  final Coordinate[] worldCoordinates = new Coordinate[gridCoordinates.length];
  for (int i = 0; i < gridCoordinates.length; i++) {
    final DirectPosition2D worldPt = new DirectPosition2D();
    final DirectPosition2D dp = new DirectPosition2D(gridCoordinates[i]);
    gridToCRS.transform(dp, worldPt);
    worldCoordinates[i] = new Coordinate(worldPt.getX(), worldPt.getY());
  }
  return worldCoordinates;
}
 
Example #5
Source File: AbstractDerivedCRS.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * For {@link DefaultDerivedCRS#DefaultDerivedCRS(Map, SingleCRS, CoordinateReferenceSystem, OperationMethod,
 * MathTransform, CoordinateSystem)} constructor only (<strong>not legal for {@code ProjectedCRS}</strong>).
 */
@SuppressWarnings("unchecked")
AbstractDerivedCRS(final Map<String,?>             properties,
                   final SingleCRS                 baseCRS,
                   final CoordinateReferenceSystem interpolationCRS,
                   final OperationMethod           method,
                   final MathTransform             baseToDerived,
                   final CoordinateSystem          derivedCS)
        throws MismatchedDimensionException
{
    super(properties, derivedCS);
    ArgumentChecks.ensureNonNull("baseCRS", baseCRS);
    ArgumentChecks.ensureNonNull("method", method);
    ArgumentChecks.ensureNonNull("baseToDerived", baseToDerived);
    conversionFromBase = (C) new DefaultConversion(   // Cast to (C) is valid only for DefaultDerivedCRS.
            ConversionKeys.unprefix(properties), baseCRS, this, interpolationCRS, method, baseToDerived);
}
 
Example #6
Source File: GeometryUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
public static SimpleFeature crsTransform(
    final SimpleFeature entry,
    final SimpleFeatureType reprojectedType,
    final MathTransform transform) {
  SimpleFeature crsEntry = entry;

  if (transform != null) {
    // we can use the transform we have already calculated for this
    // feature
    try {

      // this will clone the feature and retype it to Index CRS
      crsEntry = SimpleFeatureBuilder.retype(entry, reprojectedType);

      // this will transform the geometry
      crsEntry.setDefaultGeometry(
          JTS.transform((Geometry) entry.getDefaultGeometry(), transform));
    } catch (MismatchedDimensionException | TransformException e) {
      LOGGER.warn(
          "Unable to perform transform to specified CRS of the index, the feature geometry will remain in its original CRS",
          e);
    }
  }

  return crsEntry;
}
 
Example #7
Source File: AbstractDirectPosition.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Sets this direct position to the given position. If the given position is
 * {@code null}, then all coordinate values are set to {@link Double#NaN NaN}.
 *
 * <p>If this position and the given position have a non-null CRS, then the default implementation
 * requires the CRS to be {@linkplain Utilities#equalsIgnoreMetadata equals (ignoring metadata)},
 * otherwise a {@code MismatchedReferenceSystemException} is thrown. However subclass may choose
 * to assign the CRS of this position to the CRS of the given position.</p>
 *
 * @param  position  the new position, or {@code null}.
 * @throws MismatchedDimensionException if the given position doesn't have the expected dimension.
 * @throws MismatchedReferenceSystemException if the given position doesn't use the expected CRS.
 */
public void setLocation(final DirectPosition position)
        throws MismatchedDimensionException, MismatchedReferenceSystemException
{
    final int dimension = getDimension();
    if (position != null) {
        ensureDimensionMatches("position", dimension, position);
        final CoordinateReferenceSystem crs = getCoordinateReferenceSystem();
        if (crs != null) {
            final CoordinateReferenceSystem other = position.getCoordinateReferenceSystem();
            if (other != null && !Utilities.equalsIgnoreMetadata(crs, other)) {
                throw new MismatchedReferenceSystemException(Errors.format(Errors.Keys.MismatchedCRS));
            }
        }
        for (int i=0; i<dimension; i++) {
            setOrdinate(i, position.getOrdinate(i));
        }
    } else {
        for (int i=0; i<dimension; i++) {
            setOrdinate(i, Double.NaN);
        }
    }
}
 
Example #8
Source File: DatumShiftTransform.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures that the {@link #grid} performs geocentric translations in the given units.
 * This method is invoked by constructor for validation of given arguments.
 *
 * <p>This method is defined here in order to ensure a consistent behavior of
 * {@link InterpolatedGeocentricTransform} with {@link InterpolatedMolodenskyTransform}.</p>
 *
 * @param  grid  the grid to validate.
 * @param  unit  the unit of semi-axis length of the <strong>source</strong> ellipsoid.
 * @throws IllegalArgumentException if the given grid is not valid.
 */
static void ensureGeocentricTranslation(final DatumShiftGrid<?,?> grid, final Unit<Length> unit)
        throws IllegalArgumentException
{
    final int dim = grid.getTranslationDimensions();
    if (dim != 3) {
        throw new MismatchedDimensionException(Errors.format(Errors.Keys.MismatchedDimension_3, "grid", 3, dim));
    }
    Object unitLabel = "ratio";
    if (grid.isCellValueRatio() || (unitLabel = grid.getTranslationUnit()) != unit) {
        throw new IllegalArgumentException(Resources.format(Resources.Keys.IllegalUnitFor_2, "translation", unitLabel));
    }
}
 
Example #9
Source File: GridGeometry.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures that the given dimension is equals to the expected value. If not, throws an exception.
 * This method assumes that the argument name is {@code "extent"}.
 *
 * @param extent    the extent to validate, or {@code null} if none.
 * @param expected  the expected number of dimension.
 */
private static void ensureDimensionMatches(final int expected, final GridExtent extent) throws MismatchedDimensionException {
    if (extent != null) {
        final int dimension = extent.getDimension();
        if (dimension != expected) {
            throw new MismatchedDimensionException(Errors.format(
                    Errors.Keys.MismatchedDimension_3, "extent", expected, dimension));
        }
    }
}
 
Example #10
Source File: Plane.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Computes the values of all {@code sum_*} fields from randomly distributed points.
 * Value of all other fields are undetermined..
 */
Fit(final Iterable<? extends DirectPosition> points) {
    int i = 0, n = 0;
    for (final DirectPosition p : points) {
        final int dimension = p.getDimension();
        if (dimension != DIMENSION) {
            throw new MismatchedDimensionException(Errors.format(Errors.Keys.MismatchedDimension_3,
                        Strings.toIndexed("points", i), DIMENSION, dimension));
        }
        i++;
        final double x = p.getOrdinate(0); if (Double.isNaN(x)) continue;
        final double y = p.getOrdinate(1); if (Double.isNaN(y)) continue;
        final double z = p.getOrdinate(2); if (Double.isNaN(z)) continue;
        xx.setToProduct(x, x);
        yy.setToProduct(y, y);
        xy.setToProduct(x, y);
        zx.setToProduct(z, x);
        zy.setToProduct(z, y);
        sum_x .add(x );
        sum_y .add(y );
        sum_z .add(z );
        sum_xx.add(xx);
        sum_yy.add(yy);
        sum_xy.add(xy);
        sum_zx.add(zx);
        sum_zy.add(zy);
        n++;
    }
    this.n = n;
}
 
Example #11
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 #12
Source File: RasterUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static Geometry getFootprint(
    final ReferencedEnvelope projectedReferenceEnvelope,
    final GridCoverage gridCoverage) {
  try {
    final Envelope sampleEnvelope = gridCoverage.getEnvelope();
    final double avgSpan =
        (projectedReferenceEnvelope.getSpan(0) + projectedReferenceEnvelope.getSpan(1)) / 2;
    final MathTransform gridCrsToWorldCrs =
        CRS.findMathTransform(
            gridCoverage.getCoordinateReferenceSystem(),
            projectedReferenceEnvelope.getCoordinateReferenceSystem(),
            true);
    final Coordinate[] polyCoords =
        getWorldCoordinates(
            sampleEnvelope.getMinimum(0),
            sampleEnvelope.getMinimum(1),
            sampleEnvelope.getMaximum(0),
            sampleEnvelope.getMaximum(1),
            gridCrsToWorldCrs.isIdentity() ? 2
                : (int) Math.min(
                    Math.max((avgSpan * MIN_SEGMENTS) / SIMPLIFICATION_MAX_DEGREES, MIN_SEGMENTS),
                    MAX_SEGMENTS),
            gridCrsToWorldCrs);
    final Polygon poly = new GeometryFactory().createPolygon(polyCoords);
    if (polyCoords.length > MAX_VERTICES_BEFORE_SIMPLIFICATION) {
      final Geometry retVal = DouglasPeuckerSimplifier.simplify(poly, SIMPLIFICATION_MAX_DEGREES);
      if (retVal.isEmpty()) {
        return poly;
      }
      return retVal;
    } else {
      return poly;
    }
  } catch (MismatchedDimensionException | TransformException | FactoryException e1) {
    LOGGER.warn("Unable to calculate grid coverage footprint", e1);
  }
  return null;
}
 
Example #13
Source File: GeometryUtility.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Project geometry.
 *
 * @param originalGeom
 *            the original geom
 * @param srcCRSCode
 *            the src crs code
 * @param trgCRSCode
 *            the trg crs code
 * @return the geometry
 * @throws NoSuchAuthorityCodeException
 *             the no such authority code exception
 * @throws FactoryException
 *             the factory exception
 * @throws MismatchedDimensionException
 *             the mismatched dimension exception
 * @throws TransformException
 *             the transform exception
 */
public static Geometry projectGeometry(Geometry originalGeom, String srcCRSCode,
    String trgCRSCode) throws NoSuchAuthorityCodeException, FactoryException, MismatchedDimensionException,
    TransformException
{

    Geometry projectedGeometry = null;
    final MathTransform transform = CRS.findMathTransform(CRS.decode(srcCRSCode, true), CRS.decode(trgCRSCode, true), true);

    // converting geometries into a linear system
    try
    {
        projectedGeometry = JTS.transform(originalGeom, transform);
    }
    catch (Exception e)
    {
        GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(
                    PrecisionModel.FLOATING), 4326);
        WKTReader reader = new WKTReader(geometryFactory);

        try
        {
            Polygon worldCutPolygon = (Polygon) reader.read("POLYGON((-180 -89.9, -180 89.9, 180 89.9, 180 -89.9, -180 -89.9))");

            projectedGeometry = JTS.transform(originalGeom.intersection(worldCutPolygon),
                    transform);
        }
        catch (Exception ex)
        {
            throw new RuntimeException(ex);
        }
    }

    return projectedGeometry;
}
 
Example #14
Source File: ExtractGeometryFilterVisitor.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public Object visit(final BBOX filter, final Object data) {
  if (attributeOfInterest.equals(filter.getExpression1().toString())) {
    final Geometry bbox = bbox(data);
    final BoundingBox referencedBBox = filter.getBounds();
    Geometry bounds =
        new GeometryFactory().toGeometry(
            new Envelope(
                referencedBBox.getMinX(),
                referencedBBox.getMaxX(),
                referencedBBox.getMinY(),
                referencedBBox.getMaxY()));

    if ((crs != null)
        && (referencedBBox.getCoordinateReferenceSystem() != null)
        && !crs.equals(referencedBBox.getCoordinateReferenceSystem())) {
      try {
        bounds =
            JTS.transform(
                bounds,
                CRS.findMathTransform(referencedBBox.getCoordinateReferenceSystem(), crs, true));
      } catch (MismatchedDimensionException | TransformException | FactoryException e) {
        LOGGER.error("Unable to transforma bbox", e);
      }
    }
    if (bbox != null) {
      return bbox.union(bounds);
    } else {
      return new ExtractGeometryFilterVisitorResult(bounds, CompareOperation.INTERSECTS);
    }
  } else {
    return new ExtractGeometryFilterVisitorResult(infinity(), null);
  }
}
 
Example #15
Source File: GeoServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public CrsTransform getCrsTransform(Crs sourceCrs, Crs targetCrs) throws GeomajasException {
	String key = getTransformKey(sourceCrs, targetCrs);
	CrsTransform transform = transformCache.get(key);
	if (null == transform) {
		MathTransform mathTransform = getBaseMathTransform(sourceCrs, targetCrs);

		// as there was no transformable area configured, try to build it instead
		Envelope transformableArea = null;
		try {
			org.opengis.geometry.Envelope ogEnvelope = CRS.getEnvelope(targetCrs);
			if (null != ogEnvelope) {
				Envelope envelope = new Envelope(ogEnvelope.getLowerCorner().getCoordinate()[0], ogEnvelope
						.getUpperCorner().getCoordinate()[0], ogEnvelope.getLowerCorner().getCoordinate()[1],
						ogEnvelope.getUpperCorner().getCoordinate()[1]);
				log.debug("CRS " + targetCrs.getId() + " envelope " + envelope);
				ReferencedEnvelope refEnvelope = new ReferencedEnvelope(envelope, targetCrs);
				transformableArea = refEnvelope.transform(sourceCrs, true);
				log.debug("transformable area for " + key + " is " + transformableArea);
			}
		} catch (MismatchedDimensionException mde) {
			log.warn(WARN_TRANSFORMABLE_AREA, new Object[] {sourceCrs.getId(), targetCrs.getId(),
					mde.getMessage()});
		} catch (TransformException te) {
			log.warn(WARN_TRANSFORMABLE_AREA, new Object[] {sourceCrs.getId(), targetCrs.getId(),
					te.getMessage()});
		} catch (FactoryException fe) {
			log.warn(WARN_TRANSFORMABLE_AREA, new Object[] {sourceCrs.getId(), targetCrs.getId(),
					fe.getMessage()});
		}

		transform = new CrsTransformImpl(key, sourceCrs, targetCrs, mathTransform, transformableArea);
		transformCache.put(key, transform);
	}
	return transform;
}
 
Example #16
Source File: GridCoverageUtilTest.java    From elasticgeo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testCrop() throws MismatchedDimensionException {
    float[][] grid = new float[][] {{3,4},{1,2}};
    final GridCoverageFactory coverageFactory = CoverageFactoryFinder.getGridCoverageFactory(GeoTools.getDefaultHints());
    final GridCoverage2D coverage = coverageFactory.create("geohashGridAgg", grid, new ReferencedEnvelope(0,20,0,20,null));
    final ReferencedEnvelope envelope = new ReferencedEnvelope(10,20,10,20,null);
    final GridCoverage2D croppedCoverage = GridCoverageUtil.crop(coverage, envelope);
    final RenderedImage renderedImage = croppedCoverage.getRenderedImage();
    assertEquals(1, renderedImage.getWidth());
    assertEquals(1, renderedImage.getHeight());
    assertEquals(4, croppedCoverage.evaluate(new Point2D.Double(15,15), new float[1])[0], 1e-10);
}
 
Example #17
Source File: CoordinateUtils.java    From TomboloDigitalConnector with MIT License 5 votes vote down vote up
public static Coordinate eastNorthToLatLong(double x, double y, String sourceCrs, String targetCrs) throws FactoryException, MismatchedDimensionException, TransformException {
    CoordinateReferenceSystem targetCrsDecoded = CRS.decode(targetCrs);
    CoordinateReferenceSystem sourceCrsDecoded = CRS.decode(sourceCrs);

    CoordinateOperation op = new DefaultCoordinateOperationFactory().createOperation(sourceCrsDecoded, targetCrsDecoded);

    DirectPosition source = new GeneralDirectPosition(x, y);
    DirectPosition target = op.getMathTransform().transform(source, null);
    Double targetX = target.getOrdinate(0);
    Double targetY = target.getOrdinate(1);

    return new Coordinate(targetY, targetX);
}
 
Example #18
Source File: SpecializableTransform.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method for verifying transform dimension consistency.
 *
 * @param  type  0 if verifying source dimension, or 1 if verifying target dimension.
 */
private static void ensureDimensionMatches(final int type, final int expected, final int actual) {
    if (expected != actual) {
        throw new MismatchedDimensionException(Resources.format(
                Resources.Keys.MismatchedTransformDimension_3, type, expected, actual));
    }
}
 
Example #19
Source File: LinearTransformBuilder.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the given number of dimensions is equal to the expected value.
 * No verification are done if the source point is the first point of randomly distributed points.
 */
private void verifySourceDimension(final int actual) throws MismatchedDimensionException {
    final int expected;
    if (gridSize != null) {
        expected = gridSize.length;
    } else if (sources != null) {
        expected = sources.length;
    } else {
        return;
    }
    if (actual != expected) {
        throw new MismatchedDimensionException(Errors.format(Errors.Keys.MismatchedDimension_3, "source", expected, actual));
    }
}
 
Example #20
Source File: TransformResultComparator.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Delegates to the tested implementation and verifies that the value is equals
 * to the one provided by the reference implementation.
 */
@Override
public Matrix derivative(DirectPosition point) throws MismatchedDimensionException, TransformException {
    final Matrix value = tested.derivative(point);
    assertMatrixEquals("derivative", reference.derivative(point), value, tolerance);
    return value;
}
 
Example #21
Source File: GeneralEnvelope.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Sets this envelope to the same coordinate values than the specified envelope.
 * If the given envelope has a non-null Coordinate Reference System (CRS), then
 * the CRS of this envelope will be set to the CRS of the given envelope.
 *
 * @param  envelope  the envelope to copy coordinates from.
 * @throws MismatchedDimensionException if the specified envelope doesn't have
 *         the expected number of dimensions.
 */
public void setEnvelope(final Envelope envelope) throws MismatchedDimensionException {
    if (envelope == this) {
        return;     // Optimization for methods chaining like env.setEnvelope(Envelopes.transform(env, crs))
    }
    ensureNonNull("envelope", envelope);
    final int beginIndex = beginIndex();
    final int dimension = endIndex() - beginIndex;
    ensureDimensionMatches("envelope", dimension, envelope);
    final int d = coordinates.length >>> 1;
    if (envelope instanceof ArrayEnvelope) {
        /*
         * Optimization for a common case. This code path is used by Envelopes.compound(…).
         * The main intent is to avoid the creation of temporary DirectPosition objects.
         */
        final double[] source = ((ArrayEnvelope) envelope).coordinates;
        final int srcOffset = ((ArrayEnvelope) envelope).beginIndex();
        System.arraycopy(source, srcOffset, coordinates, beginIndex, dimension);
        System.arraycopy(source, srcOffset + (source.length >>> 1), coordinates, beginIndex + d, dimension);
    } else {
        @SuppressWarnings("null")
        final DirectPosition lower = envelope.getLowerCorner();
        final DirectPosition upper = envelope.getUpperCorner();
        for (int i=0; i<dimension; i++) {
            final int iLower = beginIndex + i;
            final int iUpper = iLower + d;
            coordinates[iLower] = lower.getOrdinate(i);
            coordinates[iUpper] = upper.getOrdinate(i);
        }
    }
    final CoordinateReferenceSystem envelopeCRS = envelope.getCoordinateReferenceSystem();
    if (envelopeCRS != null) {
        crs = envelopeCRS;
        assert crs.getCoordinateSystem().getDimension() == getDimension() : crs;
        assert envelope.getClass() != getClass() || equals(envelope) : envelope;
    }
}
 
Example #22
Source File: DefaultDerivedCRS.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a derived CRS from a defining conversion and a type inferred from the given arguments.
 * This method expects the same arguments and performs the same work than the
 * {@linkplain #DefaultDerivedCRS(Map, SingleCRS, Conversion, CoordinateSystem) above constructor},
 * except that the {@code DerivedCRS} instance returned by this method may additionally implement
 * the {@link GeodeticCRS}, {@link VerticalCRS}, {@link TemporalCRS}, {@link ParametricCRS} or
 * {@link EngineeringCRS} interface.
 * See the class javadoc for more information.
 *
 * @param  properties  the properties to be given to the new derived CRS object.
 * @param  baseCRS     coordinate reference system to base the derived CRS on.
 * @param  conversion  the defining conversion from a normalized base to a normalized derived CRS.
 * @param  derivedCS   the coordinate system for the derived CRS. The number of axes
 *                     must match the target dimension of the {@code baseToDerived} transform.
 * @return the newly created derived CRS, potentially implementing an additional CRS interface.
 * @throws MismatchedDimensionException if the source and target dimensions of {@code baseToDerived}
 *         do not match the dimensions of {@code base} and {@code derivedCS} respectively.
 *
 * @see #DefaultDerivedCRS(Map, SingleCRS, Conversion, CoordinateSystem)
 * @see org.apache.sis.referencing.factory.GeodeticObjectFactory#createDerivedCRS(Map, CoordinateReferenceSystem, Conversion, CoordinateSystem)
 */
public static DefaultDerivedCRS create(final Map<String,?>    properties,
                                       final SingleCRS        baseCRS,
                                       final Conversion       conversion,
                                       final CoordinateSystem derivedCS)
        throws MismatchedDimensionException
{
    if (baseCRS != null && derivedCS != null) {
        final String type = getType(baseCRS, derivedCS);
        if (type != null) switch (type) {
            case WKTKeywords.GeodeticCRS:   return new Geodetic  (properties, (GeodeticCRS)   baseCRS, conversion,                derivedCS);
            case WKTKeywords.VerticalCRS:   return new Vertical  (properties, (VerticalCRS)   baseCRS, conversion,   (VerticalCS) derivedCS);
            case WKTKeywords.TimeCRS:       return new Temporal  (properties, (TemporalCRS)   baseCRS, conversion,       (TimeCS) derivedCS);
            case WKTKeywords.ParametricCRS: return new Parametric(properties, (ParametricCRS) baseCRS, conversion, (DefaultParametricCS) derivedCS);
            case WKTKeywords.EngineeringCRS: {
                /*
                 * This case may happen for baseCRS of kind GeodeticCRS, ProjectedCRS or EngineeringCRS.
                 * But only the later is associated to EngineeringDatum; the two formers are associated
                 * to GeodeticDatum. Consequently we can implement the EngineeringCRS.getDatum() method
                 * only if the base CRS is itself of kind EngineeringCRS.  Otherwise we will return the
                 * "type-neutral" DefaultDerivedCRS implementation.   Note that even in the later case,
                 * the WKT format will still be able to detect that the WKT keyword is "EngineeringCRS".
                 */
                if (baseCRS instanceof EngineeringCRS) {
                    return new Engineering(properties, (EngineeringCRS) baseCRS, conversion, derivedCS);
                }
                break;
            }
        }
    }
    return new DefaultDerivedCRS(properties, baseCRS, conversion, derivedCS);
}
 
Example #23
Source File: GeneralEnvelope.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the given array of coordinate values has the expected length
 * for the given number of dimensions.
 *
 * @param  dimension  the dimension of the envelope.
 * @param  corners    the user-provided array of coordinate values.
 */
static void verifyArrayLength(final int dimension, final double[] corners) {
    if ((corners.length & 1) != 0) {
        throw new IllegalArgumentException(Errors.format(
                Errors.Keys.OddArrayLength_1, corners.length));
    }
    final int d = corners.length >>> 1;
    if (d != dimension) {
        throw new MismatchedDimensionException(Errors.format(
                Errors.Keys.MismatchedDimension_3, "coordinates", dimension, d));
    }
}
 
Example #24
Source File: GeneralEnvelope.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the coordinate reference system in which the coordinate are given.
 * This method <strong>does not</strong> reproject the envelope, and does
 * not check if the envelope is contained in the new domain of validity.
 *
 * <p>If the envelope coordinates need to be transformed to the new CRS, consider
 * using {@link Envelopes#transform(Envelope, CoordinateReferenceSystem)} instead.</p>
 *
 * @param  crs  the new coordinate reference system, or {@code null}.
 * @throws MismatchedDimensionException if the specified CRS doesn't have the expected number of dimensions.
 * @throws IllegalStateException if a range of coordinate values in this envelope is compatible with the given CRS.
 *         See <cite>Envelope validation</cite> in class javadoc for more details.
 */
public void setCoordinateReferenceSystem(final CoordinateReferenceSystem crs)
        throws MismatchedDimensionException
{
    if (crs != null) {
        ensureDimensionMatches("crs", getDimension(), crs);
        /*
         * The check performed here shall be identical to ArrayEnvelope.verifyRanges(crs, coordinates)
         * except that it may verify only a subset of the coordinate array and throws a different kind
         * of exception in case of failure.
         */
        final int beginIndex = beginIndex();
        final int endIndex = endIndex();
        final int d = coordinates.length >>> 1;
        for (int i=beginIndex; i<endIndex; i++) {
            final double lower = coordinates[i];
            final double upper = coordinates[i + d];
            if (lower > upper) {
                final int j = i - beginIndex;
                if (!isWrapAround(crs, j)) {
                    throw new IllegalStateException(illegalRange(crs, j, lower, upper));
                }
            }
        }
    }
    this.crs = crs;                                             // Set only on success.
}
 
Example #25
Source File: AbstractEnvelope.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests if a specified coordinate is inside the boundary of this envelope.
 * Both lower and upper values of this envelope are considered inclusive.
 * If it least one coordinate value in the given point is {@link Double#NaN NaN},
 * then this method returns {@code false}.
 *
 * <h4>Pre-conditions</h4>
 * This method assumes that the specified point uses the same CRS than this envelope.
 * For performance reasons, it will no be verified unless Java assertions are enabled.
 *
 * <h4>Spanning the anti-meridian of a Geographic CRS</h4>
 * For any dimension, if <var>upper</var> &lt; <var>lower</var> then this method uses an
 * algorithm which is the opposite of the usual one: rather than testing if the given point is
 * inside the envelope interior, this method tests if the given point is <em>outside</em> the
 * envelope <em>exterior</em>.
 *
 * @param  position  the point to text.
 * @return {@code true} if the specified coordinate is inside the boundary of this envelope; {@code false} otherwise.
 * @throws MismatchedDimensionException if the specified point does not have the expected number of dimensions.
 * @throws AssertionError if assertions are enabled and the envelopes have mismatched CRS.
 */
public boolean contains(final DirectPosition position) throws MismatchedDimensionException {
    ensureNonNull("position", position);
    final int dimension = getDimension();
    ensureDimensionMatches("point", dimension, position);
    assert equalsIgnoreMetadata(getCoordinateReferenceSystem(),
            position.getCoordinateReferenceSystem(), true) : position;
    for (int i=0; i<dimension; i++) {
        final double value = position.getOrdinate(i);
        final double lower = getLower(i);
        final double upper = getUpper(i);
        final boolean c1   = (value >= lower);
        final boolean c2   = (value <= upper);
        if (c1 & c2) {
            continue;               // Point inside the range, check other dimensions.
        }
        if (c1 | c2) {
            if (isNegative(upper - lower)) {
                /*
                 * "Spanning the anti-meridian" case: if we reach this point, then the
                 * [upper...lower] range  (note the 'lower' and 'upper' interchanging)
                 * is actually a space outside the envelope and we have checked that
                 * the coordinate value is outside that space.
                 */
                continue;
            }
        }
        return false;
    }
    return true;
}
 
Example #26
Source File: ArrayEnvelope.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Makes sure the specified dimensions are identical.
 */
static void ensureSameDimension(final int dim1, final int dim2) throws MismatchedDimensionException {
    if (dim1 != dim2) {
        throw new MismatchedDimensionException(Errors.format(
                Errors.Keys.MismatchedDimension_2, dim1, dim2));
    }
}
 
Example #27
Source File: ArrayEnvelope.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an envelope defined by two corners given as direct positions.
 * If at least one corner is associated to a CRS, then the new envelope will also
 * be associated to that CRS.
 *
 * @param  lowerCorner  the limits in the direction of decreasing coordinate values for each dimension.
 * @param  upperCorner  the limits in the direction of increasing coordinate values for each dimension.
 * @throws MismatchedDimensionException if the two positions do not have the same dimension.
 * @throws MismatchedReferenceSystemException if the CRS of the two position are not equal.
 */
public ArrayEnvelope(final DirectPosition lowerCorner, final DirectPosition upperCorner)
        throws MismatchedDimensionException, MismatchedReferenceSystemException
{
    crs = getCommonCRS(lowerCorner, upperCorner);           // This performs also an argument check.
    final int dimension = lowerCorner.getDimension();
    ensureDimensionMatches("crs", dimension, crs);
    ensureSameDimension(dimension, upperCorner.getDimension());
    coordinates = new double[dimension * 2];
    for (int i=0; i<dimension; i++) {
        coordinates[i            ] = lowerCorner.getOrdinate(i);
        coordinates[i + dimension] = upperCorner.getOrdinate(i);
    }
    verifyRanges(crs, coordinates);
}
 
Example #28
Source File: GeneralDirectPosition.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Sets this coordinate to the specified direct position. If the specified position
 * contains a coordinate reference system (CRS), then the CRS for this position will
 * be set to the CRS of the specified position.
 *
 * @param  position  the new position for this point,
 *                   or {@code null} for setting all coordinate values to {@link Double#NaN NaN}.
 * @throws MismatchedDimensionException if the given position does not have the expected dimension.
 */
@Override
public void setLocation(final DirectPosition position) throws MismatchedDimensionException {
    if (position == null) {
        Arrays.fill(coordinates, Double.NaN);
    } else {
        ensureDimensionMatches("position", coordinates.length, position);
        setCoordinateReferenceSystem(position.getCoordinateReferenceSystem());
        for (int i=0; i<coordinates.length; i++) {
            coordinates[i] = position.getOrdinate(i);
        }
    }
}
 
Example #29
Source File: GeneralDirectPosition.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the coordinate values along all dimensions.
 *
 * @param  coordinates  the new coordinates values, or a {@code null} array for
 *                      setting all coordinate values to {@link Double#NaN NaN}.
 * @throws MismatchedDimensionException if the length of the specified array is not
 *         equals to the {@linkplain #getDimension() dimension} of this position.
 */
public void setCoordinate(final double... coordinates) throws MismatchedDimensionException {
    if (coordinates == null) {
        Arrays.fill(this.coordinates, Double.NaN);
    } else {
        ensureDimensionMatches("coordinates", this.coordinates.length, coordinates);
        System.arraycopy(coordinates, 0, this.coordinates, 0, coordinates.length);
    }
}
 
Example #30
Source File: GeneralDirectPosition.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the coordinate reference system in which the coordinate is given.
 *
 * @param  crs  the new coordinate reference system, or {@code null}.
 * @throws MismatchedDimensionException if the specified CRS does not have the expected number of dimensions.
 */
public void setCoordinateReferenceSystem(final CoordinateReferenceSystem crs)
        throws MismatchedDimensionException
{
    ensureDimensionMatches("crs", getDimension(), crs);
    this.crs = crs;
}