org.opengis.referencing.operation.MathTransform Java Examples

The following examples show how to use org.opengis.referencing.operation.MathTransform. 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: GridDerivationTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@link GridDerivation#subgrid(Envelope, double...)} using only the
 * {@link GridExtent} result provided by {@link GridDerivation#getIntersection()}.
 */
@Test
public void testSubExtent() {
    GeneralEnvelope envelope = new GeneralEnvelope(HardCodedCRS.WGS84_3D);
    envelope.setRange(0, -80, 120);
    envelope.setRange(1, -12,  21);
    envelope.setRange(2,  10,  25);
    final MathTransform gridToCRS = MathTransforms.linear(new Matrix4(
            0,   0.5, 0,  -90,
            0.5, 0,   0, -180,
            0,   0,   2,    3,
            0,   0,   0,    1));
    final GridGeometry grid = new GridGeometry(PixelInCell.CELL_CORNER, gridToCRS, envelope, GridRoundingMode.NEAREST);
    assertExtentEquals(
            new long[] {336,  20,  4},
            new long[] {401, 419, 10}, grid.getExtent());
    /*
     * Set the region of interest as a two-dimensional envelope. The vertical dimension is omitted.
     * The result should be that all grid indices in the vertical dimension are kept unchanged.
     */
    envelope = new GeneralEnvelope(HardCodedCRS.WGS84);
    envelope.setRange(0, -70.001, +80.002);
    envelope.setRange(1,   4.997,  15.003);
    assertExtentEquals(new long[] {370,  40,  4},
                       new long[] {389, 339, 10}, grid.derive().subgrid(envelope).getIntersection());
}
 
Example #2
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 #3
Source File: DefaultMathTransformFactory.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a transform by concatenating two existing transforms.
 * A concatenated transform acts in the same way as applying two transforms, one after the other.
 *
 * <p>The dimension of the output space of the first transform must match the dimension of the input space
 * in the second transform. In order to concatenate more than two transforms, use this constructor repeatedly.</p>
 *
 * @param  tr1  the first transform to apply to points.
 * @param  tr2  the second transform to apply to points.
 * @return the concatenated transform.
 * @throws FactoryException if the object creation failed.
 *
 * @see MathTransforms#concatenate(MathTransform, MathTransform)
 */
@Override
public MathTransform createConcatenatedTransform(final MathTransform tr1,
                                                 final MathTransform tr2)
        throws FactoryException
{
    lastMethod.remove();
    ArgumentChecks.ensureNonNull("tr1", tr1);
    ArgumentChecks.ensureNonNull("tr2", tr2);
    final MathTransform tr;
    try {
        tr = ConcatenatedTransform.create(tr1, tr2, this);
    } catch (IllegalArgumentException exception) {
        throw new InvalidGeodeticParameterException(exception.getLocalizedMessage(), exception);
    }
    assert MathTransforms.isValid(MathTransforms.getSteps(tr)) : tr;
    return unique(tr);
}
 
Example #4
Source File: NormalizedProjection.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Concatenates or pre-concatenates in an optimized way this projection with the given transform, if possible.
 * If no optimization is available, returns {@code null}.
 */
@Override
protected MathTransform tryConcatenate(final boolean applyOtherFirst, final MathTransform other,
        final MathTransformFactory factory) throws FactoryException
{
    final Matrix m = getMiddleMatrix(this, other, applyOtherFirst);
    if (m != null) {
        /*
         * 'projectedSpace' values:
         *   - false if applyOtherFirst == false since we have (inverse projection) → (affine) → (projection).
         *   - true  if applyOtherFirst == true  since we have (projection) → (affine) → (inverse projection).
         */
        return forward.tryConcatenate(applyOtherFirst, m, factory);
    }
    return super.tryConcatenate(applyOtherFirst, other, factory);
}
 
Example #5
Source File: AbstractCoordinateOperation.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the parameter descriptors for the given transform, or {@code null} if unknown.
 */
static ParameterDescriptorGroup getParameterDescriptors(MathTransform transform) {
    while (transform != null) {
        if (transform instanceof Parameterized) {
            final ParameterDescriptorGroup param;
            if (Semaphores.queryAndSet(Semaphores.ENCLOSED_IN_OPERATION)) {
                throw new AssertionError();                                     // Should never happen.
            }
            try {
                param = ((Parameterized) transform).getParameterDescriptors();
            } finally {
                Semaphores.clear(Semaphores.ENCLOSED_IN_OPERATION);
            }
            if (param != null) {
                return param;
            }
        }
        if (transform instanceof PassThroughTransform) {
            transform = ((PassThroughTransform) transform).getSubTransform();
        } else {
            break;
        }
    }
    return null;
}
 
Example #6
Source File: GeocentricAffine.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a math transform from the specified group of parameter values.
 * The default implementation creates an affine transform, but some subclasses
 * will wrap that affine operation into Geographic/Geocentric conversions.
 *
 * @param  factory  the factory to use for creating concatenated transforms.
 * @param  values   the group of parameter values.
 * @return the created math transform.
 * @throws FactoryException if a transform can not be created.
 */
@Override
@SuppressWarnings("fallthrough")
public MathTransform createMathTransform(final MathTransformFactory factory, final ParameterValueGroup values)
        throws FactoryException
{
    final BursaWolfParameters parameters = new BursaWolfParameters(null, null);
    final Parameters pv = Parameters.castOrWrap(values);
    boolean reverseRotation = false;
    switch (getType()) {
        default:             throw new AssertionError();
        case FRAME_ROTATION: reverseRotation = true;                    // Fall through
        case SEVEN_PARAM:    parameters.rX = pv.doubleValue(RX);
                             parameters.rY = pv.doubleValue(RY);
                             parameters.rZ = pv.doubleValue(RZ);
                             parameters.dS = pv.doubleValue(DS);
        case TRANSLATION:    parameters.tX = pv.doubleValue(TX);        // Fall through
                             parameters.tY = pv.doubleValue(TY);
                             parameters.tZ = pv.doubleValue(TZ);
    }
    if (reverseRotation) {
        parameters.reverseRotation();
    }
    return MathTransforms.linear(parameters.getPositionVectorTransformation(null));
}
 
Example #7
Source File: ConcatenatedTransformTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the concatenation of a 3D affine transform with a pass-through transform.
 * The {@link ConcatenatedTransform#create(MathTransform, MathTransform, MathTransformFactory)}
 * method should optimize this case.
 *
 * @throws FactoryException if an error occurred while creating the math transform to test.
 */
@Test
public void testPassthrough() throws FactoryException {
    final MathTransform kernel = new PseudoTransform(2, 3);                     // Any non-linear transform.
    final MathTransform passth = MathTransforms.passThrough(0, kernel, 1);
    final Matrix4 matrix = new Matrix4();
    transform = ConcatenatedTransform.create(MathTransforms.linear(matrix), passth, null);
    assertSame("Identity transform should be ignored.", passth, transform);
    assertEquals("Source dimensions", 3, transform.getSourceDimensions());
    assertEquals("Target dimensions", 4, transform.getTargetDimensions());
    /*
     * Put scale or offset factors only in the dimension to be processed by the sub-transform.
     * The matrix should be concatenated to the sub-transform rather than to the passthrough
     * transform.
     */
    matrix.m00 = 3;
    matrix.m13 = 2;
    transform = ConcatenatedTransform.create(MathTransforms.linear(matrix), passth, null);
    assertInstanceOf("Expected a new passthrough transform.", PassThroughTransform.class, transform);
    final MathTransform subTransform = ((PassThroughTransform) transform).subTransform;
    assertInstanceOf("Expected a new concatenated transform.", ConcatenatedTransform.class, subTransform);
    assertSame(kernel, ((ConcatenatedTransform) subTransform).transform2);
    assertEquals("Source dimensions", 3, transform.getSourceDimensions());
    assertEquals("Target dimensions", 4, transform.getTargetDimensions());
    /*
     * Put scale or offset factors is a passthrough dimension. Now, the affine transform
     * can not anymore be concatenated with the sub-transform.
     */
    matrix.m22 = 4;
    transform = ConcatenatedTransform.create(MathTransforms.linear(matrix), passth, null);
    assertInstanceOf("Expected a new concatenated transform.", ConcatenatedTransform.class, transform);
    assertSame(passth, ((ConcatenatedTransform) transform).transform2);
    assertEquals("Source dimensions", 3, transform.getSourceDimensions());
    assertEquals("Target dimensions", 4, transform.getTargetDimensions());
}
 
Example #8
Source File: RasterUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the math transform as a two-dimensional affine transform.
 *
 * @return The math transform as a two-dimensional affine transform.
 * @throws IllegalStateException if the math transform is not of the appropriate type.
 */
public static AffineTransform createAffineTransform(
    final double[] idRangePerDimension,
    final MultiDimensionalNumericData fullBounds) throws IllegalStateException {
  final MathTransform transform = createTransform(idRangePerDimension, fullBounds);
  if (transform instanceof AffineTransform) {
    return (AffineTransform) transform;
  }
  throw new IllegalStateException(Errors.format(ErrorKeys.NOT_AN_AFFINE_TRANSFORM));
}
 
Example #9
Source File: AbstractLinearTransform.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an identity transform if this transform is the inverse of the given transform.
 * If this method is unsure, it conservatively returns {@code null}.
 */
@Override
protected final MathTransform tryConcatenate(boolean applyOtherFirst, MathTransform other, MathTransformFactory factory)
        throws FactoryException
{
    if (other instanceof LinearTransform) {
        return super.tryConcatenate(applyOtherFirst, other, factory);
    }
    return null;        // No need to compute the inverse if the other transform is not linear.
}
 
Example #10
Source File: WraparoundAdjustment.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Transforms {@link #domainOfValidity} to the same CRS than the Area Of Interest (AOI) or Point Of Interest (POI).
 * This method should be invoked only when the caller detected a wraparound axis. This method transforms the domain
 * the first time it is invoked, and does nothing on all subsequent calls.
 */
private void transformDomainToAOI() throws TransformException {
    if (!isDomainTransformed) {
        isDomainTransformed = true;
        MathTransform domainToGeographic = domainToAOI;
        if (domainToGeographic == null) {
            domainToGeographic = geographicToAOI;
        } else if (geographicToAOI != null) {
            domainToGeographic = MathTransforms.concatenate(domainToGeographic, geographicToAOI.inverse());
        }
        if (domainToGeographic != null && !domainToGeographic.isIdentity()) {
            domainOfValidity = Envelopes.transform(domainToGeographic, domainOfValidity);
        }
    }
}
 
Example #11
Source File: Projection.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
MathTransform computeProjection(final IScope scope) {
	MathTransform crsTransformation = null;
	if (initialCRS == null) { return null; }
	try {
		crsTransformation = CRS.findMathTransform(initialCRS, getTargetCRS(scope), true);
	} catch (final FactoryException e) {
		e.printStackTrace();
		return null;
	}
	return crsTransformation;
}
 
Example #12
Source File: PassThroughTransform.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the inverse transform of this object.
 *
 * @return {@inheritDoc}
 * @throws NoninvertibleTransformException if the {@linkplain #subTransform sub-transform} is not invertible.
 */
@Override
public synchronized MathTransform inverse() throws NoninvertibleTransformException {
    if (inverse == null) {
        inverse = new PassThroughTransform(firstAffectedCoordinate, subTransform.inverse(), numTrailingCoordinates);
        inverse.inverse = this;
    }
    return inverse;
}
 
Example #13
Source File: MTFactory.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Unsupported by the {@literal Proj.4} wrapper.
 */
@Override
public MathTransform createPassThroughTransform(int firstAffectedCoordinate, MathTransform subTransform, int numTrailingCoordinates)
        throws FactoryException
{
    throw new UnsupportedOperationException();
}
 
Example #14
Source File: GeoServiceTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void getCrsTransformCrsTest() throws Exception {
	MathTransform mathTransform = geoService.findMathTransform(CRS.decode(LONLAT), CRS.decode(LAMBERT72));
	Assert.assertEquals("EPSG:4326->EPSG:31300", ((CrsTransform)mathTransform).getId());

	CrsTransform crsTransform = geoService.getCrsTransform(LONLAT, LAMBERT72);
	Assert.assertEquals("EPSG:4326->EPSG:31300", crsTransform.getId());
	Assert.assertTrue(crsTransform.equals(mathTransform));

	CrsTransform crsTransform2 = geoService.getCrsTransform(CRS.decode(LONLAT), CRS.decode(LAMBERT72));
	Assert.assertEquals("EPSG:4326->EPSG:31300", crsTransform2.getId());
	Assert.assertTrue(crsTransform2.equals(mathTransform));
}
 
Example #15
Source File: GeoWaveRasterReader.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public MathTransform getOriginalGridToWorld(
    final String coverageName,
    final PixelInCell pixInCell) {
  // just reuse super class implementation but ensure that we do not use a
  // cached raster2model
  synchronized (this) {
    raster2Model = null;
    return super.getOriginalGridToWorld(coverageName, pixInCell);
  }
}
 
Example #16
Source File: PositionTransformer.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the inverse transform, computed when first needed.
 */
private MathTransform inverse() throws TransformException {
    if (inverse == null) {
        if (!Utilities.equalsIgnoreMetadata(lastCRS, defaultCRS)) {
            setSourceCRS(defaultCRS);
        }
        inverse = (forward != null) ? forward.inverse() : MathTransforms.identity(getDimension());
    }
    return inverse;
}
 
Example #17
Source File: WraparoundAdjustmentTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Convenience method for the tests.
 */
private static Envelope adjustWraparoundAxes(Envelope areaOfInterest, Envelope domainOfValidity, MathTransform validToAOI)
        throws TransformException
{
    WraparoundAdjustment adj = new WraparoundAdjustment(domainOfValidity, validToAOI, MathTransforms.identity(2));
    return adj.shift(areaOfInterest);
}
 
Example #18
Source File: DefaultPassThroughOperation.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the ordered sequence of indices in a source coordinate tuple of the coordinates
 * affected by this pass-through operation.
 *
 * @return zero-based indices of the modified source coordinates.
 *
 * @see PassThroughTransform#getModifiedCoordinates()
 */
@Override
public int[] getModifiedCoordinates() {
    final MathTransform transform = super.getMathTransform();
    if (transform instanceof PassThroughTransform) {
        return ((PassThroughTransform) transform).getModifiedCoordinates();
    } else {
        /*
         * Should not happen with objects created by public methods since the constructor created the transform
         * itself. However may happen with operations parsed from GML. As a fallback, search in the components
         * of CompoundCRS. This is not a universal fallback, but work for the most straightforward cases.
         */
        final CoordinateReferenceSystem sourceCRS = super.getSourceCRS();
        if (sourceCRS instanceof CompoundCRS) {
            int firstAffectedCoordinate = 0;
            final CoordinateReferenceSystem search = operation.getSourceCRS();
            for (final CoordinateReferenceSystem c : ((CompoundCRS) sourceCRS).getComponents()) {
                final int dim = ReferencingUtilities.getDimension(c);
                if (c == search) {
                    final int[] indices = new int[dim];
                    for (int i=0; i<dim; i++) {
                        indices[i] = firstAffectedCoordinate + i;
                    }
                    return indices;
                }
                firstAffectedCoordinate += dim;
            }
        }
        throw new UnsupportedImplementationException(transform.getClass());
    }
}
 
Example #19
Source File: OpenMappingImporter.java    From TomboloDigitalConnector with MIT License 5 votes vote down vote up
public Geometry getShape(String wtk) throws FactoryException, TransformException {
    GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), Subject.SRID);
    WKTReader reader = new WKTReader(geometryFactory);
    MathTransform crsTransform = GeotoolsDataStoreUtils.makeCrsTransform("EPSG:27700");

    try {
        LineString line = (LineString) reader.read(wtk);
        Geometry transformedGeom = JTS.transform(line, crsTransform);
        return transformedGeom;
    } catch (ParseException e) {
        e.printStackTrace();
        log.error("Not a valid geometry");
        return null;
    }
}
 
Example #20
Source File: PassThroughTransform.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs the general {@code PassThroughTransform} object. An optimization is done right in
 * the constructor for the case where the sub-transform is already a {@code PassThroughTransform}.
 * It is caller's responsibility to ensure that the argument values are valid.
 */
private static PassThroughTransform newInstance(final int firstAffectedCoordinate,
                                                final MathTransform subTransform,
                                                final int numTrailingCoordinates)
{
    int dim = subTransform.getSourceDimensions();
    if (subTransform.getTargetDimensions() == dim) {
        dim += firstAffectedCoordinate + numTrailingCoordinates;
        if (dim == 2) {
            return new PassThroughTransform2D(firstAffectedCoordinate, subTransform, numTrailingCoordinates);
        }
    }
    return new PassThroughTransform(firstAffectedCoordinate, subTransform, numTrailingCoordinates);
}
 
Example #21
Source File: PassThroughTransformTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests a pass-through transform built using the given sub-transform.
 *
 * @param  subTransform   the sub-transform to use for building pass-through transform.
 * @param  expectedClass  the expected implementation class of pass-through transforms.
 * @throws TransformException if a transform failed.
 */
private void runTest(final MathTransform subTransform, final Class<? extends MathTransform> expectedClass)
        throws TransformException
{
    random = TestUtilities.createRandomNumberGenerator();
    /*
     * Test many combinations of "first affected coordinate" and "number of trailing coordinates" parameters.
     * For each combination we create a passthrough transform, test it with the 'verifyTransform' method.
     */
    for (int firstAffectedCoordinate=0; firstAffectedCoordinate<=3; firstAffectedCoordinate++) {
        for (int numTrailingCoordinates=0; numTrailingCoordinates<=3; numTrailingCoordinates++) {
            final int numAdditionalOrdinates = firstAffectedCoordinate + numTrailingCoordinates;
            transform = MathTransforms.passThrough(firstAffectedCoordinate, subTransform, numTrailingCoordinates);
            if (numAdditionalOrdinates == 0) {
                assertSame("Failed to recognize that no passthrough was needed.", subTransform, transform);
                continue;
            }
            assertNotSame(subTransform, transform);
            assertTrue   ("Wrong transform class.", expectedClass.isInstance(transform));
            assertEquals ("Wrong number of source dimensions.",
                    subTransform.getSourceDimensions() + numAdditionalOrdinates, transform.getSourceDimensions());
            assertEquals ("Wrong number of target dimensions.",
                    subTransform.getTargetDimensions() + numAdditionalOrdinates, transform.getTargetDimensions());
            verifyTransform(subTransform, firstAffectedCoordinate);
        }
    }
}
 
Example #22
Source File: NwwUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public static Sector envelope2Sector( ReferencedEnvelope env ) throws Exception {
    CoordinateReferenceSystem sourceCRS = env.getCoordinateReferenceSystem();
    CoordinateReferenceSystem targetCRS = GPS_CRS;

    MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);
    Envelope envLL = JTS.transform(env, transform);
    ReferencedEnvelope llEnv = new ReferencedEnvelope(envLL, targetCRS);
    Sector sector = Sector.fromDegrees(llEnv.getMinY(), llEnv.getMaxY(), llEnv.getMinX(), llEnv.getMaxX());
    return sector;
}
 
Example #23
Source File: TestUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static MathTransform transformFromCrs(final CoordinateReferenceSystem crs) {
  MathTransform mathTransform = null;
  if (crs != null) {
    try {
      mathTransform = CRS.findMathTransform(GeometryUtils.getDefaultCRS(), crs, true);
    } catch (final FactoryException e) {
      LOGGER.warn("Unable to create coordinate reference system transform", e);
    }
  }
  return mathTransform;
}
 
Example #24
Source File: AxisOrderReversal.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the transform.
 *
 * @param  factory  ignored (can be null).
 * @param  values   ignored.
 * @return the math transform.
 */
@Override
public synchronized MathTransform createMathTransform(MathTransformFactory factory, ParameterValueGroup values) {
    if (transform == null) {
        final MatrixSIS m = Matrices.createZero(getTargetDimensions() + 1, getSourceDimensions() + 1);
        m.setElement(0, 1, 1);
        m.setElement(1, 0, 1);
        transform = MathTransforms.linear(m);
    }
    return transform;
}
 
Example #25
Source File: ProjectedCoordinate.java    From gtfs-validator with MIT License 5 votes vote down vote up
public ProjectedCoordinate(MathTransform mathTransform,
  Coordinate to, Coordinate refLatLon) {
  this.transform = mathTransform;
  this.x = to.x;
  this.y = to.y;
  this.refLatLon = refLatLon;
}
 
Example #26
Source File: MathTransformParser.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Parses an {@code "INVERSE_MT"} element. This element has the following pattern:
 *
 * {@preformat text
 *     INVERSE_MT[<math transform>]
 * }
 *
 * @param  parent  the parent element.
 * @return the {@code "INVERSE_MT"} element as an {@link MathTransform} object.
 * @throws ParseException if the {@code "INVERSE_MT"} element can not be parsed.
 */
private MathTransform parseInverseMT(final Element parent) throws ParseException {
    final Element element = parent.pullElement(FIRST, WKTKeywords.Inverse_MT);
    if (element == null) {
        return null;
    }
    MathTransform transform = parseMathTransform(element, true);
    try {
        transform = transform.inverse();
    } catch (NoninvertibleTransformException exception) {
        throw element.parseFailed(exception);
    }
    element.close(ignoredElements);
    return transform;
}
 
Example #27
Source File: GeoServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private MathTransform getBaseMathTransform(Crs sourceCrs, Crs targetCrs) throws GeomajasException {
	try {
		MathTransform transform;
		try {
			transform = CRS.findMathTransform(sourceCrs, targetCrs);
		} catch (Exception e) { // NOSONAR GeoTools can throw unexpected exceptions
			transform = CRS.findMathTransform(sourceCrs, targetCrs, true);
		}
		return transform;
	} catch (FactoryException fe) {
		throw new GeomajasException(fe, ExceptionCode.CRS_TRANSFORMATION_NOT_POSSIBLE, sourceCrs.getId(),
				targetCrs.getId());
	}
}
 
Example #28
Source File: Transformer.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Transforms the given points.
 */
final double[][] transform(final double[][] points) {
    final MathTransform         mt       = operation.getMathTransform();
    final GeneralDirectPosition sourcePt = new GeneralDirectPosition(mt.getSourceDimensions());
    final GeneralDirectPosition targetPt = new GeneralDirectPosition(mt.getTargetDimensions());
    final double[][] result = new double[points.length][];
    for (int j=0; j<points.length; j++) {
        final double[] coords = points[j];
        if (coords != null) {                                               // Paranoiac check.
            for (int i=sourcePt.coordinates.length; --i>=0;) {
                sourcePt.coordinates[i] = (i < coords.length) ? coords[i] : 0;
            }
            try {
                result[j] = mt.transform(sourcePt, targetPt).getCoordinate();
            } catch (TransformException exception) {
                /*
                 * The coordinate operation failed for this particular point. But maybe it will
                 * succeed for an other point. Set the values to NaN and continue the loop. Note:
                 * we will report the failure for logging purpose, but only the first one since
                 * all subsequent failures are likely to be the same one.
                 */
                final double[] pad = new double[mt.getTargetDimensions()];
                Arrays.fill(pad, Double.NaN);
                result[j] = pad;
                if (warning == null) {
                    warning = exception;
                }
            }
        }
    }
    return result;
}
 
Example #29
Source File: TestUtils.java    From geowave with Apache License 2.0 4 votes vote down vote up
public static ExpectedResults getExpectedResults(
    final URL[] expectedResultsResources,
    final CoordinateReferenceSystem crs) throws IOException {
  final Map<String, Object> map = new HashMap<>();
  DataStore dataStore = null;
  final Set<Long> hashedCentroids = new HashSet<>();
  int expectedResultCount = 0;
  final MathTransform mathTransform = transformFromCrs(crs);
  final TWKBWriter writer = new TWKBWriter();
  final TWKBReader reader = new TWKBReader();
  for (final URL expectedResultsResource : expectedResultsResources) {
    map.put("url", expectedResultsResource);
    SimpleFeatureIterator featureIterator = null;
    try {
      dataStore = DataStoreFinder.getDataStore(map);
      if (dataStore == null) {
        LOGGER.error("Could not get dataStore instance, getDataStore returned null");
        throw new IOException("Could not get dataStore instance, getDataStore returned null");
      }
      final SimpleFeatureCollection expectedResults =
          dataStore.getFeatureSource(dataStore.getNames().get(0)).getFeatures();

      expectedResultCount += expectedResults.size();
      // unwrap the expected results into a set of features IDs so its
      // easy to check against
      featureIterator = expectedResults.features();
      while (featureIterator.hasNext()) {
        final SimpleFeature feature = featureIterator.next();
        final Geometry geometry = (Geometry) feature.getDefaultGeometry();

        // TODO: Geometry has to be serialized and deserialized here
        // to make the centroid match the one coming out of the
        // database.
        final long centroid =
            hashCentroid(
                reader.read(
                    writer.write(
                        mathTransform != null ? JTS.transform(geometry, mathTransform)
                            : geometry)));
        hashedCentroids.add(centroid);
      }
    } catch (MismatchedDimensionException | TransformException | ParseException e) {
      LOGGER.warn("Unable to transform geometry", e);
      Assert.fail("Unable to transform geometry to CRS: " + crs.toString());
    } finally {
      IOUtils.closeQuietly(featureIterator);
      if (dataStore != null) {
        dataStore.dispose();
      }
    }
  }
  return new ExpectedResults(hashedCentroids, expectedResultCount);
}
 
Example #30
Source File: EllipsoidToCentricTransform.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the inverse of this math transform.
 */
@Override
public MathTransform inverse() {
    return forward;
}