This is an automated email from the ASF dual-hosted git repository. asf-gitbox-commits pushed a commit to branch geoapi-4.0 in repository https://gitbox.apache.org/repos/asf/sis.git
commit 4c261c547bd8bfaab6ce5ba3004090c4a2f08d1c Author: jsorel <[email protected]> AuthorDate: Mon Nov 16 15:35:02 2026 +0100 feat(Geometry): implement Geodesic and Rhumb envelope --- .../org/apache/sis/geometries/curve/Rhumb.java | 21 +- .../internal/shared/DefaultGeodesic.java | 90 +++++++- .../geometries/internal/shared/DefaultRhumb.java | 126 ++++++++++- .../geometries/internal/shared/GeographicAxes.java | 236 +++++++++++++++++++++ .../internal/shared/HorizontalBounds.java | 166 +++++++++++++++ .../apache/sis/geometries/curve/GeodesicTest.java | 117 +++++++++- .../org/apache/sis/geometries/curve/RhumbTest.java | 214 ++++++++++++++++++- 7 files changed, 957 insertions(+), 13 deletions(-) diff --git a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/curve/Rhumb.java b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/curve/Rhumb.java index 3d1618f491..ee96ae76df 100644 --- a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/curve/Rhumb.java +++ b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/curve/Rhumb.java @@ -82,16 +82,25 @@ public sealed interface Rhumb extends Curve } /** - * Constant azimuth followed by this curve. + * Constant azimuth followed by the given segment of this curve. * - * <p>Note: this attribute appears in the ISO 19107 UML (figure 23) but not in its - * {@code Rhumb} clause.</p> + * <p>Constraints:</p> + * <ul> + * <li>Segment <var>i</var> goes from data point <var>i</var> to data point <var>i</var> + 1, + * so the index ranges from 0 inclusive to {@link #getNumPoints()} − 1 exclusive.</li> + * </ul> * - * @return constant bearing of this curve. + * <p>Difference with ISO 19107: the UML (figure 23) declares a single derived {@code bearing} + * attribute, which does not appear in the {@code Rhumb} clause. Since each rhumb segment has its + * own constant azimuth, the bearing is given per segment.</p> * - * @see ISO 19107:2019 - 7.5.1 + * @param segment index of the segment. + * @return constant bearing of the segment, or {@code null} if the segment has no length. + * @throws IndexOutOfBoundsException if the index is outside the range of segments. + * + * @see ISO 19107:2019 - 7.5.1, 7.5.2 */ - Bearing getBearing(); + Bearing getBearing(int segment); /** * The number of Points in this Rhumb. diff --git a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/DefaultGeodesic.java b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/DefaultGeodesic.java index 08924b1795..89874bb47d 100644 --- a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/DefaultGeodesic.java +++ b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/DefaultGeodesic.java @@ -19,9 +19,12 @@ package org.apache.sis.geometries.internal.shared; import org.opengis.geometry.Envelope; import org.apache.sis.geometries.DataPoints; import org.apache.sis.geometries.curve.Geodesic; +import org.apache.sis.maths.Vector; +import org.apache.sis.referencing.GeodeticCalculator; /** + * Default implementation of {@link Geodesic}, storing its data points. * * @author Johann Sorel (Geomatys) */ @@ -43,9 +46,94 @@ public non-sealed class DefaultGeodesic extends AbstractGeometry implements Geod return points; } + /** + * Returns the envelope of the geodesic segments. + * <p> + * Longitude changes monotonically along a geodesic segment, but latitude may reach an extreme between + * the end points, at the vertex of the geodesic. That extreme is computed with Clairaut's relation + * (sin α cos β is constant, with β the reduced latitude) and included in the envelope. + * <ul> + * <li>In reference systems without ellipsoidal axes, segments are straight and the envelope is the one + * of the data points.</li> + * <li>Geodesics are computed on the ellipsoid of the geographic component. Other ellipsoidal or spherical + * coordinate systems, such as rotated poles, are not supported.</li> + * <li>A segment passing over a pole crosses all longitudes.</li> + * <li>Data points on a pole take the longitude of the adjacent segment.</li> + * <li>The longitude range crosses the anti-meridian (lower > upper) when the geodesic does.</li> + * <li>Other dimensions, such as heights, use the range of the data points.</li> + * </ul> + * + * @return envelope of the geodesic, or {@code null} if it has no data point. + * @throws UnsupportedOperationException if the reference system is not supported. + * @see ISO 19107:2019 - 7.3.2 + */ @Override public Envelope getEnvelope() { - throw new UnsupportedOperationException("Not supported yet."); + if (points.isEmpty()) { + return null; + } + final GeographicAxes axes = GeographicAxes.of(points.getCoordinateReferenceSystem(), Geodesic.TYPE); + if (axes == null) { + return points.getEnvelope(); + } + final GeodeticCalculator calculator = GeodeticCalculator.create(axes.geographic()); + final double axisRatio = axes.axisRatio(); + final HorizontalBounds bounds = axes.start(points); + double latitude = axes.latitude(points.getPosition(0)); + for (int i = 1, n = points.size(); i < n; i++) { + final Vector<?> position = points.getPosition(i); + final double nextLatitude = axes.latitude(position); + addSegment(calculator, axisRatio, bounds, latitude, nextLatitude, axes.longitude(position)); + latitude = nextLatitude; + } + return axes.toEnvelope(points.getEnvelope(), bounds); + } + + /** + * Adds to the bounds the geodesic segment from the current point to the given one. + * + * @param calculator calculator on the ellipsoid of the geodesic. + * @param axisRatio ratio of the semi-minor axis to the semi-major axis of the ellipsoid. + * @param bounds bounds of the previous segments, ending at the current point. + * @param latitude latitude of the current point, in degrees. + * @param endLatitude latitude of the segment end point, in degrees. + * @param endLongitude longitude of the segment end point, in degrees. + */ + private static void addSegment(final GeodeticCalculator calculator, final double axisRatio, + final HorizontalBounds bounds, final double latitude, final double endLatitude, final double endLongitude) + { + if (HorizontalBounds.isPole(endLatitude)) { + bounds.moveTo(0, endLatitude); + return; + } + double change = bounds.shorterChangeTo(endLongitude); + if (HorizontalBounds.isPole(latitude)) { + // Meridian from the pole, which belongs to all meridians. + bounds.moveTo(change, endLatitude); + return; + } + calculator.setStartGeographicPoint(latitude, bounds.longitude()); + calculator.setEndGeographicPoint(endLatitude, endLongitude); + final double startAzimuth = Math.toRadians(calculator.getStartingAzimuth()); + final double endAzimuth = Math.toRadians(calculator.getEndingAzimuth()); + final double sinStart = Math.sin(startAzimuth); + final double cosStart = Math.cos(startAzimuth); + if (cosStart * Math.cos(endAzimuth) < 0) { + // Latitude increases then decreases, or the opposite: the segment passes the vertex. + final double reducedLatitude = Math.atan(axisRatio * Math.tan(Math.toRadians(latitude))); + final double vertexReduced = Math.acos(Math.min(1, Math.abs(sinStart * Math.cos(reducedLatitude)))); + final double vertexLatitude = Math.toDegrees(Math.atan(Math.tan(vertexReduced) / axisRatio)); + bounds.addLatitude(cosStart > 0 ? vertexLatitude : -vertexLatitude); + if (HorizontalBounds.isPole(vertexLatitude)) { + bounds.coverAllLongitudes(); + } + } + if (sinStart > 0 && change < 0) { + change += 360; + } else if (sinStart < 0 && change > 0) { + change -= 360; + } + bounds.moveTo(change, endLatitude); } } diff --git a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/DefaultRhumb.java b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/DefaultRhumb.java index 831df9e0c4..27155f6264 100644 --- a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/DefaultRhumb.java +++ b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/DefaultRhumb.java @@ -16,13 +16,25 @@ */ package org.apache.sis.geometries.internal.shared; +import java.util.Objects; import org.opengis.geometry.Envelope; +import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.apache.sis.geometries.DataPoints; import org.apache.sis.geometries.cs.Bearing; +import org.apache.sis.geometries.cs.FixedDirection; +import org.apache.sis.geometries.cs.Rotation; import org.apache.sis.geometries.curve.Rhumb; +import org.apache.sis.maths.DataType; +import org.apache.sis.maths.Sample; +import org.apache.sis.maths.SampleSystem; +import org.apache.sis.maths.Vector; +import org.apache.sis.measure.Quantities; +import org.apache.sis.measure.Units; +import org.apache.sis.referencing.GeodeticCalculator; /** + * Default implementation of {@link Rhumb}, storing its data points. * * @author Johann Sorel (Geomatys) */ @@ -44,14 +56,122 @@ public non-sealed class DefaultRhumb extends AbstractGeometry implements Rhumb { return points; } + /** + * Returns the envelope of the rhumb segments. + * <p> + * Latitude and longitude change monotonically along a rhumb segment, so the envelope of a segment is the one + * of its end points, with the longitude range going the shorter way around the globe. + * <ul> + * <li>In reference systems without ellipsoidal axes, segments are straight and the envelope is the one + * of the data points.</li> + * <li>Other ellipsoidal or spherical coordinate systems than geographic ones, such as rotated poles, + * are not supported.</li> + * <li>A segment whose end points are 180° of longitude apart goes east.</li> + * <li>Data points on a pole take the longitude of the adjacent segment.</li> + * <li>The longitude range crosses the anti-meridian (lower > upper) when the rhumb does.</li> + * <li>Other dimensions, such as heights, use the range of the data points.</li> + * </ul> + * + * @return envelope of the rhumb, or {@code null} if it has no data point. + * @throws UnsupportedOperationException if the reference system is not supported. + * @see ISO 19107:2019 - 7.5.2 + */ @Override public Envelope getEnvelope() { - throw new UnsupportedOperationException("Not supported yet."); + if (points.isEmpty()) { + return null; + } + final GeographicAxes axes = GeographicAxes.of(points.getCoordinateReferenceSystem(), Rhumb.TYPE); + if (axes == null) { + return points.getEnvelope(); + } + final HorizontalBounds bounds = axes.start(points); + for (int i = 1, n = points.size(); i < n; i++) { + final Vector<?> position = points.getPosition(i); + final double latitude = axes.latitude(position); + if (HorizontalBounds.isPole(latitude)) { + bounds.moveTo(0, latitude); + } else { + bounds.moveTo(bounds.shorterChangeTo(axes.longitude(position)), latitude); + } + } + return axes.toEnvelope(points.getEnvelope(), bounds); } + /** + * Returns the constant azimuth followed by the given rhumb segment. + * <p> + * The azimuth is measured clockwise from true north, on the ellipsoid of the geographic component. + * <ul> + * <li>In reference systems without ellipsoidal axes, segments are straight. The bearing is their direction, + * measured clockwise from grid north.</li> + * <li>Other ellipsoidal or spherical coordinate systems than geographic ones, such as rotated poles, + * are not supported.</li> + * <li>A segment whose end points are 180° of longitude apart goes east.</li> + * <li>A segment from or to a pole follows a meridian.</li> + * <li>On the ellipsoid, other dimensions such as heights are ignored.</li> + * </ul> + * + * @param segment index of the segment, which goes from data point {@code segment} to the next one. + * @return bearing of the segment, or {@code null} if the segment has no length. + * @throws IndexOutOfBoundsException if the index is negative or not less than the number of segments. + * @throws UnsupportedOperationException if the reference system is not supported. + * @see ISO 19107:2019 - 7.5.2 + */ @Override - public Bearing getBearing() { - throw new UnsupportedOperationException("Not supported yet."); + public Bearing getBearing(final int segment) { + Objects.checkIndex(segment, points.size() - 1); + final Vector<?> start = points.getPosition(segment); + final Vector<?> end = points.getPosition(segment + 1); + final GeographicAxes axes = GeographicAxes.of(points.getCoordinateReferenceSystem(), Rhumb.TYPE); + return (axes != null) ? azimuthOnEllipsoid(axes, start, end) : straightDirection(start, end); + } + + /** + * Returns the azimuth of the rhumb line between the given points, going the shorter way around the globe. + * + * @return the bearing, or {@code null} if both points are the same. + */ + private static Bearing azimuthOnEllipsoid(final GeographicAxes axes, final Vector<?> start, final Vector<?> end) { + final double latitude = axes.latitude(start); + final double endLatitude = axes.latitude(end); + final boolean fromPole = HorizontalBounds.isPole(latitude); + final boolean toPole = HorizontalBounds.isPole(endLatitude); + final double azimuth; + if (fromPole || toPole) { + if (fromPole && toPole && (latitude > 0) == (endLatitude > 0)) { + return null; + } + azimuth = (endLatitude > latitude) ? 0 : 180; + } else { + final double longitude = axes.longitude(start); + final double endLongitude = axes.longitude(end); + final double change = HorizontalBounds.shorterChange(longitude, endLongitude); + if (change == 0 && endLatitude == latitude) { + return null; + } + final GeodeticCalculator calculator = GeodeticCalculator.create(axes.geographic()); + calculator.setStartGeographicPoint(latitude, longitude); + calculator.setEndGeographicPoint(endLatitude, endLongitude); + // The calculator may go west for a 180° change, so the side is taken from the change. + azimuth = Math.copySign(Math.abs(calculator.getConstantAzimuth()), change); + } + return Bearing.ofAzimuth(Quantities.create(azimuth, Units.DEGREE)); + } + + /** + * Returns the direction of the straight segment between the given points. + * + * @return the bearing, or {@code null} if both points are the same. + */ + private Bearing straightDirection(final Vector<?> start, final Vector<?> end) { + final Vector<?> step = end.copy(DataType.DOUBLE).subtract(start); + if (step.length() == 0) { + return null; + } + final CoordinateReferenceSystem crs = points.getCoordinateReferenceSystem(); + final SampleSystem system = (crs != null) ? SampleSystem.of(crs) : SampleSystem.ofSize(step.getDimension()); + return Bearing.ofDirection(new Sample(system, step), FixedDirection.GRID_NORTH, Rotation.CLOCKWISE); } } diff --git a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/GeographicAxes.java b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/GeographicAxes.java new file mode 100644 index 0000000000..af88e13ff5 --- /dev/null +++ b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/GeographicAxes.java @@ -0,0 +1,236 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.sis.geometries.internal.shared; + +import javax.measure.UnitConverter; +import javax.measure.quantity.Angle; +import org.opengis.geometry.Envelope; +import org.opengis.referencing.crs.CoordinateReferenceSystem; +import org.opengis.referencing.crs.GeographicCRS; +import org.opengis.referencing.crs.SingleCRS; +import org.opengis.referencing.cs.AxisDirection; +import org.opengis.referencing.cs.CoordinateSystem; +import org.opengis.referencing.cs.CoordinateSystemAxis; +import org.opengis.referencing.cs.EllipsoidalCS; +import org.opengis.referencing.cs.RangeMeaning; +import org.opengis.referencing.cs.SphericalCS; +import org.opengis.referencing.datum.Ellipsoid; +import org.apache.sis.geometry.GeneralEnvelope; +import org.apache.sis.geometries.DataPoints; +import org.apache.sis.maths.Vector; +import org.apache.sis.measure.Units; +import org.apache.sis.referencing.CRS; +import org.apache.sis.referencing.datum.DatumOrEnsemble; + + +/** + * Longitude and latitude axes of a reference system, with conversions between their values and degrees. + * <p> + * Values in degrees are positive east and north, whatever the axis directions and units. + * <ul> + * <li>Only the axes of a geographic component are supported. Other ellipsoidal or spherical + * coordinate systems, such as rotated poles, are rejected.</li> + * </ul> + * + * @author Johann Sorel (Geomatys) + */ +final class GeographicAxes { + + /** + * Number of degrees in a full turn. + */ + private static final double TURN = 360; + + /** + * The geographic component of the reference system. + */ + private final GeographicCRS geographic; + + private final int longitudeDimension; + private final int latitudeDimension; + private final CoordinateSystemAxis longitudeAxis; + private final UnitConverter longitudeToDegrees; + private final UnitConverter latitudeToDegrees; + private final UnitConverter degreesToLongitude; + private final UnitConverter degreesToLatitude; + + /** + * Whether the longitude axis is oriented west. + */ + private final boolean westward; + + /** + * Whether the latitude axis is oriented south. + */ + private final boolean southward; + + /** + * Locates the axes of the given geographic component. + * + * @param geographic the geographic component. + * @param offset index of the first dimension of the component in the full reference system. + */ + private GeographicAxes(final GeographicCRS geographic, final int offset) { + this.geographic = geographic; + final CoordinateSystem cs = geographic.getCoordinateSystem(); + int longitude = -1; + int latitude = -1; + for (int i = 0; i < cs.getDimension(); i++) { + final AxisDirection direction = cs.getAxis(i).getDirection(); + if (direction == AxisDirection.EAST || direction == AxisDirection.WEST) { + longitude = i; + } else if (direction == AxisDirection.NORTH || direction == AxisDirection.SOUTH) { + latitude = i; + } + } + if (longitude < 0 || latitude < 0) { + throw new UnsupportedOperationException("No longitude and latitude axes in " + geographic.getName() + '.'); + } + longitudeAxis = cs.getAxis(longitude); + final CoordinateSystemAxis latitudeAxis = cs.getAxis(latitude); + longitudeDimension = offset + longitude; + latitudeDimension = offset + latitude; + westward = longitudeAxis.getDirection() == AxisDirection.WEST; + southward = latitudeAxis.getDirection() == AxisDirection.SOUTH; + longitudeToDegrees = longitudeAxis.getUnit().asType(Angle.class).getConverterTo(Units.DEGREE); + latitudeToDegrees = latitudeAxis .getUnit().asType(Angle.class).getConverterTo(Units.DEGREE); + degreesToLongitude = longitudeToDegrees.inverse(); + degreesToLatitude = latitudeToDegrees.inverse(); + } + + /** + * Returns the geographic axes of the given reference system. + * + * @param crs the reference system, or {@code null}. + * @param curveType name of the curve type, for the error message. + * @return the axes, or {@code null} if the reference system has no ellipsoidal or spherical axes. + * @throws UnsupportedOperationException if the ellipsoidal or spherical axes are not those of a geographic component. + */ + static GeographicAxes of(final CoordinateReferenceSystem crs, final String curveType) { + if (crs == null) { + return null; + } + int offset = 0; + for (final SingleCRS component : CRS.getSingleComponents(crs)) { + final CoordinateSystem cs = component.getCoordinateSystem(); + if (cs instanceof EllipsoidalCS || cs instanceof SphericalCS) { + if (component instanceof GeographicCRS geographic && cs instanceof EllipsoidalCS) { + return new GeographicAxes(geographic, offset); + } + throw new UnsupportedOperationException(curveType + " curves in " + component.getName() + + " are not supported yet."); + } + offset += cs.getDimension(); + } + return null; + } + + /** + * Returns the geographic component of the reference system. + */ + GeographicCRS geographic() { + return geographic; + } + + /** + * Returns the ratio of the semi-minor axis to the semi-major axis of the ellipsoid, which is 1 − flattening. + */ + double axisRatio() { + final Ellipsoid ellipsoid = DatumOrEnsemble.getEllipsoid(geographic).orElseThrow( + () -> new UnsupportedOperationException("No ellipsoid in " + geographic.getName() + '.')); + return ellipsoid.getSemiMinorAxis() / ellipsoid.getSemiMajorAxis(); + } + + /** + * Returns the longitude of the given position, in degrees east. + */ + double longitude(final Vector<?> position) { + final double value = longitudeToDegrees.convert(position.get(longitudeDimension)); + return westward ? -value : value; + } + + /** + * Returns the latitude of the given position, in degrees north. + */ + double latitude(final Vector<?> position) { + final double value = latitudeToDegrees.convert(position.get(latitudeDimension)); + return southward ? -value : value; + } + + /** + * Starts the bounds of a curve at its first data point. + * A first point on a pole takes the longitude of the first point outside the poles. + * + * @param points data points of the curve, not empty. + * @return bounds containing the first point. + */ + HorizontalBounds start(final DataPoints points) { + final double latitude = latitude(points.getPosition(0)); + double longitude = longitude(points.getPosition(0)); + for (int i = 0, n = points.size(); i < n; i++) { + final Vector<?> position = points.getPosition(i); + if (!HorizontalBounds.isPole(latitude(position))) { + longitude = longitude(position); + break; + } + } + return new HorizontalBounds(longitude, latitude); + } + + /** + * Returns the envelope of data points with the longitude and latitude ranges replaced by the given bounds. + * <p> + * The longitude range is fitted in the range of the longitude axis. It crosses the anti-meridian + * (lower > upper) when the bounds do and the axis wraps around. Otherwise it covers the whole axis. + * + * @param pointsEnvelope envelope of the data points, which gives the ranges of the other dimensions. + * @param bounds longitude and latitude ranges swept by the curve. + * @return envelope of the curve. + */ + GeneralEnvelope toEnvelope(final Envelope pointsEnvelope, final HorizontalBounds bounds) { + final GeneralEnvelope envelope = new GeneralEnvelope(pointsEnvelope); + final double south = degreesToLatitude.convert(southward ? -bounds.north() : bounds.south()); + final double north = degreesToLatitude.convert(southward ? -bounds.south() : bounds.north()); + envelope.setRange(latitudeDimension, Math.min(south, north), Math.max(south, north)); + + final double turn = Math.abs(degreesToLongitude.convert(TURN) - degreesToLongitude.convert(0)); + double lower = degreesToLongitude.convert(westward ? -bounds.east() : bounds.west()); + double upper = degreesToLongitude.convert(westward ? -bounds.west() : bounds.east()); + final double axisMinimum = longitudeAxis.getMinimumValue(); + final double axisMaximum = longitudeAxis.getMaximumValue(); + final boolean wraps = longitudeAxis.getRangeMeaning() == RangeMeaning.WRAPAROUND + && Double.isFinite(axisMinimum) && Double.isFinite(axisMaximum); + if (bounds.spansAllLongitudes()) { + if (wraps) { + lower = axisMinimum; + upper = axisMaximum; + } + } else if (wraps) { + double span = upper - lower; + if (span < 0) span += turn; + lower -= turn * Math.floor((lower - axisMinimum) / turn); + upper = lower + span; + if (upper > axisMinimum + turn) upper -= turn; + } + if (lower > upper && !wraps) { + lower = Math.min(degreesToLongitude.convert(-TURN / 2), degreesToLongitude.convert(TURN / 2)); + upper = Math.max(degreesToLongitude.convert(-TURN / 2), degreesToLongitude.convert(TURN / 2)); + } + envelope.setRange(longitudeDimension, lower, upper); + return envelope; + } +} diff --git a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/HorizontalBounds.java b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/HorizontalBounds.java new file mode 100644 index 0000000000..e6acd54c91 --- /dev/null +++ b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/HorizontalBounds.java @@ -0,0 +1,166 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.sis.geometries.internal.shared; + + +/** + * Longitude and latitude ranges swept by a curve on an ellipsoid, accumulated segment by segment. + * <p> + * Longitudes are tracked without wrapping: each segment adds its signed longitude change to the current + * longitude. Since the curve is continuous, the swept longitudes are the range between the lowest and the + * highest tracked values, which may cross the anti-meridian once normalized. + * <ul> + * <li>All values are in degrees, longitudes positive east and latitudes positive north.</li> + * <li>A segment sweeping longitudes in both directions, as a geodesic over a pole, must declare + * {@linkplain #coverAllLongitudes() all longitudes}.</li> + * </ul> + * + * @author Johann Sorel (Geomatys) + */ +final class HorizontalBounds { + + /** + * Tolerance in degrees for considering a latitude on a pole. + */ + private static final double POLE_TOLERANCE = 1e-10; + + /** + * Current longitude, without wrapping. + */ + private double longitude; + + private double minLongitude; + private double maxLongitude; + private double south; + private double north; + private boolean allLongitudes; + + /** + * Starts the bounds at the first point of a curve. + * + * @param longitude longitude of the first point. + * @param latitude latitude of the first point. + */ + HorizontalBounds(final double longitude, final double latitude) { + this.longitude = longitude; + minLongitude = longitude; + maxLongitude = longitude; + south = latitude; + north = latitude; + } + + /** + * Returns the longitude of the current point, without wrapping. + */ + double longitude() { + return longitude; + } + + /** + * Returns the signed longitude change from the current point to the given longitude, going the shorter way. + * When both ways have the same length, the change is eastward (+180°). + */ + double shorterChangeTo(final double target) { + return shorterChange(longitude, target); + } + + /** + * Returns the signed longitude change between the given longitudes, going the shorter way. + * When both ways have the same length, the change is eastward (+180°). + */ + static double shorterChange(final double source, final double target) { + final double change = Math.IEEEremainder(target - source, 360); + return (change == -180) ? 180 : change; + } + + /** + * Adds a latitude reached between two points, such as the vertex of a geodesic. + */ + void addLatitude(final double latitude) { + south = Math.min(south, latitude); + north = Math.max(north, latitude); + } + + /** + * Moves to the next point of the curve. + * + * @param longitudeChange signed longitude change from the current point, in the direction of the curve. + * @param latitude latitude of the next point. + */ + void moveTo(final double longitudeChange, final double latitude) { + longitude += longitudeChange; + minLongitude = Math.min(minLongitude, longitude); + maxLongitude = Math.max(maxLongitude, longitude); + addLatitude(latitude); + } + + /** + * Declares that the curve crosses all meridians. + */ + void coverAllLongitudes() { + allLongitudes = true; + } + + /** + * Returns whether the curve crosses all meridians. + */ + boolean spansAllLongitudes() { + return allLongitudes || maxLongitude - minLongitude >= 360; + } + + /** + * Returns the west bound, normalized to [−180 … 180)°. It is −180° when all longitudes are crossed. + */ + double west() { + return spansAllLongitudes() ? -180 : normalize(minLongitude); + } + + /** + * Returns the east bound, normalized to (−180 … 180]°. It is 180° when all longitudes are crossed, + * and it is less than the {@linkplain #west() west bound} when the range crosses the anti-meridian. + */ + double east() { + if (spansAllLongitudes()) { + return 180; + } + final double east = west() + (maxLongitude - minLongitude); + return (east > 180) ? east - 360 : east; + } + + double south() { + return south; + } + + double north() { + return north; + } + + /** + * Returns whether the given latitude is on a pole, where longitudes are undefined. + */ + static boolean isPole(final double latitude) { + return Math.abs(latitude) >= 90 - POLE_TOLERANCE; + } + + /** + * Normalizes a longitude to the [−180 … 180)° range. + */ + private static double normalize(final double value) { + final double result = value - 360 * Math.floor((value + 180) / 360); + return (result >= 180) ? result - 360 : result; + } +} diff --git a/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/curve/GeodesicTest.java b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/curve/GeodesicTest.java index 157c8ae6d4..8d6f0b543e 100644 --- a/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/curve/GeodesicTest.java +++ b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/curve/GeodesicTest.java @@ -16,10 +16,16 @@ */ package org.apache.sis.geometries.curve; +import org.opengis.geometry.Envelope; +import org.opengis.referencing.crs.CoordinateReferenceSystem; +import org.apache.sis.geometries.Geometries; import org.apache.sis.geometries.GeometryFactory; +import org.apache.sis.referencing.CommonCRS; +import org.apache.sis.referencing.GeodeticCalculator; // Test dependencies import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.apache.sis.geometries.GeometryTest; @@ -31,6 +37,12 @@ import org.apache.sis.geometries.GeometryTest; * @author Johann Sorel (Geomatys) */ public class GeodesicTest extends GeometryTest { + + /** + * Geographic reference system on a sphere, with (longitude, latitude) axes in degrees. + */ + private static final CoordinateReferenceSystem SPHERE = CommonCRS.SPHERE.normalizedGeographic(); + @Test @Disabled("Not implemented yet.") public void testGetGeometryType() { @@ -268,9 +280,112 @@ public class GeodesicTest extends GeometryTest { public void testGetGeometryType2() { } + /** + * Tests the envelope in a Cartesian system and on a sphere, where the vertex latitude is known. + */ @Test - @Disabled("Not implemented yet.") public void testGetEnvelope() { + Envelope envelope = GeometryFactory.DEFAULT.createGeodesic( + GeometryFactory.DEFAULT.createDataPoints(Geometries.getUndefinedCRS(2), 0,0, 10,10)).getEnvelope(); + assertRange(envelope, 0, 0, 10); + assertRange(envelope, 1, 0, 10); + + envelope = geodesic(SPHERE, 0,45, 90,45).getEnvelope(); + assertRange(envelope, 0, 0, 90); + assertRange(envelope, 1, 45, Math.toDegrees(Math.atan(Math.sqrt(2)))); + + envelope = geodesic(SPHERE, 0,-45, 90,-45).getEnvelope(); + assertRange(envelope, 1, -Math.toDegrees(Math.atan(Math.sqrt(2))), -45); + } + + /** + * Tests that the envelope on the WGS84 ellipsoid contains points sampled along the geodesic. + */ + @Test + public void testGetEnvelopeOnEllipsoid() { + final Envelope envelope = geodesic(CRS_2D, 0,45, 90,45).getEnvelope(); + assertRange(envelope, 0, 0, 90); + assertEquals(45, envelope.getMinimum(1), TOLERANCE); + assertEquals(sampledMaximumLatitude(45, 0, 45, 90), envelope.getMaximum(1), 1E-4); + assertTrue(envelope.getMaximum(1) >= sampledMaximumLatitude(45, 0, 45, 90)); + } + + /** + * Tests a geodesic crossing the anti-meridian. + */ + @Test + public void testGetEnvelopeAcrossAntimeridian() { + final Envelope envelope = geodesic(CRS_2D, 170,10, -170,10).getEnvelope(); + assertRange(envelope, 0, 170, -170); + assertEquals(10, envelope.getMinimum(1), TOLERANCE); + assertTrue(envelope.getMaximum(1) > 10); + } + + /** + * Tests a geodesic passing over the north pole, which crosses all longitudes. + */ + @Test + public void testGetEnvelopeOverPole() { + final Envelope envelope = geodesic(SPHERE, 0,80, 180,80).getEnvelope(); + assertRange(envelope, 0, -180, 180); + assertRange(envelope, 1, 80, 90); + } + + /** + * Tests a geodesic ending on a pole, where the longitude is undefined. + */ + @Test + public void testGetEnvelopeToPole() { + final Envelope envelope = geodesic(CRS_2D, 30,80, 0,90).getEnvelope(); + assertRange(envelope, 0, 30, 30); + assertRange(envelope, 1, 80, 90); + } + + /** + * Tests a reference system with (latitude, longitude, height) axes. + */ + @Test + public void testGetEnvelopeAxisOrder() { + final Envelope envelope = GeometryFactory.DEFAULT.createGeodesic( + GeometryFactory.DEFAULT.createDataPoints(CRS_3D, 45,0,100, 45,90,200)).getEnvelope(); + assertEquals(45, envelope.getMinimum(0), TOLERANCE); + assertEquals(sampledMaximumLatitude(45, 0, 45, 90), envelope.getMaximum(0), 1E-4); + assertRange(envelope, 1, 0, 90); + assertRange(envelope, 2, 100, 200); + } + + private static Geodesic geodesic(final CoordinateReferenceSystem crs, final double... coordinates) { + return GeometryFactory.DEFAULT.createGeodesic(GeometryFactory.DEFAULT.createDataPoints(crs, coordinates)); + } + + /** + * Returns the highest latitude of points sampled along the geodesic between two points of WGS84. + */ + private static double sampledMaximumLatitude(final double latitude1, final double longitude1, + final double latitude2, final double longitude2) + { + final GeodeticCalculator calculator = GeodeticCalculator.create(CRS_2D); + calculator.setStartGeographicPoint(latitude1, longitude1); + calculator.setEndGeographicPoint(latitude2, longitude2); + final double azimuth = calculator.getStartingAzimuth(); + final double distance = calculator.getGeodesicDistance(); + double maximum = Double.NEGATIVE_INFINITY; + for (int i = 0; i <= 2000; i++) { + calculator.setStartGeographicPoint(latitude1, longitude1); + calculator.setStartingAzimuth(azimuth); + calculator.setGeodesicDistance(distance * i / 2000); + maximum = Math.max(maximum, calculator.getEndPoint().getCoordinate(1)); + } + return maximum; + } + + /** + * Asserts the raw bounds of the envelope in one dimension. The lower bound is greater than the upper one + * when the range crosses the anti-meridian. + */ + private static void assertRange(final Envelope envelope, final int dimension, final double lower, final double upper) { + assertEquals(lower, envelope.getLowerCorner().getCoordinate(dimension), TOLERANCE); + assertEquals(upper, envelope.getUpperCorner().getCoordinate(dimension), TOLERANCE); } @Test diff --git a/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/curve/RhumbTest.java b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/curve/RhumbTest.java index 8f739f4558..0481f33b85 100644 --- a/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/curve/RhumbTest.java +++ b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/curve/RhumbTest.java @@ -16,10 +16,23 @@ */ package org.apache.sis.geometries.curve; +import org.opengis.geometry.Envelope; +import org.opengis.referencing.crs.CoordinateReferenceSystem; +import org.apache.sis.geometries.Geometries; import org.apache.sis.geometries.GeometryFactory; +import org.apache.sis.geometries.cs.Bearing; +import org.apache.sis.geometries.cs.FixedDirection; +import org.apache.sis.measure.Units; +import org.apache.sis.referencing.CommonCRS; +import org.apache.sis.referencing.datum.DefaultEllipsoid; // Test dependencies import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.apache.sis.geometries.GeometryTest; @@ -31,6 +44,11 @@ import org.apache.sis.geometries.GeometryTest; * @author Johann Sorel (Geomatys) */ public class RhumbTest extends GeometryTest { + /** + * Geographic reference system on a sphere, with (longitude, latitude) axes in degrees. + */ + private static final CoordinateReferenceSystem SPHERE = CommonCRS.SPHERE.normalizedGeographic(); + @Test @Disabled("Not implemented yet.") public void testGetGeometryType() { @@ -41,9 +59,133 @@ public class RhumbTest extends GeometryTest { public void testGetInterpolation() { } + /** + * Tests the bearing along the equator, a closed parallel, a meridian, across the anti-meridian, + * and with (latitude, longitude, height) axes. + */ @Test - @Disabled("Not implemented yet.") public void testGetBearing() { + assertAzimuths(rhumb(CRS_2D, 0,0, 90,0, 0,0), 90, 270); + assertAzimuths(rhumb(CRS_2D, 0,80, 120,80, 240,80, 0,80), 90, 90, 90); + assertAzimuths(rhumb(CRS_2D, 10,0, 10,45, 10,0), 0, 180); + assertAzimuths(rhumb(CRS_2D, 170,10, -170,10, 170,10), 90, 270); + assertAzimuths(GeometryFactory.DEFAULT.createRhumb( + GeometryFactory.DEFAULT.createDataPoints(CRS_3D, 0,0,100, 0,90,200)), 90); + assertEquals(FixedDirection.TRUE_NORTH, rhumb(CRS_2D, 0,0, 90,0).getBearing(0).getReference()); + } + + /** + * Tests segment indices outside the range of segments. + */ + @Test + public void testGetBearingIndex() { + final Rhumb rhumb = rhumb(CRS_2D, 0,0, 90,0); + assertThrows(IndexOutOfBoundsException.class, () -> rhumb.getBearing(-1)); + assertThrows(IndexOutOfBoundsException.class, () -> rhumb.getBearing(1)); + } + + /** + * Tests segments half a turn apart, which go east. + */ + @Test + public void testGetBearingHalfTurn() { + assertAzimuths(rhumb(CRS_2D, 0,10, 180,10, 0,10), 90, 90); + final Rhumb rhumb = rhumb(CRS_2D, 0,10, 180,20, 0,10); + final double azimuth = azimuth(rhumb, 0); + assertTrue(azimuth > 0 && azimuth < 90, () -> "Azimuth " + azimuth + " does not go north-east."); + assertAzimuths(rhumb, azimuth, 180 - azimuth); + } + + /** + * Tests points on rhumb lines of known azimuth, on a sphere and on the WGS84 ellipsoid. + * On the ellipsoid, the azimuths would differ if computed on a sphere. + */ + @Test + public void testGetBearingOnRhumbLine() { + assertAzimuths(rhumb(SPHERE, rhumbLine(0, 30, 0, 20, 40, 60)), 30, 30, 30); + assertAzimuths(rhumb(SPHERE, rhumbLine(0, 210, 60, 40, 20, 0)), 210, 210, 210); + final double eccentricity = DefaultEllipsoid.castOrCopy(CommonCRS.WGS84.ellipsoid()).getEccentricity(); + assertAzimuths(rhumb(CRS_2D, rhumbLine(eccentricity, 60, -20, 10, 40, 70)), 60, 60, 60); + assertAzimuths(rhumb(CRS_2D, rhumbLine(eccentricity, 300, -20, 10, 40, 70)), 300, 300, 300); + assertAzimuths(rhumb(CRS_2D, rhumbLine(eccentricity, 120, 70, 40, 10, -20)), 120, 120, 120); + assertNotEquals(60, azimuth(rhumb(SPHERE, rhumbLine(eccentricity, 60, -20, 10, 40, 70)), 2), 1E-6); + } + + /** + * Tests segments from and to a pole, which follow meridians. + */ + @Test + public void testGetBearingPole() { + assertAzimuths(rhumb(CRS_2D, 30,80, 0,90, 120,80), 0, 180); + assertAzimuths(rhumb(CRS_2D, 30,-80, 0,-90, 0,90), 180, 0); + } + + /** + * Tests segments without length, which have no bearing. + */ + @Test + public void testGetBearingWithoutLength() { + assertAzimuths(rhumb(CRS_2D, 0,0, 0,0, 90,0, 450,0), Double.NaN, 90, Double.NaN); + assertAzimuths(rhumb(CRS_2D, 0,90, 120,90), Double.NaN); + assertAzimuths(rhumb(Geometries.getUndefinedCRS(2), 10,20, 10,20), Double.NaN); + } + + /** + * Tests a Cartesian system, where segments are straight and the bearing is measured from grid north. + */ + @Test + public void testGetBearingCartesian() { + final Rhumb rhumb = rhumb(Geometries.getUndefinedCRS(2), 0,0, 10,10, 20,10); + assertAzimuths(rhumb, 45, 90); + assertEquals(FixedDirection.GRID_NORTH, rhumb.getBearing(0).getReference()); + } + + /** + * Returns the (longitude, latitude) coordinates of points on a rhumb line starting at longitude 0°. + * The longitude is proportional to the isometric latitude ψ = atanh(sin φ) − ℯ⋅atanh(ℯ⋅sin φ). + * + * @param eccentricity eccentricity of the ellipsoid, 0 for a sphere. + * @param azimuth azimuth of the rhumb line in degrees, not 90° or 270°. + * @param latitudes latitudes of the points in degrees, the first one at longitude 0°. + */ + private static double[] rhumbLine(final double eccentricity, final double azimuth, final double... latitudes) { + final double slope = Math.tan(Math.toRadians(azimuth)); + final double start = isometricLatitude(eccentricity, latitudes[0]); + final double[] coordinates = new double[latitudes.length * 2]; + for (int i = 0; i < latitudes.length; i++) { + coordinates[i*2] = Math.toDegrees(slope * (isometricLatitude(eccentricity, latitudes[i]) - start)); + coordinates[i*2 + 1] = latitudes[i]; + } + return coordinates; + } + + private static double isometricLatitude(final double eccentricity, final double latitude) { + final double sin = Math.sin(Math.toRadians(latitude)); + return atanh(sin) - eccentricity * atanh(eccentricity * sin); + } + + private static double atanh(final double x) { + return 0.5 * Math.log((1 + x) / (1 - x)); + } + + private static double azimuth(final Rhumb rhumb, final int segment) { + final Bearing bearing = rhumb.getBearing(segment); + assertNotNull(bearing, () -> "No bearing for segment " + segment + " of " + rhumb); + return bearing.getAzimuth().to(Units.DEGREE).getValue().doubleValue(); + } + + /** + * Asserts the azimuth of each segment of the rhumb, NaN meaning that the segment has no bearing. + */ + private static void assertAzimuths(final Rhumb rhumb, final double... expected) { + assertEquals(expected.length, rhumb.getNumPoints() - 1); + for (int i = 0; i < expected.length; i++) { + if (Double.isNaN(expected[i])) { + assertNull(rhumb.getBearing(i)); + } else { + assertEquals(expected[i], azimuth(rhumb, i), TOLERANCE); + } + } } @Test @@ -273,9 +415,77 @@ public class RhumbTest extends GeometryTest { public void testGetGeometryType2() { } + /** + * Tests the envelope in a Cartesian system and along a parallel, where a rhumb does not bulge. + */ @Test - @Disabled("Not implemented yet.") public void testGetEnvelope() { + Envelope envelope = GeometryFactory.DEFAULT.createRhumb( + GeometryFactory.DEFAULT.createDataPoints(Geometries.getUndefinedCRS(2), 0,0, 10,10)).getEnvelope(); + assertRange(envelope, 0, 0, 10); + assertRange(envelope, 1, 0, 10); + + envelope = rhumb(CRS_2D, 0,45, 90,45).getEnvelope(); + assertRange(envelope, 0, 0, 90); + assertRange(envelope, 1, 45, 45); + } + + /** + * Tests a rhumb crossing the anti-meridian, and segments half a turn apart, which go east. + */ + @Test + public void testGetEnvelopeAcrossAntimeridian() { + Envelope envelope = rhumb(CRS_2D, 170,10, -170,20).getEnvelope(); + assertRange(envelope, 0, 170, -170); + assertRange(envelope, 1, 10, 20); + + envelope = rhumb(CRS_2D, 0,0, 180,0).getEnvelope(); + assertRange(envelope, 0, 0, 180); + } + + /** + * Tests a closed rhumb around the north pole, which crosses all longitudes but does not reach the pole. + */ + @Test + public void testGetEnvelopeAroundPole() { + final Envelope envelope = rhumb(CRS_2D, 0,80, 120,80, 240,80, 0,80).getEnvelope(); + assertRange(envelope, 0, -180, 180); + assertRange(envelope, 1, 80, 80); + } + + /** + * Tests a rhumb ending on a pole, where the longitude is undefined. + */ + @Test + public void testGetEnvelopeToPole() { + final Envelope envelope = rhumb(CRS_2D, 30,80, 0,90).getEnvelope(); + assertRange(envelope, 0, 30, 30); + assertRange(envelope, 1, 80, 90); + } + + /** + * Tests a reference system with (latitude, longitude, height) axes. + */ + @Test + public void testGetEnvelopeAxisOrder() { + final Envelope envelope = GeometryFactory.DEFAULT.createRhumb( + GeometryFactory.DEFAULT.createDataPoints(CRS_3D, 45,0,100, 50,90,200)).getEnvelope(); + assertRange(envelope, 0, 45, 50); + assertRange(envelope, 1, 0, 90); + assertRange(envelope, 2, 100, 200); + } + + private static Rhumb rhumb(final CoordinateReferenceSystem crs, final double... coordinates) { + return GeometryFactory.DEFAULT.createRhumb(GeometryFactory.DEFAULT.createDataPoints(crs, coordinates)); + } + + /** + * Asserts the raw bounds of the envelope in one dimension. The lower bound is greater than the upper one + * when the range crosses the anti-meridian. + */ + private static void assertRange(final Envelope envelope, final int dimension, final double lower, final double upper) { + assertEquals(lower, envelope.getLowerCorner().getCoordinate(dimension), TOLERANCE); + assertEquals(upper, envelope.getUpperCorner().getCoordinate(dimension), TOLERANCE); } @Test
