org.opengis.geometry.DirectPosition Java Examples

The following examples show how to use org.opengis.geometry.DirectPosition. 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: DirectPosition1DTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@link DirectPosition2D#equals(Object)} method between different implementations.
 * The purpose of this test is also to run the assertion in the direct position implementations.
 */
@Test
public void testEquals() {
    assertTrue(DirectPosition1D     .class.desiredAssertionStatus());
    assertTrue(GeneralDirectPosition.class.desiredAssertionStatus());

    DirectPosition p1 = new DirectPosition1D     (48.543261561072285);
    DirectPosition p2 = new GeneralDirectPosition(48.543261561072285);
    assertTrue(p1.equals(p2));
    assertTrue(p2.equals(p1));
    assertEquals(p2.hashCode(), p1.hashCode());

    p1.setOrdinate(0, p1.getOrdinate(0) + 1);
    assertFalse(p1.equals(p2));
    assertFalse(p2.equals(p1));
    assertFalse(p2.hashCode() == p1.hashCode());
}
 
Example #2
Source File: ReferencingAssert.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that two envelopes have the same minimum and maximum coordinates.
 * This method ignores the envelope type (i.e. the implementation class) and the CRS.
 *
 * @param expected    the expected envelope.
 * @param actual      the envelope to compare with the expected one.
 * @param tolerances  the tolerance threshold on location along each axis. If this array length is shorter
 *                    than the number of dimensions, then the last tolerance is reused for all remaining axes.
 *                    If this array is empty, then the tolerance threshold is zero.
 *
 * @since 0.7
 */
public static void assertEnvelopeEquals(final Envelope expected, final Envelope actual, final double... tolerances) {
    final int dimension = expected.getDimension();
    assertEquals("dimension", dimension, actual.getDimension());
    final DirectPosition expectedLower = expected.getLowerCorner();
    final DirectPosition expectedUpper = expected.getUpperCorner();
    final DirectPosition actualLower   = actual  .getLowerCorner();
    final DirectPosition actualUpper   = actual  .getUpperCorner();
    double tolerance = 0;
    for (int i=0; i<dimension; i++) {
        if (i < tolerances.length) {
            tolerance = tolerances[i];
        }
        if (abs(expectedLower.getOrdinate(i) - actualLower.getOrdinate(i)) > tolerance ||
            abs(expectedUpper.getOrdinate(i) - actualUpper.getOrdinate(i)) > tolerance)
        {
            fail("Envelopes are not equal in dimension " + i + ":\n"
                    + "expected " + Envelopes.toString(expected) + "\n"
                    + " but got " + Envelopes.toString(actual));
        }
    }
}
 
Example #3
Source File: ArrayEnvelope.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a new envelope with the same data than the specified envelope.
 *
 * @param envelope  the envelope to copy.
 */
public ArrayEnvelope(final Envelope envelope) {
    ensureNonNull("envelope", envelope);
    /*
     * Do not optimize with `if (envelope instanceof ArrayEnvelope)` because subclasses may change the semantic.
     * In particular the SubEnvelope subclass uses only a subrange of this array. If we still want to optimize,
     * we would have to test for specific classes. It is probably not worth at this stage.
     */
    crs = envelope.getCoordinateReferenceSystem();
    final int dimension = envelope.getDimension();
    coordinates = new double[dimension * 2];
    final DirectPosition lowerCorner = envelope.getLowerCorner();
    final DirectPosition upperCorner = envelope.getUpperCorner();
    for (int i=0; i<dimension; i++) {
        coordinates[i]           = lowerCorner.getOrdinate(i);
        coordinates[i+dimension] = upperCorner.getOrdinate(i);
    }
    verifyRanges(crs, coordinates);
}
 
Example #4
Source File: DirectPosition2DTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@link DirectPosition2D#equals(Object)} method between different implementations.
 * The purpose of this test is also to run the assertion in the direct position implementations.
 */
@Test
public void testEquals() {
    assertTrue(DirectPosition2D     .class.desiredAssertionStatus());
    assertTrue(GeneralDirectPosition.class.desiredAssertionStatus());

    DirectPosition p1 = new DirectPosition2D     (48.543261561072285, -123.47009555832284);
    DirectPosition p2 = new GeneralDirectPosition(48.543261561072285, -123.47009555832284);
    assertTrue(p1.equals(p2));
    assertTrue(p2.equals(p1));
    assertEquals(p2.hashCode(), p1.hashCode());

    p1.setOrdinate(0, p1.getOrdinate(0) + 1);
    assertFalse(p1.equals(p2));
    assertFalse(p2.equals(p1));
    assertFalse(p2.hashCode() == p1.hashCode());
}
 
Example #5
Source File: CoordinateFormat.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Formats the given coordinate.
 *
 * @param  position  the coordinate to format.
 * @return the formatted position.
 */
public String format(final DirectPosition position) {
    if (buffer == null) {
        buffer = new StringBuffer();
    }
    buffer.setLength(0);
    try {
        format(position, buffer);
    } catch (IOException e) {
        /*
         * Should never happen when writing into a StringBuffer, unless the user override the
         * format(…) method. We do not rethrow an AssertionError because of this possibility.
         */
        throw new UncheckedIOException(e);
    }
    return buffer.toString();
}
 
Example #6
Source File: ImageGenerator.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
private void expandToIncludeEnvelope( ReferencedEnvelope maxExtent, org.opengis.geometry.Envelope envelope ) {
    ReferencedEnvelope tmpExtent = new ReferencedEnvelope(envelope.getCoordinateReferenceSystem());
    DirectPosition ll = envelope.getLowerCorner();
    double[] coordinate = ll.getCoordinate();
    tmpExtent.expandToInclude(new Coordinate(coordinate[0], coordinate[1]));
    DirectPosition ur = envelope.getUpperCorner();
    coordinate = ur.getCoordinate();
    tmpExtent.expandToInclude(new Coordinate(coordinate[0], coordinate[1]));

    try {
        ReferencedEnvelope transformed = tmpExtent.transform(maxExtent.getCoordinateReferenceSystem(), true);
        maxExtent.expandToInclude(transformed);
    } catch (TransformException | FactoryException e) {
        e.printStackTrace();
    }
}
 
Example #7
Source File: LinearTransformBuilder.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the index where to fetch a target position for the given source position in the flattened array.
 * This is the same work as {@link LinearTransformBuilder#flatIndex(DirectPosition)}, but without throwing
 * exception if the position is invalid. Instead, -1 is returned as a sentinel value for invalid source
 * (including mismatched number of dimensions).
 *
 * <p>The default implementation assumes a grid. This method must be overridden by {@link Ungridded}.</p>
 *
 * @see LinearTransformBuilder#flatIndex(DirectPosition)
 */
int flatIndex(final DirectPosition source) {
    final double[][] targets = LinearTransformBuilder.this.targets;
    if (targets != null) {
        final int[] gridSize = LinearTransformBuilder.this.gridSize;
        int i = gridSize.length;
        if (i == source.getDimension()) {
            int offset = 0;
            while (i != 0) {
                final int size = gridSize[--i];
                final double coordinate = source.getOrdinate(i);
                final int index = (int) coordinate;
                if (index < 0 || index >= size || index != coordinate) {
                    return -1;
                }
                offset = offset * size + index;
            }
            if (!Double.isNaN(targets[0][offset])) return offset;
        }
    }
    return -1;
}
 
Example #8
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public static RegionMap gridGeometry2RegionParamsMap( GridGeometry2D gridGeometry ) {
    RegionMap envelopeParams = new RegionMap();

    Envelope envelope = gridGeometry.getEnvelope2D();
    DirectPosition lowerCorner = envelope.getLowerCorner();
    double[] westSouth = lowerCorner.getCoordinate();
    DirectPosition upperCorner = envelope.getUpperCorner();
    double[] eastNorth = upperCorner.getCoordinate();

    GridEnvelope2D gridRange = gridGeometry.getGridRange2D();
    int height = gridRange.height;
    int width = gridRange.width;

    AffineTransform gridToCRS = (AffineTransform) gridGeometry.getGridToCRS();
    double xRes = XAffineTransform.getScaleX0(gridToCRS);
    double yRes = XAffineTransform.getScaleY0(gridToCRS);

    envelopeParams.put(NORTH, eastNorth[1]);
    envelopeParams.put(SOUTH, westSouth[1]);
    envelopeParams.put(WEST, westSouth[0]);
    envelopeParams.put(EAST, eastNorth[0]);
    envelopeParams.put(XRES, xRes);
    envelopeParams.put(YRES, yRes);
    envelopeParams.put(ROWS, (double) height);
    envelopeParams.put(COLS, (double) width);

    return envelopeParams;
}
 
Example #9
Source File: MilitaryGridReferenceSystemTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Decodes the given reference and returns its direct position.
 */
private static DirectPosition decode(final MilitaryGridReferenceSystem.Coder coder, final String reference)
        throws TransformException
{
    final AbstractLocation loc = coder.decode(reference);
    final Envelope2D envelope = new Envelope2D(loc.getEnvelope());
    final DirectPosition2D pos = new DirectPosition2D(loc.getPosition().getDirectPosition());
    assertTrue(reference, envelope.contains(pos));
    return pos;
}
 
Example #10
Source File: PrintUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public static String getRegionPrint( GridCoverage2D coverage ) {
    org.opengis.geometry.Envelope envelope = coverage.getEnvelope();

    DirectPosition lowerCorner = envelope.getLowerCorner();
    double[] westSouth = lowerCorner.getCoordinate();
    DirectPosition upperCorner = envelope.getUpperCorner();
    double[] eastNorth = upperCorner.getCoordinate();

    GridGeometry2D gridGeometry = coverage.getGridGeometry();
    GridEnvelope2D gridRange = gridGeometry.getGridRange2D();

    String numberSpace = "                ";
    String numberRest = "                  ";

    StringBuilder sb = new StringBuilder();
    sb.append("        +----------------------   ").append(String.format("%17.8f", eastNorth[1]))
            .append("   ----------------------+").append("\n");
    sb.append("        +                         ").append(String.format("%17.8f", gridRange.getMinY()))
            .append("                         +").append("\n");
    sb.append("        +                         ").append(numberSpace).append("                          +").append("\n");
    sb.append("        +                         ").append(numberSpace).append("                          +").append("\n");
    sb.append(String.format("%17.8f", westSouth[0])).append(numberRest).append(numberSpace).append(numberRest)
            .append(String.format("%17.8f", eastNorth[0])).append("\n");
    sb.append(String.format("%17.8f", gridRange.getMinX())).append(numberRest).append(numberSpace).append(numberRest)
            .append(String.format("%17.8f", gridRange.getMaxX())).append("\n");
    sb.append("        +                         ").append(numberSpace).append("                          +").append("\n");
    sb.append("        +                         ").append(numberSpace).append("                          +").append("\n");
    sb.append("        +                         ").append(String.format("%17.8f", gridRange.getMaxY()))
            .append("                         +").append("\n");
    sb.append("        +----------------------   ").append(String.format("%17.8f", westSouth[1]))
            .append("   ----------------------+").append("\n");

    return sb.toString();
}
 
Example #11
Source File: GeohashReferenceSystem.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Encodes the given position into a geohash. The default implementation transforms the given position
 * to the coordinate reference system expected by the enclosing {@link GeohashReferenceSystem}, then
 * delegates to {@link #encode(double, double)}.
 *
 * @param  position  the coordinate to encode.
 * @return geohash encoding of the given position.
 * @throws TransformException if an error occurred while transforming the given coordinate to a geohash reference.
 */
public String encode(DirectPosition position) throws TransformException {
    ArgumentChecks.ensureNonNull("position", position);
    final CoordinateReferenceSystem ps = position.getCoordinateReferenceSystem();
    if (ps != null && !normalizedCRS.equals(ps, ComparisonMode.IGNORE_METADATA)) {
        if (lastOp == null || !Utilities.equalsIgnoreMetadata(lastOp.getSourceCRS(), ps)) try {
            lastOp = CRS.findOperation(ps, normalizedCRS, null);
        } catch (FactoryException e) {
            throw new GazetteerException(e.getLocalizedMessage(), e);
        }
        position = lastOp.getMathTransform().transform(position, null);
    }
    return encode(position.getOrdinate(1), position.getOrdinate(0));
}
 
Example #12
Source File: GeneralEnvelopeTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that the given two-dimensional envelope is equals to the given rectangle.
 * The {@code xLower} and {@code xUpper} arguments are the <var>x</var> coordinate values
 * for the lower and upper corners respectively. The actual {@code xmin} and {@code ymin}
 * values will be inferred from those corners.
 *
 * <p>This method assumes that only the <var>x</var> axis may be a wraparound axis.</p>
 *
 * @param  test    the actual envelope to verify.
 * @param  xLower  the expected first   <var>x</var> coordinate value. May  be greater than {@code xUpper}.
 * @param  xUpper  the expected last    <var>x</var> coordinate value. May  be less    than {@code xLower}.
 * @param  ymin    the expected minimal <var>y</var> coordinate value. Must be less    than {@code ymax}.
 * @param  ymax    the expected maximal <var>y</var> coordinate value. Must be greater than {@code ymax}.
 */
private static void assertEnvelopeEquals(final Envelope test,
        final double xLower, final double ymin, final double xUpper, final double ymax)
{
    final double xmin, xmax;
    if (MathFunctions.isNegative(xUpper - xLower)) {                // Check for anti-meridian spanning.
        xmin = -180;
        xmax = +180;
    } else {
        xmin = xLower;
        xmax = xUpper;
    }
    final DirectPosition lower = test.getLowerCorner();
    final DirectPosition upper = test.getUpperCorner();
    assertEquals("lower", xLower, lower.getOrdinate(0), STRICT);
    assertEquals("upper", xUpper, upper.getOrdinate(0), STRICT);
    assertEquals("xmin",  xmin,   test .getMinimum (0), STRICT);
    assertEquals("xmax",  xmax,   test .getMaximum (0), STRICT);
    assertEquals("ymin",  ymin,   test .getMinimum (1), STRICT);
    assertEquals("ymax",  ymax,   test .getMaximum (1), STRICT);
    assertEquals("ymin",  ymin,   lower.getOrdinate(1), STRICT);
    assertEquals("ymax",  ymax,   upper.getOrdinate(1), STRICT);
    if (test instanceof Envelope2D) {
        final Envelope2D ri = (Envelope2D) test;
        assertEquals("xmin", xmin, ri.getMinX(), STRICT);
        assertEquals("xmax", xmax, ri.getMaxX(), STRICT);
        assertEquals("ymin", ymin, ri.getMinY(), STRICT);
        assertEquals("ymax", ymax, ri.getMaxY(), STRICT);
    }
}
 
Example #13
Source File: EllipsoidToCentricTransform.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Computes the derivative at the given location. We need to override this method because
 * we will inverse 3×2 matrices in a special way, with the knowledge that <var>h</var>
 * can be set to 0.
 */
@Override
public Matrix derivative(final DirectPosition point) throws TransformException {
    ArgumentChecks.ensureNonNull("point", point);
    final double[] coordinate = point.getCoordinate();
    ArgumentChecks.ensureDimensionMatches("point", 3, coordinate);
    return this.transform(coordinate, 0, coordinate, 0, true);
}
 
Example #14
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 #15
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get the parameters of the region covered by the {@link ImageMosaicReader}. 
 * 
 * @param reader the ImageMosaicReader.
 * @return the {@link HashMap map} of parameters. ( {@link #NORTH} and the 
 *          other static vars can be used to retrieve them.
 */
public static RegionMap getRegionParamsFromImageMosaicReader( ImageMosaicReader reader ) throws IOException {
    RegionMap envelopeParams = new RegionMap();

    Envelope envelope = reader.getOriginalEnvelope();

    DirectPosition lowerCorner = envelope.getLowerCorner();
    double[] westSouth = lowerCorner.getCoordinate();
    DirectPosition upperCorner = envelope.getUpperCorner();
    double[] eastNorth = upperCorner.getCoordinate();

    GridEnvelope2D gridRange = (GridEnvelope2D) reader.getOriginalGridRange();
    int height = gridRange.height;
    int width = gridRange.width;
    double[][] resolutionLevels = reader.getResolutionLevels();
    double xRes = resolutionLevels[0][0];
    double yRes = resolutionLevels[0][1];

    envelopeParams.put(NORTH, eastNorth[1]);
    envelopeParams.put(SOUTH, westSouth[1]);
    envelopeParams.put(WEST, westSouth[0]);
    envelopeParams.put(EAST, eastNorth[0]);
    envelopeParams.put(XRES, xRes);
    envelopeParams.put(YRES, yRes);
    envelopeParams.put(ROWS, (double) height);
    envelopeParams.put(COLS, (double) width);

    return envelopeParams;
}
 
Example #16
Source File: LinearTransformBuilder.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the target point for the given source point.
 * This method is fast on gridded data, but requires linear scan on non-gridded data.
 */
@Override
public final DirectPosition get(final Object key) {
    if (key instanceof Position) {
        final int index = flatIndex(((Position) key).getDirectPosition());
        if (index >= 0) return position(targets, index);
    }
    return null;
}
 
Example #17
Source File: ArgumentChecks.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures that the given direct position, if non-null, has the expected number of dimensions.
 * This method does nothing if the given direct position 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  position  the direct position to check for its dimension, or {@code null}.
 * @throws MismatchedDimensionException if the given direct position is non-null and does
 *         not have the expected number of dimensions.
 */
public static void ensureDimensionMatches(final String name, final int expected, final DirectPosition position)
        throws MismatchedDimensionException
{
    if (position != null) {
        final int dimension = position.getDimension();
        if (dimension != expected) {
            throw new MismatchedDimensionException(Errors.format(
                    Errors.Keys.MismatchedDimension_3, name, expected, dimension));
        }
    }
}
 
Example #18
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 #19
Source File: GridExtent.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a slice of this given grid extent computed by a ratio between 0 and 1 inclusive.
 * This is a helper method for {@link GridDerivation#sliceByRatio(double, int...)} implementation.
 *
 * @param  slicePoint        a pre-allocated direct position to be overwritten by this method.
 * @param  sliceRatio        the ratio to apply on all grid dimensions except the ones to keep.
 * @param  dimensionsToKeep  the grid dimension to keep unchanged.
 */
final GridExtent sliceByRatio(final DirectPosition slicePoint, final double sliceRatio, final int[] dimensionsToKeep) {
    for (int i=slicePoint.getDimension(); --i >= 0;) {
        slicePoint.setOrdinate(i, sliceRatio * getSize(i, true) + getLow(i));       // TODO: use Math.fma
    }
    for (int i=0; i<dimensionsToKeep.length; i++) {
        slicePoint.setOrdinate(dimensionsToKeep[i], Double.NaN);
    }
    return slice(slicePoint, null);
}
 
Example #20
Source File: ConcatenatedTransform.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Transforms the specified {@code ptSrc} and stores the result in {@code ptDst}.
 *
 * @throws TransformException if {@link #transform1} or {@link #transform2} failed.
 */
@Override
public DirectPosition transform(final DirectPosition ptSrc, final DirectPosition ptDst)
        throws TransformException
{
    assert isValid();
    /*
     * Note: If we know that the transfer dimension is the same than source
     *       and target dimension, then we don't need to use an intermediate
     *       point. This optimization is done in ConcatenatedTransformDirect.
     */
    return transform2.transform(transform1.transform(ptSrc, null), ptDst);
}
 
Example #21
Source File: CompoundDirectPositions.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Starts a new iteration.
 *
 * @return always {@code this}.
 */
@Override
public Iterator<DirectPosition> iterator() {
    if (hasNext()) {
        throw new UnsupportedOperationException(Errors.format(Errors.Keys.CanIterateOnlyOnce));
    }
    index = -1;
    return this;
}
 
Example #22
Source File: CoordinateFormatTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests parsing from a position different then the beginning of the string.
 *
 * @throws ParseException if the parsing failed.
 */
@Test
public void testParseFromOffset() throws ParseException {
    CoordinateFormat coordinateFormat = new CoordinateFormat(Locale.CANADA, null);
    coordinateFormat.setDefaultCRS(VerticalCRSMock.BAROMETRIC_HEIGHT);
    ParsePosition  charPos  = new ParsePosition(7);
    DirectPosition position = coordinateFormat.parse("[skip] 12", charPos);
    assertEquals("Should have parsed the whole text.", 9, charPos.getIndex());
    assertEquals("DirectPosition.getDimension()", 1, position.getDimension());
    assertArrayEquals(new double[] {12}, position.getCoordinate(), STRICT);
}
 
Example #23
Source File: ProjectiveTransform.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a single coordinate point in a list of ordinal values,
 * and optionally computes the derivative at that location.
 *
 * @return {@inheritDoc}
 */
@Override
public final Matrix transform(final double[] srcPts, final int srcOff,
                              final double[] dstPts, final int dstOff,
                              final boolean derivate)
{
    transform(srcPts, srcOff, dstPts, dstOff, 1);
    return derivate ? derivative((DirectPosition) null) : null;
}
 
Example #24
Source File: CopyTransform.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Transforms a single coordinate in a list of ordinal values, and optionally returns
 * the derivative at that location.
 */
@Override
public Matrix transform(final double[] srcPts, final int srcOff,
                        final double[] dstPts, final int dstOff,
                        final boolean derivate)
{
    transform(srcPts, srcOff, dstPts, dstOff, 1);
    return derivate ? derivative((DirectPosition) null) : null;
}
 
Example #25
Source File: AbstractEnvelope.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Implementation of the public {@link #toString()} and {@link Envelopes#toString(Envelope)}
 * methods for formatting a {@code BOX} element from an envelope.
 *
 * @param  envelope           the envelope to format.
 * @param  isSinglePrecision  {@code true} if every lower and upper corner values can be casted to {@code float}.
 * @return this envelope as a {@code BOX} or {@code BOX3D} (most typical dimensions) element.
 *
 * @see GeneralEnvelope#GeneralEnvelope(CharSequence)
 * @see CoordinateFormat
 * @see org.apache.sis.io.wkt
 */
static String toString(final Envelope envelope, final boolean isSinglePrecision) {
    final int dimension = envelope.getDimension();
    final StringBuilder buffer = new StringBuilder(64).append("BOX");
    if (dimension != 2) {
        buffer.append(dimension).append('D');
    }
    if (dimension == 0) {
        buffer.append("()");
    } else {
        final DirectPosition lowerCorner = envelope.getLowerCorner();
        final DirectPosition upperCorner = envelope.getUpperCorner();
        boolean isUpper = false;
        do {                                                        // Executed exactly twice.
            for (int i=0; i<dimension; i++) {
                buffer.append(i == 0 && !isUpper ? '(' : ' ');
                final double coordinate = (isUpper ? upperCorner : lowerCorner).getOrdinate(i);
                if (isSinglePrecision) {
                    buffer.append((float) coordinate);
                } else {
                    buffer.append(coordinate);
                }
                trimFractionalPart(buffer);
            }
            buffer.append(isUpper ? ')' : ',');
        } while ((isUpper = !isUpper) == true);
    }
    return buffer.toString();
}
 
Example #26
Source File: AbstractMathTransform1D.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the derivative of this transform at a point. The default implementation ensures that
 * {@code point} is one-dimensional, then delegates to {@link #derivative(double)}.
 *
 * @param  point  the coordinate point where to evaluate the derivative, or {@code null}.
 * @return the derivative at the specified point (never {@code null}).
 * @throws MismatchedDimensionException if {@code point} does not have the expected dimension.
 * @throws TransformException if the derivative can not be evaluated at the specified point.
 */
@Override
public Matrix derivative(final DirectPosition point) throws TransformException {
    final double coordinate;
    if (point == null) {
        coordinate = Double.NaN;
    } else {
        ensureDimensionMatches("point", 1, point);
        coordinate = point.getOrdinate(0);
    }
    return new Matrix1(derivative(coordinate));
}
 
Example #27
Source File: IdentityTransform.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Copies the values from {@code ptSrc} to {@code ptDst}.
 * Overrides the super-class method for performance reason.
 */
@Override
public DirectPosition transform(final DirectPosition ptSrc, final DirectPosition ptDst) {
    ArgumentChecks.ensureDimensionMatches("ptSrc", dimension, ptSrc);
    if (ptDst == null) {
        return new GeneralDirectPosition(ptSrc);
    }
    ArgumentChecks.ensureDimensionMatches("ptDst", dimension, ptDst);
    for (int i=0; i<dimension; i++) {
        ptDst.setOrdinate(i, ptSrc.getOrdinate(i));
    }
    return ptDst;
}
 
Example #28
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 #29
Source File: LocationFormat.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Transforms the given position from the given source to the given target CRS.
 * If the source and target CRS are the same, then this method returns the position unchanged.
 */
private static DirectPosition transform(DirectPosition position,
                                        CoordinateReferenceSystem sourceCRS,
                                        CoordinateReferenceSystem targetCRS)
        throws FactoryException, TransformException
{
    if (sourceCRS != targetCRS) {
        position = CRS.findOperation(sourceCRS, targetCRS, null).getMathTransform().transform(position, null);
    }
    return position;
}
 
Example #30
Source File: PassThroughTransform.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the derivative of this transform at a point.
 *
 * @return {@inheritDoc}
 * @throws TransformException if the {@linkplain #subTransform sub-transform} failed.
 */
@Override
public Matrix derivative(final DirectPosition point) throws TransformException {
    final int nSkipped = firstAffectedCoordinate + numTrailingCoordinates;
    final int transDim = subTransform.getSourceDimensions();
    ensureDimensionMatches("point", transDim + nSkipped, point);
    final GeneralDirectPosition subPoint = new GeneralDirectPosition(transDim);
    for (int i=0; i<transDim; i++) {
        subPoint.coordinates[i] = point.getOrdinate(i + firstAffectedCoordinate);
    }
    return expand(MatrixSIS.castOrCopy(subTransform.derivative(subPoint)),
            firstAffectedCoordinate, numTrailingCoordinates, 0);
}