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 139333beb331bb92c4b958c1a78168c62e5ad893 Author: jsorel <[email protected]> AuthorDate: Mon Nov 16 15:10:39 2026 +0100 feat(SMC): add Spherical Multiple-Cell DGGRS --- ...g.dggs.DiscreteGlobalGridReferenceSystemFactory | 1 + .../main/module-info.java | 4 +- .../sis/referencing/dggs/smc/CellOutline.java | 184 +++++++++++ .../apache/sis/referencing/dggs/smc/SmcCoder.java | 84 +++++ .../apache/sis/referencing/dggs/smc/SmcDgg.java | 320 ++++++++++++++++++ .../apache/sis/referencing/dggs/smc/SmcDggh.java | 184 +++++++++++ .../apache/sis/referencing/dggs/smc/SmcDggrs.java | 360 +++++++++++++++++++++ .../apache/sis/referencing/dggs/smc/SmcDggs.java | 200 ++++++++++++ .../sis/referencing/dggs/smc/SmcFactory.java | 78 +++++ .../apache/sis/referencing/dggs/smc/SmcZone.java | 308 ++++++++++++++++++ .../sis/referencing/dggs/smc/package-info.java | 27 ++ .../DiscreteGlobalGridReferenceSystemsTest.java | 48 +++ .../sis/referencing/dggs/smc/SmcDggrsTest.java | 125 +++++++ .../sis/referencing/dggs/smc/SmcRotatedTest.java | 114 +++++++ .../apache/sis/referencing/dggs/smc/SmcTest.java | 273 ++++++++++++++++ 15 files changed, 2309 insertions(+), 1 deletion(-) diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/META-INF/services/org.apache.sis.referencing.dggs.DiscreteGlobalGridReferenceSystemFactory b/incubator/src/org.apache.sis.referencing.dggs/main/META-INF/services/org.apache.sis.referencing.dggs.DiscreteGlobalGridReferenceSystemFactory index 71959df9dd..7b55747722 100644 --- a/incubator/src/org.apache.sis.referencing.dggs/main/META-INF/services/org.apache.sis.referencing.dggs.DiscreteGlobalGridReferenceSystemFactory +++ b/incubator/src/org.apache.sis.referencing.dggs/main/META-INF/services/org.apache.sis.referencing.dggs.DiscreteGlobalGridReferenceSystemFactory @@ -1 +1,2 @@ org.apache.sis.referencing.dggs.s2.S2Factory +org.apache.sis.referencing.dggs.smc.SmcFactory diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/module-info.java b/incubator/src/org.apache.sis.referencing.dggs/main/module-info.java index d9774cbfde..f67330db56 100644 --- a/incubator/src/org.apache.sis.referencing.dggs/main/module-info.java +++ b/incubator/src/org.apache.sis.referencing.dggs/main/module-info.java @@ -30,6 +30,7 @@ module org.apache.sis.referencing.dggs { exports org.apache.sis.referencing.dggs; exports org.apache.sis.referencing.dggs.s2; + exports org.apache.sis.referencing.dggs.smc; exports org.apache.sis.referencing.rs; exports org.apache.sis.storage.coverage; exports org.apache.sis.storage.dggs; @@ -38,5 +39,6 @@ module org.apache.sis.referencing.dggs { uses org.apache.sis.referencing.dggs.DiscreteGlobalGridReferenceSystemFactory; provides org.apache.sis.referencing.dggs.DiscreteGlobalGridReferenceSystemFactory - with org.apache.sis.referencing.dggs.s2.S2Factory; + with org.apache.sis.referencing.dggs.s2.S2Factory, + org.apache.sis.referencing.dggs.smc.SmcFactory; } diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/CellOutline.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/CellOutline.java new file mode 100644 index 0000000000..ee41b1eef9 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/CellOutline.java @@ -0,0 +1,184 @@ +/* + * 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.referencing.dggs.smc; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.DoubleStream; +import com.google.common.geometry.S2LatLng; +import com.google.common.geometry.S2Loop; +import com.google.common.geometry.S2Point; +import com.google.common.geometry.S2Polygon; +import org.opengis.referencing.operation.TransformException; +import org.apache.sis.geometry.GeneralEnvelope; +import org.apache.sis.util.ArgumentChecks; + + +/** + * Outline of an SMC cell as a polygon on the sphere, and its envelope. + * <p> + * Polygon edges are great circle arcs while cell edges along parallels are not, so edges are densified. + * Meridians are great circles, but after a pole rotation their geographic extremes may lie between + * the cell corners, so they are densified too for accurate envelopes. + * + * <ul> + * <li>Edges are split in steps of at most 1° of lattice coordinates, then each step by the subdivision.</li> + * <li>Vertices are counter-clockwise. The south polar ring therefore runs westward.</li> + * </ul> + * + * @author Johann Sorel (Geomatys) + */ +final class CellOutline { + + /** + * Maximal length in degrees of an edge segment before subdivision. + */ + private static final double MAX_STEP = 1; + + private final SmcZone zone; + + /** + * Grid system converting lattice coordinates to the base CRS. + */ + private final SmcDggs dggs; + + CellOutline(final SmcZone zone) { + this.zone = zone; + this.dggs = zone.grid.dggrs.dggs; + } + + /** + * Returns the outline vertices as (longitude, latitude) pairs in lattice coordinates, without closing point. + * A polar cell has a single edge along its parallel, all around the pole. + * + * @param subdivision number of segments per edge step, at least 1. + * @return counter-clockwise vertices. + */ + double[] latticeRing(final int subdivision) { + ArgumentChecks.ensureStrictlyPositive("subdivision", subdivision); + final double west = zone.west(); + final double east = zone.east(); + final double south = zone.south(); + final double north = zone.north(); + final DoubleStream.Builder ring = DoubleStream.builder(); + if (!zone.isPolar()) { + addEdge(ring, west, south, east, south, subdivision); + addEdge(ring, east, south, east, north, subdivision); + addEdge(ring, east, north, west, north, subdivision); + addEdge(ring, west, north, west, south, subdivision); + } else if (zone.isNorthPolar()) { + addEdge(ring, west, south, east, south, subdivision); + } else { + addEdge(ring, east, north, west, north, subdivision); + } + return ring.build().toArray(); + } + + /** + * Adds the vertices of an edge, from its start point inclusive to its end point exclusive. + */ + private static void addEdge(final DoubleStream.Builder ring, final double startLongitude, final double startLatitude, + final double endLongitude, final double endLatitude, final int subdivision) + { + final double length = Math.max(Math.abs(endLongitude - startLongitude), Math.abs(endLatitude - startLatitude)); + final int count = Math.max(1, (int) Math.ceil(length / MAX_STEP)) * subdivision; + for (int i = 0; i < count; i++) { + ring.add(startLongitude + (endLongitude - startLongitude) * i / count) + .add(startLatitude + (endLatitude - startLatitude) * i / count); + } + } + + /** + * Returns the outline as an S2 polygon in the base CRS. + * + * @param subdivision number of segments per edge step, at least 1. + * @return polygon of the zone. + * @throws TransformException if a vertex cannot be converted. + */ + S2Polygon toPolygon(final int subdivision) throws TransformException { + final double[] ring = latticeRing(subdivision); + dggs.toBase(ring, 0, ring.length / 2); + final List<S2Point> points = new ArrayList<>(ring.length / 2); + for (int i = 0; i < ring.length; i += 2) { + points.add(S2LatLng.fromDegrees(ring[i + 1], ring[i]).toPoint()); + } + return new S2Polygon(new S2Loop(points)); + } + + /** + * Returns the envelope of the outline in the base CRS. + * <p> + * The longitude range is the smallest one containing all vertices, so it may cross the anti-meridian + * (west > east). A cell containing a geographic pole spans all longitudes up to that pole. + * For rotated lattices, latitude extremes are those of the densified vertices. + * + * @return envelope of the zone. + * @throws TransformException if a vertex cannot be converted. + */ + GeneralEnvelope envelope() throws TransformException { + final double[] ring = latticeRing(1); + final int count = ring.length / 2; + dggs.toBase(ring, 0, count); + final double[] longitudes = new double[count]; + double south = Double.POSITIVE_INFINITY; + double north = Double.NEGATIVE_INFINITY; + for (int i = 0; i < count; i++) { + longitudes[i] = ring[2 * i]; + south = Math.min(south, ring[2 * i + 1]); + north = Math.max(north, ring[2 * i + 1]); + } + Arrays.sort(longitudes); + double west = longitudes[0]; + double east = longitudes[count - 1]; + double gap = 360 - (east - west); + for (int i = 1; i < count; i++) { + final double candidate = longitudes[i] - longitudes[i - 1]; + if (candidate > gap) { + gap = candidate; + west = longitudes[i]; + east = longitudes[i - 1]; + } + } + if (east == -180 && west > east) { + east = 180; + } + if (containsPole(90)) { + north = 90; + west = -180; + east = 180; + } + if (containsPole(-90)) { + south = -90; + west = -180; + east = 180; + } + final GeneralEnvelope envelope = new GeneralEnvelope(dggs.getCrs()); + envelope.setRange(0, west, east); + envelope.setRange(1, south, north); + return envelope; + } + + /** + * Returns whether the cell contains the geographic pole of the given latitude. + */ + private boolean containsPole(final double latitude) throws TransformException { + final double[] pole = new double[] {0, latitude}; + dggs.toLattice(pole, 0, pole, 0); + return zone.equals(zone.grid.zoneAt(pole[0], pole[1])); + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcCoder.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcCoder.java new file mode 100644 index 0000000000..12bc5d72a2 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcCoder.java @@ -0,0 +1,84 @@ +/* + * 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.referencing.dggs.smc; + +import org.opengis.geometry.DirectPosition; +import org.opengis.referencing.operation.TransformException; +import org.apache.sis.referencing.dggs.DiscreteGlobalGridReferenceSystem; +import org.apache.sis.util.ArgumentChecks; + + +/** + * Converts positions to SMC zone identifiers at a chosen refinement level. + * + * @author Johann Sorel (Geomatys) + */ +final class SmcCoder extends DiscreteGlobalGridReferenceSystem.Coder { + + private final SmcDggrs dggrs; + + private int level; + + SmcCoder(final SmcDggrs dggrs) { + this.dggrs = dggrs; + } + + @Override + public SmcDggrs getReferenceSystem() { + return dggrs; + } + + @Override + public int getPrecisionLevel() { + return level; + } + + /** + * Sets the refinement level of encoded zones. + * + * @throws IllegalArgumentException if the level is outside the lattice levels. + */ + @Override + public void setPrecisionLevel(final int level) { + ArgumentChecks.ensureBetween("level", 0, dggrs.dggs.dggh.size() - 1, level); + this.level = level; + } + + /** + * Returns the {@code "level-i-j"} identifier of the zone containing the given position. + * + * @throws TransformException if the position cannot be converted or is outside the lattice domain. + */ + @Override + public String encode(final DirectPosition position) throws TransformException { + return getZone(position).getTextIdentifier().toString(); + } + + /** + * Returns the 64-bit identifier of the zone containing the given position. + * + * @throws TransformException if the position cannot be converted or is outside the lattice domain. + */ + @Override + public Long encodeIdentifier(final DirectPosition position) throws TransformException { + return getZone(position).getLongIdentifier(); + } + + private SmcZone getZone(final DirectPosition position) throws TransformException { + return dggrs.dggs.dggh.get(level).getZone(position); + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcDgg.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcDgg.java new file mode 100644 index 0000000000..aaea280964 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcDgg.java @@ -0,0 +1,320 @@ +/* + * 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.referencing.dggs.smc; + +import java.util.Collection; +import java.util.List; +import java.util.stream.LongStream; +import java.util.stream.Stream; +import javax.measure.Quantity; +import com.google.common.geometry.S2Polygon; +import org.opengis.geometry.DirectPosition; +import org.opengis.metadata.extent.GeographicExtent; +import org.opengis.referencing.operation.TransformException; +import org.apache.sis.measure.Quantities; +import org.apache.sis.measure.Units; +import org.apache.sis.referencing.dggs.Zone; +import org.apache.sis.referencing.dggs.internal.shared.AbstractDiscreteGlobalGrid; +import org.apache.sis.storage.dggs.DiscreteGlobalGridSystems; + + +/** + * All SMC cells of one refinement level. + * <p> + * Rows and columns are counted from the south-west corner of the domain, in units of this level. + * A cell is identified by its row and its first column, which is a multiple of the row merge factor. + * Coordinates are lattice coordinates in degrees. + * + * @author Johann Sorel (Geomatys) + * @see "Li 2023, SMC grid guide, sections 3.1 and 3.4" + */ +final class SmcDgg extends AbstractDiscreteGlobalGrid<SmcDggh> { + + final SmcDggrs dggrs; + + /** + * Cell width (before merging) and height in degrees. + */ + final double longitudeIncrement, latitudeIncrement; + + /** + * Number of columns (before merging) and of rows. + */ + final long columnCount, rowCount; + + /** + * Highest merge exponent, such that each row holds a whole number of cells, + * and at least 2 cells when the lattice wraps around the globe. + */ + private final int mergeCapExponent; + + /** + * Number of zones, computed when first needed. + */ + private volatile long zoneCount = -1; + + SmcDgg(final SmcDggh dggh, final int level) { + super(dggh, level); + dggrs = dggh.dggrs; + longitudeIncrement = Math.scalb(dggrs.longitudeIncrement, -level); + latitudeIncrement = Math.scalb(dggrs.latitudeIncrement, -level); + columnCount = ((long) dggrs.columnCount) << level; + rowCount = ((long) dggrs.rowCount) << level; + final int twos = Long.numberOfTrailingZeros(columnCount); + mergeCapExponent = (dggrs.wraps && Long.bitCount(columnCount) == 1) ? twos - 1 : twos; + } + + SmcDggh hierarchy() { + return hierarchy; + } + + /** + * Returns whether the given row is made of a single round polar cell. + * + * @see "Li 2023, SMC grid guide, section 3.4" + */ + boolean isPolarRow(final long row) { + return (dggrs.southPolar && row == 0) || (dggrs.northPolar && row == rowCount - 1); + } + + /** + * Returns the number of columns merged in each cell of the given row. + * <p> + * It is 2<sup><var>p</var></sup>, where <var>p</var> is the number of size-changing parallels + * arccos(2<sup>−<var>p</var></sup>) (60°, 75.5°, 82.8°, 86.4°, …) strictly crossed by the poleward edge of the row, + * which is the largest <var>p</var> with cos φ < 2<sup>−<var>p</var></sup>. A row ending exactly on a parallel, + * such as 60°, is not merged. The exponent is capped by {@link #mergeCapExponent}. + * Polar rows return the column count. + * + * @see "Li 2023, SMC grid guide, section 3.1" + */ + long mergeFactor(final long row) { + if (isPolarRow(row)) { + return columnCount; + } + final double poleward = Math.max(Math.abs(latitude(row)), Math.abs(latitude(row + 1))) - SmcDggrs.TOLERANCE; + final double log2 = -Math.log(Math.cos(Math.toRadians(poleward))) / Math.log(2); + return 1L << (int) Math.max(0, Math.min(Math.ceil(log2) - 1, mergeCapExponent)); + } + + /** + * Returns the latitude in degrees of the south edge of the given row. + * The row after the last one gives the domain north edge. Domain edges on poles are exactly ±90°. + */ + double latitude(final long row) { + if (row == 0 && dggrs.southPolar) return -90; + if (row == rowCount && dggrs.northPolar) return 90; + return dggrs.southLatitude + row * latitudeIncrement; + } + + /** + * Returns the longitude in degrees of the west edge of the given column. + */ + double longitude(final long column) { + return dggrs.westLongitude + column * longitudeIncrement; + } + + /** + * Returns the zone of the given row which contains the given column. + */ + SmcZone zoneCovering(final long row, final long column) { + return new SmcZone(this, row, column - Math.floorMod(column, mergeFactor(row))); + } + + /** + * Adds the zones of the given row which overlap the given range of columns. + * + * @param target where to add the zones. + * @param row row of the zones. + * @param from first column, inclusive. + * @param to last column, exclusive. + */ + void addZones(final Collection<? super SmcZone> target, final long row, final long from, final long to) { + final long step = mergeFactor(row); + for (long column = from - Math.floorMod(from, step); column < to; column += step) { + target.add(new SmcZone(this, row, column)); + } + } + + /** + * Returns the zone at the given indices. + * + * @throws IllegalArgumentException if the indices do not designate a cell of this level. + */ + SmcZone zone(final long row, final long column) { + if (row < 0 || row >= rowCount || column < 0 || column >= columnCount) { + throw new IllegalArgumentException("No row " + row + " and column " + column + " at level " + level + '.'); + } + final SmcZone zone = zoneCovering(row, column); + if (zone.column != column) { + throw new IllegalArgumentException("Column " + column + " of row " + row + " at level " + level + + " is not the first column of a cell. The cell starts at column " + zone.column + '.'); + } + return zone; + } + + /** + * Returns the zone containing the given lattice coordinates. + * + * @return the zone, or {@code null} if the coordinates are outside the domain or not finite. + */ + SmcZone zoneAt(final double longitude, final double latitude) { + if (!Double.isFinite(longitude) || !Double.isFinite(latitude) + || latitude < latitude(0) - SmcDggrs.TOLERANCE + || latitude > latitude(rowCount) + SmcDggrs.TOLERANCE) + { + return null; + } + final long row = Math.clamp((long) Math.floor((latitude - dggrs.southLatitude) / latitudeIncrement), 0, rowCount - 1); + double offset = longitude - dggrs.westLongitude; + offset -= 360 * Math.floor(offset / 360); + if (offset >= 360 - SmcDggrs.TOLERANCE) { + offset = 0; + } + if (!dggrs.wraps && offset > columnCount * longitudeIncrement + SmcDggrs.TOLERANCE) { + return null; + } + return zoneCovering(row, Math.clamp((long) Math.floor(offset / longitudeIncrement), 0, columnCount - 1)); + } + + /** + * Returns the zone containing the given lattice coordinates, or throws an exception if outside the domain. + */ + private SmcZone zoneAtOrFail(final double longitude, final double latitude) throws TransformException { + final SmcZone zone = zoneAt(longitude, latitude); + if (zone == null) { + throw new TransformException("Lattice position (" + longitude + ", " + latitude + + ") is outside the SMC lattice domain."); + } + return zone; + } + + /** + * Returns the cell height as a length on the sphere, which is the resolution quoted for SMC grids + * (for example 25 km for level 7 of the global lattice). + */ + @Override + public Quantity<?> getPrecision() { + return Quantities.create(Math.toRadians(latitudeIncrement) * dggrs.dggs.radius(), Units.METRE); + } + + /** + * Returns the zone containing the given position. + * + * @throws TransformException if the position cannot be converted or is outside the lattice domain. + */ + @Override + public SmcZone getZone(final DirectPosition position) throws TransformException { + final double[] coordinates = dggrs.dggs.toLattice(position); + return zoneAtOrFail(coordinates[0], coordinates[1]); + } + + /** + * Returns the number of zones. Runs of rows having the same merge factor are found by binary search + * on each side of the equator, where merge factors are monotonic. + */ + @Override + public long getZoneCount() { + long count = zoneCount; + if (count < 0) { + long low = 0; + long high = rowCount; + while (low < high) { + // Search the first row whose centre is not south of the equator. + final long mid = (low + high) >>> 1; + if (latitude(mid) + latitude(mid + 1) < 0) { + low = mid + 1; + } else { + high = mid; + } + } + zoneCount = count = countZones(0, low) + countZones(low, rowCount); + } + return count; + } + + /** + * Counts the zones of rows where merge factors are monotonic. + */ + private long countZones(final long start, final long end) { + long total = 0; + long row = start; + while (row < end) { + final long merge = mergeFactor(row); + long low = row; + long high = end - 1; + while (low < high) { + final long mid = (low + high + 1) >>> 1; + if (mergeFactor(mid) == merge) { + low = mid; + } else { + high = mid - 1; + } + } + total += (low - row + 1) * (columnCount / merge); + row = low + 1; + } + return total; + } + + /** + * Returns the zones intersecting the given extent, or all zones if the extent is null. + * All zones are streamed lazily, row by row from south to north. + */ + @Override + public Stream<Zone> getZones(final GeographicExtent extent) throws TransformException { + if (extent == null) { + return LongStream.range(0, rowCount).mapToObj(this::rowZones).flatMap((zones) -> zones); + } + final S2Polygon geometry = DiscreteGlobalGridSystems.toS2Polygon(extent); + final List<Zone> roots; + try (Stream<Zone> zones = hierarchy.get(0).getZones()) { + roots = zones.toList(); + } + return DiscreteGlobalGridSystems.spatialSearch(roots, level, geometry); + } + + private Stream<Zone> rowZones(final long row) { + final long step = mergeFactor(row); + return LongStream.iterate(0, (column) -> column < columnCount, (column) -> column + step) + .mapToObj((column) -> new SmcZone(this, row, column)); + } + + @Override + public Stream<Zone> getZones(final Zone parent) throws TransformException { + final int parentLevel = parent.getLocationType().getRefinementLevel(); + if (parentLevel > level) { + throw new IllegalArgumentException("Parent zone is at a finer level than this grid."); + } + return parent.getChildrenAtRelativeDepth(level - parentLevel); + } + + @Override + protected long getZoneLongIdentifier(final double[] source, final int offset) throws TransformException { + final double[] coordinates = new double[2]; + dggrs.dggs.toLattice(source, offset, coordinates, 0); + return hierarchy.encode(zoneAtOrFail(coordinates[0], coordinates[1])); + } + + @Override + protected void getZonePosition(final long zoneId, final double[] target, final int offset) throws TransformException { + final SmcZone zone = hierarchy.decode(zoneId); + target[offset] = zone.centerLongitude(); + target[offset + 1] = zone.centerLatitude(); + dggrs.dggs.toBase(target, offset, 1); + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcDggh.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcDggh.java new file mode 100644 index 0000000000..a636a7a4b9 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcDggh.java @@ -0,0 +1,184 @@ +/* + * 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.referencing.dggs.smc; + +import org.apache.sis.referencing.dggs.internal.shared.AbstractDiscreteGlobalGridHierarchy; + + +/** + * Hierarchy of SMC grids, from level 0 to the finest level whose identifiers fit in 64 bits. + * <p> + * Zone identifiers have two forms: + * <ul> + * <li>64-bit integers: bits 58 to 62 hold the level, followed by the row and then the column, both sized for + * the finest level. The sign bit is always 0, so identifiers sort by level, then row, then column.</li> + * <li>Texts of the form {@code "level-i-j"}, where <var>i</var> is the column and <var>j</var> the row + * of the cell south-west corner in units of the level. Example: {@code "7-1020-412"}.</li> + * </ul> + * Methods accepting an identifier of unknown form accept both, and SMC zones. + * + * @author Johann Sorel (Geomatys) + * @see "Li 2023, SMC grid guide, section 3.1" + */ +final class SmcDggh extends AbstractDiscreteGlobalGridHierarchy<SmcDggrs> { + + /** + * Number of bits available for row and column indices in long identifiers. + */ + private static final int INDEX_BITS = 58; + + /** + * Highest level which can be stored in the 5 remaining bits of long identifiers. + */ + private static final int LEVEL_LIMIT = 31; + + private static final char SEPARATOR = '-'; + + private final SmcDgg[] grids; + + /** + * Number of bits holding the column index in long identifiers. + */ + private final int columnBits; + + /** + * Creates the grids of all levels whose identifiers fit in 64 bits. + * + * @throws IllegalArgumentException if the indices of level 0 do not fit in identifiers. + */ + SmcDggh(final SmcDggrs dggrs) { + super(dggrs); + final int levelZeroBits = bitLength(dggrs.columnCount) + bitLength(dggrs.rowCount); + if (levelZeroBits > INDEX_BITS) { + throw new IllegalArgumentException("Level 0 indices need " + levelZeroBits + + " bits, but identifiers have only " + INDEX_BITS + '.'); + } + grids = new SmcDgg[Math.min(LEVEL_LIMIT, (INDEX_BITS - levelZeroBits) / 2) + 1]; + for (int i = 0; i < grids.length; i++) { + grids[i] = new SmcDgg(this, i); + } + columnBits = bitLength(grids[grids.length - 1].columnCount); + } + + /** + * Returns the number of bits needed for the indices from 0 inclusive to the given count exclusive. + */ + private static int bitLength(final long count) { + return Long.SIZE - Long.numberOfLeadingZeros(count - 1); + } + + @Override + public SmcDgg get(final int level) { + return grids[level]; + } + + @Override + public int size() { + return grids.length; + } + + @Override + public boolean supportLongIdentifiers() { + return true; + } + + @Override + public String toTextIdentifier(final Object zoneId) throws IllegalArgumentException { + return format(getZone(zoneId)); + } + + @Override + public long toLongIdentifier(final Object zoneId) throws IllegalArgumentException { + return encode(getZone(zoneId)); + } + + /** + * Returns the zone designated by the given identifier. + * + * @param identifier a {@link Long}, a {@link CharSequence} or an SMC zone. + * @throws IllegalArgumentException if the identifier type is unsupported or designates no cell. + */ + @Override + public SmcZone getZone(final Object identifier) throws IllegalArgumentException { + if (identifier instanceof SmcZone zone) { + return zone; + } else if (identifier instanceof CharSequence text) { + return parse(text); + } else if (identifier instanceof Long id) { + return decode(id); + } + throw new IllegalArgumentException("Unsupported SMC zone identifier: " + identifier); + } + + long encode(final SmcZone zone) { + return (((long) zone.grid.getRefinementLevel()) << INDEX_BITS) | (zone.row << columnBits) | zone.column; + } + + /** + * Returns the zone of the given 64-bit identifier. + * + * @throws IllegalArgumentException if the identifier designates no cell. + */ + SmcZone decode(final long identifier) { + if (identifier < 0) { + throw new IllegalArgumentException("Negative SMC zone identifier: " + identifier); + } + final long indices = identifier & ((1L << INDEX_BITS) - 1); + return grid((int) (identifier >>> INDEX_BITS)) + .zone(indices >>> columnBits, indices & ((1L << columnBits) - 1)); + } + + String format(final SmcZone zone) { + return Integer.toString(zone.grid.getRefinementLevel()) + SEPARATOR + zone.column + SEPARATOR + zone.row; + } + + /** + * Returns the zone of the given {@code "level-i-j"} identifier. + * + * @throws IllegalArgumentException if the identifier is malformed or designates no cell. + */ + SmcZone parse(final CharSequence identifier) { + final String text = identifier.toString().trim(); + final int first = text.indexOf(SEPARATOR); + final int second = text.indexOf(SEPARATOR, first + 1); + if (first <= 0 || second <= first + 1 || second == text.length() - 1 + || text.indexOf(SEPARATOR, second + 1) >= 0) + { + throw new IllegalArgumentException("SMC zone identifier must have the \"level-i-j\" form: " + text); + } + try { + final int level = Integer.parseInt(text, 0, first, 10); + final long column = Long.parseLong(text, first + 1, second, 10); + final long row = Long.parseLong(text, second + 1, text.length(), 10); + return grid(level).zone(row, column); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("SMC zone identifier must have the \"level-i-j\" form: " + text, e); + } + } + + /** + * Returns the grid of the given level. + * + * @throws IllegalArgumentException if the level does not exist. + */ + private SmcDgg grid(final int level) { + if (level < 0 || level >= grids.length) { + throw new IllegalArgumentException("Level " + level + " is outside the 0 … " + (grids.length - 1) + " range."); + } + return grids[level]; + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcDggrs.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcDggrs.java new file mode 100644 index 0000000000..f38c56d143 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcDggrs.java @@ -0,0 +1,360 @@ +/* + * 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.referencing.dggs.smc; + +import java.net.URI; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.opengis.metadata.extent.Extent; +import org.opengis.referencing.ObjectDomain; +import org.opengis.referencing.crs.GeographicCRS; +import org.opengis.referencing.gazetteer.LocationType; +import org.opengis.referencing.operation.MathTransform; +import org.opengis.util.FactoryException; +import org.opengis.util.InternationalString; +import org.apache.sis.measure.Longitude; +import org.apache.sis.metadata.iso.citation.Citations; +import org.apache.sis.metadata.iso.extent.DefaultExtent; +import org.apache.sis.metadata.iso.extent.DefaultGeographicBoundingBox; +import org.apache.sis.metadata.iso.extent.Extents; +import org.apache.sis.referencing.ImmutableIdentifier; +import org.apache.sis.referencing.gazetteer.ModifiableLocationType; +import org.apache.sis.referencing.operation.transform.DefaultMathTransformFactory; +import org.apache.sis.referencing.operation.transform.PoleRotation; +import org.apache.sis.util.ArgumentChecks; +import org.apache.sis.util.ComparisonMode; +import org.apache.sis.util.SimpleInternationalString; +import org.apache.sis.util.internal.shared.Constants; +import org.apache.sis.util.resources.Vocabulary; +import org.apache.sis.referencing.dggs.DiscreteGlobalGridReferenceSystem; +import org.apache.sis.referencing.dggs.DiscreteGlobalGridSystem; +import org.apache.sis.referencing.dggs.SubZoneOrder; +import org.apache.sis.referencing.dggs.ZonalReferenceSystem; +import org.apache.sis.referencing.dggs.internal.shared.DefaultZonalReferenceSystem; + + +/** + * Spherical Multiple-Cell (SMC) grid as a discrete global grid reference system. + * <p> + * The grid is a latitude/longitude lattice in lattice coordinates, which are the geographic coordinates rotated + * when a pole rotation is given. Level 0 is the coarsest level and level <var>k</var> divides the level 0 increments + * by 2<sup><var>k</var></sup>. A row merges its cells by 2<sup><var>p</var></sup>, where <var>p</var> is the number + * of size-changing parallels (arccos 2<sup>−<var>p</var></sup>) strictly crossed by its poleward edge. When the domain + * reaches a pole, the last row of each level is a single round polar cell. + * <p> + * Each level covers the whole domain, land included. A multi-resolution SMC grid of a wave model, such as SMC6-25, + * is a set of zones taken from several levels. Zone identifiers are 64-bit integers or {@code "level-i-j"} texts, + * where <var>i</var> is the column of the cell south-west corner and <var>j</var> its row, as in SMC cell arrays. + * + * @author Johann Sorel (Geomatys) + * @see "Li 2023, SMC grid guide, sections 3.1 and 3.4" + */ +public final class SmcDggrs extends DiscreteGlobalGridReferenceSystem { + + /** + * Identifier of the reference system on the global lattice. + */ + public static final String IDENTIFIER = "SMC"; + + /** + * Tolerance in degrees on the domain bounds and on the size-changing parallels. + */ + static final double TOLERANCE = 1e-9; + + private static final ZonalReferenceSystem ZRS = new DefaultZonalReferenceSystem("default", + "Level, then column and row of the cell south-west corner in units of the level.", true); + + /** + * Longitude and latitude in degrees of the domain south-west corner, in lattice coordinates. + */ + final double westLongitude, southLatitude; + + /** + * Cell width (before merging) and height in degrees at level 0. + */ + final double longitudeIncrement, latitudeIncrement; + + /** + * Number of columns and rows at level 0. + */ + final int columnCount, rowCount; + + /** + * Whether a pole rotation is applied, and the geographic position in degrees of the lattice north pole. + */ + final boolean rotated; + final double poleLatitude, poleLongitude; + + /** + * Whether the columns span 360°, and whether the domain reaches the south and north poles. + */ + final boolean wraps, southPolar, northPolar; + + final SmcDggs dggs; + + /** + * Creates the reference system on the global lattice and CRS:84. + */ + public SmcDggrs() { + this((GeographicCRS) null); + } + + /** + * Creates the reference system on the global lattice aligned with the Met Office SMC grids. + * <p> + * Level 0 has 8×6 cells of 45°×30° with the origin at 0°E, 90°S. Level 6 is the 50 km grid, level 7 the 25 km base + * (0.3515625°×0.234375°), and levels 8, 9 and 10 are the 12, 6 and 3 km refinements. + * + * @param base geographic CRS of zone positions and geometries, or {@code null} for CRS:84. + * @see "Li 2023, SMC grid guide, section 3.1" + */ + public SmcDggrs(final GeographicCRS base) { + this(IDENTIFIER, base, 0, -90, 45, 30, 8, 6); + } + + /** + * Creates a reference system on an unrotated lattice. + * <p> + * Constraints: + * <ul> + * <li>Increments are strictly positive and finite.</li> + * <li>The domain stays between −90° and 90° of latitude and spans at most 360° of longitude.</li> + * <li>The lattice wraps around the globe when its columns span exactly 360°. It then needs at least 2 columns.</li> + * <li>A domain reaching a pole must wrap around the globe.</li> + * <li>A domain reaching both poles needs at least 2 rows.</li> + * <li>Row and column indices of level 0 must fit in 58 bits.</li> + * <li>Merge factors are capped so that each row holds a whole number of cells, and at least 2 cells + * when the lattice wraps.</li> + * </ul> + * + * @param name name of the reference system. + * @param base geographic CRS of zone positions and geometries, or {@code null} for CRS:84. + * Its axes are normalized to (longitude, latitude) in degrees. + * @param westLongitude longitude in degrees of the domain west edge. + * @param southLatitude latitude in degrees of the domain south edge. + * @param longitudeIncrement cell width in degrees at level 0, before merging. + * @param latitudeIncrement cell height in degrees at level 0. + * @param columnCount number of columns at level 0. + * @param rowCount number of rows at level 0. + * @throws IllegalArgumentException if a constraint is violated. + */ + public SmcDggrs(final String name, final GeographicCRS base, + final double westLongitude, final double southLatitude, + final double longitudeIncrement, final double latitudeIncrement, + final int columnCount, final int rowCount) + { + this(name, base, westLongitude, southLatitude, longitudeIncrement, latitudeIncrement, + columnCount, rowCount, false, 90, 0, null); + } + + /** + * Creates a reference system on a lattice whose north pole is moved to the given geographic position. + * Rows and columns are defined in the rotated latitude/longitude coordinates. + * The constraints of the unrotated constructor apply to the rotated coordinates. + * + * @param name name of the reference system. + * @param base geographic CRS of zone positions and geometries, or {@code null} for CRS:84. + * @param westLongitude rotated longitude in degrees of the domain west edge. + * @param southLatitude rotated latitude in degrees of the domain south edge. + * @param longitudeIncrement cell width in degrees at level 0, before merging. + * @param latitudeIncrement cell height in degrees at level 0. + * @param columnCount number of columns at level 0. + * @param rowCount number of rows at level 0. + * @param poleLatitude geographic latitude in degrees of the lattice north pole. + * @param poleLongitude geographic longitude in degrees of the lattice north pole. + * @throws IllegalArgumentException if a constraint is violated. + * @throws FactoryException if the pole rotation cannot be created. + * @see "Li 2023, SMC grid guide, sections 6.3 and 7.5" + */ + public SmcDggrs(final String name, final GeographicCRS base, + final double westLongitude, final double southLatitude, + final double longitudeIncrement, final double latitudeIncrement, + final int columnCount, final int rowCount, + final double poleLatitude, final double poleLongitude) throws FactoryException + { + this(name, base, westLongitude, southLatitude, longitudeIncrement, latitudeIncrement, + columnCount, rowCount, true, poleLatitude, poleLongitude, + PoleRotation.rotateNorthPole(DefaultMathTransformFactory.provider(), poleLatitude, poleLongitude, 0)); + } + + private SmcDggrs(final String name, final GeographicCRS base, + final double westLongitude, final double southLatitude, + final double longitudeIncrement, final double latitudeIncrement, + final int columnCount, final int rowCount, + final boolean rotated, final double poleLatitude, final double poleLongitude, + final MathTransform rotation) + { + super(properties(name, rotated, westLongitude, southLatitude, + columnCount * longitudeIncrement, rowCount * latitudeIncrement), types(name)); + ArgumentChecks.ensureFinite("westLongitude", westLongitude); + ArgumentChecks.ensureFinite("southLatitude", southLatitude); + ArgumentChecks.ensureStrictlyPositive("longitudeIncrement", longitudeIncrement); + ArgumentChecks.ensureStrictlyPositive("latitudeIncrement", latitudeIncrement); + ArgumentChecks.ensureFinite("longitudeIncrement", longitudeIncrement); + ArgumentChecks.ensureFinite("latitudeIncrement", latitudeIncrement); + ArgumentChecks.ensureStrictlyPositive("columnCount", columnCount); + ArgumentChecks.ensureStrictlyPositive("rowCount", rowCount); + ArgumentChecks.ensureBetween("poleLatitude", -90.0, 90.0, poleLatitude); + ArgumentChecks.ensureFinite("poleLongitude", poleLongitude); + this.westLongitude = westLongitude; + this.southLatitude = southLatitude; + this.longitudeIncrement = longitudeIncrement; + this.latitudeIncrement = latitudeIncrement; + this.columnCount = columnCount; + this.rowCount = rowCount; + this.rotated = rotated; + this.poleLatitude = poleLatitude; + this.poleLongitude = poleLongitude; + + final double width = columnCount * longitudeIncrement; + final double north = southLatitude + rowCount * latitudeIncrement; + if (southLatitude < -90 - TOLERANCE || north > 90 + TOLERANCE) { + throw new IllegalArgumentException("Lattice rows span " + southLatitude + "° to " + north + + "°, which is outside the −90° … 90° range."); + } + if (width > 360 + TOLERANCE) { + throw new IllegalArgumentException("Lattice columns span " + width + "°, which is more than 360°."); + } + wraps = Math.abs(width - 360) <= TOLERANCE; + southPolar = Math.abs(southLatitude + 90) <= TOLERANCE; + northPolar = Math.abs(north - 90) <= TOLERANCE; + if ((southPolar || northPolar) && !wraps) { + throw new IllegalArgumentException("A lattice reaching a pole must span 360° of longitude."); + } + if (wraps && columnCount < 2) { + throw new IllegalArgumentException("A lattice spanning 360° of longitude needs at least 2 columns."); + } + if (southPolar && northPolar && rowCount < 2) { + throw new IllegalArgumentException("A lattice reaching both poles needs at least 2 rows."); + } + dggs = new SmcDggs(this, base, rotation); + } + + @Override + public List<String> getKeywords() { + return List.of("smc", "spherical multiple-cell", "dggs", "wave model"); + } + + @Override + public Optional<InternationalString> getDescription() { + return Optional.of(new SimpleInternationalString( + "Spherical Multiple-Cell grid: a latitude-longitude grid whose cells are halved at each refinement " + + "level, merged longitudinally at high latitudes to relax the CFL restriction, and closed by round " + + "polar cells. It is used by the WAVEWATCH III ocean wave model.")); + } + + /** + * Returns the WAVEWATCH III repository, which hosts the SMC grid documentation. + */ + @Override + public URI getUri() { + return URI.create("https://github.com/NOAA-EMC/WW3"); + } + + @Override + public DiscreteGlobalGridSystem getGridSystem() { + return dggs; + } + + @Override + public ZonalReferenceSystem getZonalSystem() { + return ZRS; + } + + /** + * Returns {@link SubZoneOrder#SCANLINE}: children are listed row by row from south to north, then west to east. + */ + @Override + public SubZoneOrder getSubZoneOrder() { + return SubZoneOrder.SCANLINE; + } + + @Override + public Coder createCoder() { + return new SmcCoder(this); + } + + /** + * Compares the lattice definitions in addition to the properties compared by the parent class. + */ + @Override + public boolean equals(final Object object, final ComparisonMode mode) { + if (!super.equals(object, mode)) { + return false; + } + if (object instanceof SmcDggrs other) { + return Double.compare(westLongitude, other.westLongitude) == 0 + && Double.compare(southLatitude, other.southLatitude) == 0 + && Double.compare(longitudeIncrement, other.longitudeIncrement) == 0 + && Double.compare(latitudeIncrement, other.latitudeIncrement) == 0 + && Double.compare(poleLatitude, other.poleLatitude) == 0 + && Double.compare(poleLongitude, other.poleLongitude) == 0 + && columnCount == other.columnCount + && rowCount == other.rowCount + && rotated == other.rotated; + } + return mode != ComparisonMode.STRICT; + } + + @Override + protected long computeHashCode() { + return super.computeHashCode() + 31L * Objects.hash(westLongitude, southLatitude, + longitudeIncrement, latitudeIncrement, columnCount, rowCount, rotated, poleLatitude, poleLongitude); + } + + private static LocationType[] types(final String name) { + final ModifiableLocationType type = new ModifiableLocationType(name); + type.addIdentification(Vocabulary.formatInternational(Vocabulary.Keys.Code)); + return new LocationType[] {type}; + } + + private static Map<String,Object> properties(final String name, final boolean rotated, + final double west, final double south, final double width, final double height) + { + final Map<String,Object> properties = new HashMap<>(8); + properties.put(NAME_KEY, name); + properties.put(IDENTIFIERS_KEY, new ImmutableIdentifier(Citations.SIS, Constants.SIS, name)); + properties.put(ObjectDomain.DOMAIN_OF_VALIDITY_KEY, domainOfValidity(rotated, west, south, width, height)); + properties.put(THEME_KEY, Vocabulary.formatInternational(Vocabulary.Keys.Mapping)); + return properties; + } + + /** + * Returns the geographic area covered by the lattice. Rotated lattices declare the whole world. + */ + private static Extent domainOfValidity(final boolean rotated, final double west, final double south, + final double width, final double height) + { + final double north = south + height; + final boolean allLongitudes = width >= 360 - TOLERANCE; + if (rotated || (allLongitudes && south <= -90 + TOLERANCE && north >= 90 - TOLERANCE)) { + return Extents.WORLD; + } + double lower = -180; + double upper = 180; + if (!allLongitudes) { + lower = Longitude.normalize(west); + upper = lower + width; + if (upper > 180) upper -= 360; + } + return new DefaultExtent(null, new DefaultGeographicBoundingBox( + lower, upper, Math.max(-90, south), Math.min(90, north)), null, null); + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcDggs.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcDggs.java new file mode 100644 index 0000000000..2c0ac5274e --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcDggs.java @@ -0,0 +1,200 @@ +/* + * 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.referencing.dggs.smc; + +import java.util.List; +import org.opengis.geometry.DirectPosition; +import org.opengis.referencing.crs.CoordinateReferenceSystem; +import org.opengis.referencing.crs.GeographicCRS; +import org.opengis.referencing.operation.MathTransform; +import org.opengis.referencing.operation.TransformException; +import org.opengis.util.FactoryException; +import org.apache.sis.geometry.DirectPosition2D; +import org.apache.sis.measure.Longitude; +import org.apache.sis.referencing.CRS; +import org.apache.sis.referencing.CommonCRS; +import org.apache.sis.referencing.crs.DefaultGeographicCRS; +import org.apache.sis.referencing.cs.AxesConvention; +import org.apache.sis.referencing.operation.transform.TransformFactoryException; +import org.apache.sis.util.Utilities; +import org.apache.sis.referencing.dggs.GridConstraints; +import org.apache.sis.referencing.dggs.PolyhedronOrientation; +import org.apache.sis.referencing.dggs.PolyhedronParameters; +import org.apache.sis.referencing.dggs.RefinementStrategy; +import org.apache.sis.referencing.dggs.internal.shared.AbstractDiscreteGlobalGridSystem; + + +/** + * Grid system of an SMC reference system, with the conversions between its base CRS and lattice coordinates. + * <p> + * There is no base polyhedron: the lattice is defined directly on (rotated) latitude and longitude. + * Base and lattice coordinates are (longitude, latitude) pairs in degrees, which differ only when the lattice + * has a rotated pole. Longitudes returned in the base CRS are normalized to the [−180 … 180)° range. + * + * @author Johann Sorel (Geomatys) + * @see "Li 2023, SMC grid guide, sections 3.1, 6.3 and 7.5" + */ +final class SmcDggs extends AbstractDiscreteGlobalGridSystem { + + private final SmcDggrs dggrs; + + /** + * Rotation from base to lattice coordinates, or {@code null} for the identity. + */ + private final MathTransform toLattice; + + final SmcDggh dggh; + + /** + * Creates the grid system of the given reference system. + * + * @param dggrs the reference system, with its lattice definition already set. + * @param base base CRS, or {@code null} for CRS:84. Its axes are normalized. + * @param toLattice rotation from base to lattice coordinates, or {@code null} for the identity. + */ + SmcDggs(final SmcDggrs dggrs, final GeographicCRS base, final MathTransform toLattice) { + super(base == null ? CommonCRS.WGS84.normalizedGeographic() + : DefaultGeographicCRS.castOrCopy(base).forConvention(AxesConvention.NORMALIZED)); + this.dggrs = dggrs; + this.toLattice = toLattice; + this.dggh = new SmcDggh(dggrs); + } + + /** + * Returns the radius of the sphere having the surface of the celestial body. + */ + double radius() { + return Math.sqrt(getCelestialBodySurface() / (4 * Math.PI)); + } + + /** + * Converts a position to lattice coordinates. + * + * @param position position in any CRS. Positions without CRS are assumed in the base CRS. + * @return (longitude, latitude) in lattice coordinates. + * @throws TransformException if the position cannot be converted. + */ + double[] toLattice(final DirectPosition position) throws TransformException { + DirectPosition source = position; + final CoordinateReferenceSystem positionCrs = position.getCoordinateReferenceSystem(); + if (positionCrs != null && !Utilities.equalsIgnoreMetadata(crs, positionCrs)) { + try { + source = CRS.findOperation(positionCrs, crs, null).getMathTransform().transform(position, null); + } catch (FactoryException e) { + throw new TransformFactoryException(e); + } + } + final double[] coordinates = new double[] {source.getCoordinate(0), source.getCoordinate(1)}; + toLattice(coordinates, 0, coordinates, 0); + return coordinates; + } + + /** + * Converts one (longitude, latitude) pair from the base CRS to lattice coordinates. + * The source and target arrays may be the same. + */ + void toLattice(final double[] source, final int sourceOffset, final double[] target, final int targetOffset) + throws TransformException + { + if (toLattice != null) { + toLattice.transform(source, sourceOffset, target, targetOffset, 1); + } else { + target[targetOffset] = source[sourceOffset]; + target[targetOffset + 1] = source[sourceOffset + 1]; + } + } + + /** + * Converts (longitude, latitude) pairs from lattice coordinates to the base CRS, in place. + * + * @param coordinates pairs to convert. + * @param offset index of the first longitude. + * @param count number of pairs. + */ + void toBase(final double[] coordinates, final int offset, final int count) throws TransformException { + if (toLattice != null) { + toLattice.inverse().transform(coordinates, offset, coordinates, offset, count); + } + for (int i = offset, end = offset + 2 * count; i < end; i += 2) { + coordinates[i] = Longitude.normalize(coordinates[i]); + } + } + + /** + * Converts lattice coordinates to a position in the base CRS. + */ + DirectPosition2D toPosition(final double longitude, final double latitude) throws TransformException { + final double[] coordinates = new double[] {longitude, latitude}; + toBase(coordinates, 0, 1); + return new DirectPosition2D(crs, coordinates[0], coordinates[1]); + } + + @Override + public SmcDggh getHierarchy() { + return dggh; + } + + @Override + public String getBasePolyhedron() { + return "none"; + } + + /** + * Returns 4, the number of children of a cell whose rows keep the same merge factor. + */ + @Override + public int getRefinementRatio() { + return 4; + } + + @Override + public int getSpatialDimensions() { + return 2; + } + + @Override + public int getTemporalDimensions() { + return 0; + } + + @Override + public List<String> getZoneTypes() { + return List.of(SmcZone.QUADRILATERAL, SmcZone.POLAR_CAP); + } + + /** + * Returns the geographic position of the lattice north pole. + */ + @Override + public PolyhedronParameters getParameters() { + return new PolyhedronParameters(new PolyhedronOrientation( + dggrs.poleLatitude, dggrs.poleLongitude, 0, "Geographic position of the lattice north pole.")); + } + + @Override + public List<RefinementStrategy> getRefinementStrategy() { + return List.of(RefinementStrategy.nestedChildCell); + } + + /** + * Returns {@code cellAxisAligned} for unrotated lattices, and an empty list otherwise. + */ + @Override + public List<GridConstraints> getGridConstraints() { + return dggrs.rotated ? List.of() : List.of(GridConstraints.cellAxisAligned); + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcFactory.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcFactory.java new file mode 100644 index 0000000000..bbaf4b2148 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcFactory.java @@ -0,0 +1,78 @@ +/* + * 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.referencing.dggs.smc; + +import java.util.Collection; +import java.util.List; +import org.opengis.referencing.crs.CoordinateReferenceSystem; +import org.opengis.referencing.crs.GeographicCRS; +import org.opengis.util.FactoryException; +import org.opengis.util.NoSuchIdentifierException; +import org.apache.sis.referencing.dggs.DiscreteGlobalGridReferenceSystem; +import org.apache.sis.referencing.dggs.DiscreteGlobalGridReferenceSystemFactory; + + +/** + * Creates SMC reference systems on the global lattice. + * Other lattices are created with the {@link SmcDggrs} constructors. + * + * @author Johann Sorel (Geomatys) + */ +public final class SmcFactory implements DiscreteGlobalGridReferenceSystemFactory { + + private static final String ZONAL_REFERENCE = "default"; + + /** + * Creates a factory. Invoked by {@link java.util.ServiceLoader}. + */ + public SmcFactory() { + } + + @Override + public Collection<String> listDggh() { + return List.of(SmcDggrs.IDENTIFIER); + } + + @Override + public Collection<String> listZonalRefId(final String dggh) { + return List.of(ZONAL_REFERENCE); + } + + /** + * Creates the SMC reference system on the global lattice. + * + * @param dgghId must be {@code "SMC"}. + * @param zonalRefId {@code "default"} or {@code null}. + * @param base geographic CRS, or {@code null} for CRS:84. + * @throws FactoryException if an argument is not supported. + */ + @Override + public DiscreteGlobalGridReferenceSystem createDggrs(final String dgghId, final String zonalRefId, + final CoordinateReferenceSystem base) throws FactoryException + { + if (!SmcDggrs.IDENTIFIER.equals(dgghId)) { + throw new NoSuchIdentifierException("Unknown identifier " + dgghId, dgghId); + } + if (zonalRefId != null && !ZONAL_REFERENCE.equals(zonalRefId)) { + throw new NoSuchIdentifierException("Unknown zonal reference " + zonalRefId, zonalRefId); + } + if (base == null || base instanceof GeographicCRS) { + return new SmcDggrs((GeographicCRS) base); + } + throw new FactoryException("SMC grids require a geographic base CRS."); + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcZone.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcZone.java new file mode 100644 index 0000000000..8644abfaa2 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/SmcZone.java @@ -0,0 +1,308 @@ +/* + * 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.referencing.dggs.smc; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import org.opengis.geometry.DirectPosition; +import org.opengis.geometry.Envelope; +import org.opengis.metadata.extent.BoundingPolygon; +import org.opengis.referencing.operation.TransformException; +import org.apache.sis.geometry.wrapper.s2.S2; +import org.apache.sis.referencing.dggs.RefinementLevel; +import org.apache.sis.referencing.dggs.internal.shared.AbstractZone; +import org.apache.sis.util.collection.BackingStoreException; + + +/** + * Cell of an SMC grid, identified by its level, its row and its first column. + * <p> + * The column is the index of the cell south-west corner in units of the level, as the <var>i</var> index + * of SMC cell arrays. It is therefore a multiple of the row merge factor, and 0 for polar cells. + * Bounds are in lattice coordinates. + * + * @author Johann Sorel (Geomatys) + * @see "Li 2023, SMC grid guide, section 3.1" + */ +final class SmcZone extends AbstractZone<SmcDggrs> { + + /** + * Shape of all cells except polar ones. + */ + static final String QUADRILATERAL = "quadrilateral"; + + /** + * Shape of the round cells centred on lattice poles. + */ + static final String POLAR_CAP = "polar cap"; + + final SmcDgg grid; + final long row; + final long column; + + SmcZone(final SmcDgg grid, final long row, final long column) { + super(grid.dggrs); + this.grid = grid; + this.row = row; + this.column = column; + } + + /** + * Returns whether this cell is a round cell centred on a lattice pole. + * + * @see "Li 2023, SMC grid guide, section 3.4" + */ + boolean isPolar() { + return grid.isPolarRow(row); + } + + /** + * Returns whether this cell is the polar cell of the lattice north pole. + */ + boolean isNorthPolar() { + return isPolar() && north() == 90; + } + + long mergeFactor() { + return grid.mergeFactor(row); + } + + double west() { + return grid.longitude(column); + } + + double east() { + return grid.longitude(column + mergeFactor()); + } + + double south() { + return grid.latitude(row); + } + + double north() { + return grid.latitude(row + 1); + } + + /** + * Returns the longitude of the representative position. Polar cells use the domain west edge. + */ + double centerLongitude() { + return isPolar() ? west() : (west() + east()) / 2; + } + + /** + * Returns the latitude of the representative position. Polar cells use their pole. + */ + double centerLatitude() { + if (isPolar()) { + return isNorthPolar() ? 90 : -90; + } + return (south() + north()) / 2; + } + + /** + * Returns the 64-bit identifier as a {@link Long}. + */ + @Override + public Object getIdentifier() { + return getLongIdentifier(); + } + + @Override + public long getLongIdentifier() { + return grid.hierarchy().encode(this); + } + + /** + * Returns the {@code "level-i-j"} identifier. + */ + @Override + public CharSequence getTextIdentifier() { + return grid.hierarchy().format(this); + } + + @Override + public String getShapeType() { + return isPolar() ? POLAR_CAP : QUADRILATERAL; + } + + /** + * Returns the cell area on the sphere having the celestial body surface. + */ + @Override + public Double getAreaMetersSquare() { + final double radius = dggrs.dggs.radius(); + final double width = Math.toRadians(east() - west()); + return radius * radius * width * Math.abs(Math.sin(Math.toRadians(north())) - Math.sin(Math.toRadians(south()))); + } + + @Override + public RefinementLevel getLocationType() { + return new RefinementLevel(dggrs, grid.getRefinementLevel()); + } + + /** + * Returns the cell of the previous level which contains this cell. + * + * @return the parent, or {@code null} at level 0. + */ + @Override + public SmcZone getFirstParent() { + final int level = grid.getRefinementLevel(); + return (level > 0) ? getFirstParent(level - 1) : null; + } + + /** + * Returns the cell of the given level which contains this cell. + * Since cells are nested, it is the cell covering the south-west corner of this cell. + * + * @throws IllegalArgumentException if the level is negative or finer than the level of this zone. + */ + @Override + public SmcZone getFirstParent(final int refinementLevel) { + final int depth = grid.getRefinementLevel() - refinementLevel; + if (refinementLevel < 0 || depth < 0) { + throw new IllegalArgumentException("Level " + refinementLevel + " is not an ancestor level of " + this); + } + return grid.hierarchy().get(refinementLevel).zoneCovering(row >> depth, column >> depth); + } + + @Override + public List<SmcZone> getParents() { + final SmcZone parent = getFirstParent(); + return (parent != null) ? List.of(parent) : List.of(); + } + + /** + * Returns the cells of the next level which exactly cover this cell, row by row from south to north + * and from west to east. + * <p> + * There are 4 children when the merge factor does not change. A child row merging fewer columns than + * the row of this cell holds more children, and the children of a polar cell are the next polar cell + * and its whole ring row. + * + * @return the children, or an empty list at the finest level. + */ + @Override + public List<SmcZone> getChildren() { + final SmcDggh hierarchy = grid.hierarchy(); + final int level = grid.getRefinementLevel() + 1; + if (level >= hierarchy.size()) { + return List.of(); + } + final SmcDgg finer = hierarchy.get(level); + final List<SmcZone> children = new ArrayList<>(); + final long first = column << 1; + final long end = (column + mergeFactor()) << 1; + finer.addZones(children, row << 1, first, end); + finer.addZones(children, (row << 1) + 1, first, end); + return children; + } + + /** + * Returns the cells of the same level which share an edge, or part of an edge, with this cell. + * <p> + * The neighbors of a polar cell are all cells of its ring row. + * Cells outside a regional domain are omitted. + * + * @return the neighbors, without duplicates and without this cell. + */ + @Override + public Set<SmcZone> getNeighbors() { + final Set<SmcZone> neighbors = new LinkedHashSet<>(); + final long end = column + mergeFactor(); + if (!isPolar()) { + for (final long adjacent : new long[] {column - 1, end}) { + final long c = dggrs.wraps ? Math.floorMod(adjacent, grid.columnCount) : adjacent; + if (c >= 0 && c < grid.columnCount) { + neighbors.add(grid.zoneCovering(row, c)); + } + } + } + if (row > 0) { + grid.addZones(neighbors, row - 1, column, end); + } + if (row + 1 < grid.rowCount) { + grid.addZones(neighbors, row + 1, column, end); + } + neighbors.remove(this); + return neighbors; + } + + @Override + public BoundingPolygon getGeographicExtent() { + return getGeographicExtent(1); + } + + /** + * Returns the cell outline with parallels densified by the given subdivision. + */ + @Override + public BoundingPolygon getGeographicExtent(final int subdivision) { + try { + return S2.toGeographicExtent(new CellOutline(this).toPolygon(subdivision)); + } catch (TransformException e) { + throw new BackingStoreException(e); + } + } + + /** + * Returns the cell envelope in the base CRS. Polar cells extend to their pole. + */ + @Override + public Envelope getEnvelope() { + try { + return new CellOutline(this).envelope(); + } catch (TransformException e) { + throw new BackingStoreException(e); + } + } + + /** + * Returns the cell centre, or the pole for polar cells, in the base CRS. + */ + @Override + public DirectPosition getPosition() { + try { + return dggrs.dggs.toPosition(centerLongitude(), centerLatitude()); + } catch (TransformException e) { + throw new BackingStoreException(e); + } + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) return true; + if (!(obj instanceof SmcZone)) return false; + final SmcZone other = (SmcZone) obj; + return row == other.row && column == other.column + && grid.getRefinementLevel() == other.grid.getRefinementLevel() + && (dggrs == other.dggrs || dggrs.equals(other.dggrs)); + } + + @Override + public int hashCode() { + return (31 * Long.hashCode(row) + Long.hashCode(column)) * 37 + grid.getRefinementLevel(); + } + + @Override + public String toString() { + return "SmcZone[" + getTextIdentifier() + ']'; + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/package-info.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/package-info.java new file mode 100644 index 0000000000..31c3667ddf --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/smc/package-info.java @@ -0,0 +1,27 @@ +/* + * 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. + */ + +/** + * Spherical Multiple-Cell (<abbr>SMC</abbr>) grid as a discrete global grid reference system. + * <p> + * The SMC grid is the multi-resolution latitude-longitude grid of the WAVEWATCH III ocean wave model. + * This package provides its full hierarchy, land included, on a parametric and optionally rotated lattice. + * + * @author Johann Sorel (Geomatys) + * @see "Li 2023, Spherical Multiple-Cell Grid and Applications in Ocean Surface Wave Models" + */ +package org.apache.sis.referencing.dggs.smc; diff --git a/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/DiscreteGlobalGridReferenceSystemsTest.java b/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/DiscreteGlobalGridReferenceSystemsTest.java new file mode 100644 index 0000000000..4eef3b4234 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/DiscreteGlobalGridReferenceSystemsTest.java @@ -0,0 +1,48 @@ +/* + * 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.referencing.dggs; + +import org.opengis.util.FactoryException; +import org.opengis.util.NoSuchIdentifierException; +import org.apache.sis.referencing.dggs.s2.S2Dggrs; +import org.apache.sis.referencing.dggs.smc.SmcDggrs; + +// Test dependencies +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + + +/** + * Tests {@link DiscreteGlobalGridReferenceSystems}. + * + * @author Johann Sorel (Geomatys) + */ +public class DiscreteGlobalGridReferenceSystemsTest { + + /** + * Tests the code forms accepted by {@link DiscreteGlobalGridReferenceSystems#forCode(String)}. + */ + @Test + public void testForCode() throws FactoryException { + assertInstanceOf(S2Dggrs.class, DiscreteGlobalGridReferenceSystems.forCode("S2")); + assertInstanceOf(S2Dggrs.class, DiscreteGlobalGridReferenceSystems.forCode("[ogc-dggrs:S2]")); + assertInstanceOf(S2Dggrs.class, DiscreteGlobalGridReferenceSystems.forCode("https://www.opengis.net/def/dggrs/S2")); + assertInstanceOf(SmcDggrs.class, DiscreteGlobalGridReferenceSystems.forCode("SMC")); + assertInstanceOf(SmcDggrs.class, DiscreteGlobalGridReferenceSystems.forCode("smc")); + assertThrows(NoSuchIdentifierException.class, () -> DiscreteGlobalGridReferenceSystems.forCode("unknown")); + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/smc/SmcDggrsTest.java b/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/smc/SmcDggrsTest.java new file mode 100644 index 0000000000..f5351d6bfc --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/smc/SmcDggrsTest.java @@ -0,0 +1,125 @@ +/* + * 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.referencing.dggs.smc; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.Stream; +import org.opengis.referencing.operation.TransformException; +import org.apache.sis.geometry.DirectPosition2D; +import org.apache.sis.referencing.CommonCRS; +import org.apache.sis.referencing.dggs.Zone; + +// Test dependencies +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + + +/** + * Tests the validation of {@link SmcDggrs} lattice definitions and regional lattices. + * + * @author Johann Sorel (Geomatys) + */ +public class SmcDggrsTest { + + /** + * Regional lattice over the North Atlantic, with an odd number of columns. + * Rows beyond 60° are merged from level 1. + */ + private static final SmcDggrs REGIONAL = new SmcDggrs("Regional", null, -20, 45, 4, 3, 7, 6); + + private static SmcDgg grid(final int level) { + return REGIONAL.dggs.dggh.get(level); + } + + /** + * Tests the constraints listed in the {@link SmcDggrs} constructor javadoc. + */ + @Test + public void testValidation() { + assertThrows(IllegalArgumentException.class, () -> new SmcDggrs("Test", null, 0, 0, 10, 10, 10, 9), "Pole reached without wrapping."); + assertThrows(IllegalArgumentException.class, () -> new SmcDggrs("Test", null, 0, -90, 50, 30, 8, 6), "More than 360°."); + assertThrows(IllegalArgumentException.class, () -> new SmcDggrs("Test", null, 0, -90, 360, 30, 1, 6), "Wrapping with a single column."); + assertThrows(IllegalArgumentException.class, () -> new SmcDggrs("Test", null, 0, -90, 45, 180, 8, 1), "Both poles in a single row."); + assertThrows(IllegalArgumentException.class, () -> new SmcDggrs("Test", null, 0, -10, 1e-9, 1e-9, Integer.MAX_VALUE, Integer.MAX_VALUE), "Identifier overflow."); + assertThrows(IllegalArgumentException.class, () -> new SmcDggrs("Test", null, 0, -10, 0, 1, 10, 10), "Zero increment."); + assertFalse(REGIONAL.wraps); + assertTrue(new SmcDggrs().wraps); + } + + /** + * Two reference systems with the same name but different lattices are not equal. + */ + @Test + public void testEquals() { + assertEquals(new SmcDggrs(), new SmcDggrs()); + assertNotEquals(new SmcDggrs(), new SmcDggrs(SmcDggrs.IDENTIFIER, null, 0, -90, 90, 30, 4, 6)); + } + + /** + * Parent and children stay nested in a regional lattice with merged rows. + */ + @Test + public void testRegionalNesting() { + assertEquals(1, grid(0).mergeFactor(5)); + assertEquals(2, grid(1).mergeFactor(11)); + for (int level = 0; level <= 3; level++) { + for (SmcZone zone : allZones(level)) { + double area = 0; + for (SmcZone child : zone.getChildren()) { + assertEquals(zone, child.getFirstParent()); + area += child.getAreaMetersSquare(); + } + assertEquals(zone.getAreaMetersSquare(), area, 1e-12 * zone.getAreaMetersSquare(), zone::toString); + } + } + } + + /** + * Neighbors and positions outside a regional domain do not exist. + */ + @Test + public void testRegionalBounds() throws TransformException { + assertEquals(Set.of(grid(0).zone(0, 1), grid(0).zone(1, 0)), grid(0).zone(0, 0).getNeighbors()); + for (int level = 0; level <= 3; level++) { + for (SmcZone zone : allZones(level)) { + for (SmcZone neighbor : zone.getNeighbors()) { + assertTrue(neighbor.getNeighbors().contains(zone), () -> zone + " is not a neighbor of " + neighbor); + } + } + } + assertThrows(TransformException.class, () -> grid(0).getZone( + new DirectPosition2D(CommonCRS.WGS84.normalizedGeographic(), 100, 50))); + final SmcZone zone = grid(0).getZone(new DirectPosition2D(CommonCRS.WGS84.normalizedGeographic(), -19, 46)); + assertEquals("0-0-0", zone.getTextIdentifier().toString()); + + for (int level = 0; level <= 3; level++) { + try (Stream<Zone> zones = grid(level).getZones()) { + assertEquals(grid(level).getZoneCount(), zones.count()); + } + } + } + + private static List<SmcZone> allZones(final int level) { + final List<SmcZone> zones = new ArrayList<>(); + for (long row = 0; row < grid(level).rowCount; row++) { + grid(level).addZones(zones, row, 0, grid(level).columnCount); + } + return zones; + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/smc/SmcRotatedTest.java b/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/smc/SmcRotatedTest.java new file mode 100644 index 0000000000..4b37534703 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/smc/SmcRotatedTest.java @@ -0,0 +1,114 @@ +/* + * 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.referencing.dggs.smc; + +import javax.measure.IncommensurableException; +import org.opengis.geometry.DirectPosition; +import org.opengis.geometry.Envelope; +import org.opengis.referencing.operation.TransformException; +import org.opengis.util.FactoryException; +import org.apache.sis.geometry.DirectPosition2D; +import org.apache.sis.referencing.CommonCRS; +import org.apache.sis.referencing.dggs.GridConstraints; + +// Test dependencies +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; +import org.apache.sis.referencing.dggs.AbstractDggrsTest; + + +/** + * Tests {@link SmcDggrs} on a global lattice whose north pole is at 135°E 10°N, + * the rotated pole of the Arctic SMC grid. + * + * @author Johann Sorel (Geomatys) + * @see "Li 2023, SMC grid guide, section 7.5" + */ +public class SmcRotatedTest extends AbstractDggrsTest { + + private static final SmcDggrs SMC; + static { + try { + SMC = new SmcDggrs("SMC rotated", null, 0, -90, 45, 30, 8, 6, 10, 135); + } catch (FactoryException e) { + throw new ExceptionInInitializerError(e); + } + } + + public SmcRotatedTest() { + super(SMC); + } + + private SmcZone zoneAt(final int level, final double longitude, final double latitude) throws TransformException { + final DirectPosition position = new DirectPosition2D(CommonCRS.WGS84.normalizedGeographic(), longitude, latitude); + return SMC.dggs.dggh.get(level).getZone(position); + } + + /** + * The geographic position of the rotated pole is in the lattice north polar cell. + */ + @Test + public void testLatticePole() throws TransformException { + final SmcZone zone = zoneAt(4, 135, 10); + assertTrue(zone.isNorthPolar()); + final DirectPosition position = zone.getPosition(); + assertEquals(135, position.getCoordinate(0), 1e-9); + assertEquals(10, position.getCoordinate(1), 1e-9); + } + + /** + * The geographic north pole is at lattice latitude 10°, and the envelope of its cell reaches it. + */ + @Test + public void testGeographicPole() throws TransformException { + final SmcZone zone = zoneAt(3, 0, 90); + assertFalse(zone.isPolar()); + assertTrue(zone.south() <= 10 && zone.north() >= 10, zone::toString); + final Envelope envelope = zone.getEnvelope(); + assertEquals(90, envelope.getMaximum(1)); + assertEquals(-180, envelope.getMinimum(0)); + assertEquals(180, envelope.getMaximum(0)); + } + + /** + * Enabled for SMC, which passes the spatial search test disabled for other reference systems. + */ + @Test + @Override + public void testSearchEnvelope() throws TransformException, IncommensurableException { + super.testSearchEnvelope(); + } + + /** + * Enabled for SMC, which passes the cell geometry test disabled for other reference systems. + */ + @Test + @Override + public void testPickingInCellGeometry() throws TransformException, IncommensurableException { + super.testPickingInCellGeometry(); + } + + /** + * Rotated cells are not aligned with the base CRS axes. + */ + @Test + public void testGridConstraints() { + assertFalse(SMC.getGridSystem().getGridConstraints().contains(GridConstraints.cellAxisAligned)); + assertEquals(10, SMC.getGridSystem().getParameters().getOrientation().getLatitude()); + assertEquals(135, SMC.getGridSystem().getParameters().getOrientation().getLongitude()); + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/smc/SmcTest.java b/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/smc/SmcTest.java new file mode 100644 index 0000000000..bada4012f3 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/smc/SmcTest.java @@ -0,0 +1,273 @@ +/* + * 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.referencing.dggs.smc; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; +import javax.measure.IncommensurableException; +import org.opengis.geometry.Envelope; +import org.opengis.referencing.operation.TransformException; +import org.apache.sis.geometry.DirectPosition2D; +import org.apache.sis.referencing.CommonCRS; +import org.apache.sis.referencing.dggs.DiscreteGlobalGridReferenceSystem; +import org.apache.sis.referencing.dggs.Zone; + +// Test dependencies +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; +import org.apache.sis.referencing.dggs.AbstractDggrsTest; + + +/** + * Tests {@link SmcDggrs} on the global lattice. + * + * @author Johann Sorel (Geomatys) + */ +public class SmcTest extends AbstractDggrsTest { + + private static final SmcDggrs SMC = new SmcDggrs(); + + public SmcTest() { + super(SMC); + } + + private static SmcDgg grid(final int level) { + return SMC.dggs.dggh.get(level); + } + + /** + * Levels 7 and 9 have the cell sizes of the SMC6-25 grid. + */ + @Test + public void testIncrements() { + assertEquals(0.3515625, grid(7).longitudeIncrement); + assertEquals(0.234375, grid(7).latitudeIncrement); + assertEquals(0.087890625, grid(9).longitudeIncrement); + assertEquals(0.05859375, grid(9).latitudeIncrement); + assertEquals(1024, grid(7).columnCount); + assertEquals(768, grid(7).rowCount); + assertEquals(27, SMC.dggs.dggh.size()); + } + + /** + * At level 7, the polar cells are surrounded by 8 cells. + */ + @Test + public void testPolarRing() { + final SmcDgg grid = grid(7); + assertTrue(grid.isPolarRow(0)); + assertTrue(grid.isPolarRow(grid.rowCount - 1)); + assertFalse(grid.isPolarRow(1)); + assertEquals(8, grid.columnCount / grid.mergeFactor(grid.rowCount - 2)); + assertEquals(8, grid.columnCount / grid.mergeFactor(1)); + + final SmcZone north = grid.zoneAt(0, 90); + assertTrue(north.isNorthPolar()); + assertEquals(8, north.getNeighbors().size()); + final SmcZone south = grid.zoneAt(0, -90); + assertTrue(south.isPolar()); + assertFalse(south.isNorthPolar()); + assertEquals(8, south.getNeighbors().size()); + } + + /** + * At level 7, rows between the 3rd (82.8°) and 4th (86.4°) size-changing parallels hold 128 cells, + * and no row is merged up to 60°. + */ + @Test + public void testMergeFactors() { + final SmcDgg grid = grid(7); + assertEquals(128, grid.columnCount / grid.zoneAt(0, 84).mergeFactor()); + assertEquals(128, grid.columnCount / grid.zoneAt(0, -84).mergeFactor()); + assertEquals(64, grid.columnCount / grid.zoneAt(0, 87).mergeFactor()); + + final SmcZone below60 = grid.zoneAt(0, 59.9); + assertEquals(60, below60.north()); + assertEquals(1, below60.mergeFactor()); + assertEquals(2, grid.zoneAt(0, 60.1).mergeFactor()); + for (long row = 0; row < grid.rowCount; row++) { + if (Math.max(Math.abs(grid.latitude(row)), Math.abs(grid.latitude(row + 1))) <= 60) { + assertEquals(1, grid.mergeFactor(row)); + } + } + } + + /** + * Every non-polar row keeps at least 2 cells and a whole number of cells. + */ + @Test + public void testRowCellCounts() { + for (int level = 0; level <= 10; level++) { + final SmcDgg grid = grid(level); + for (long row = 0; row < grid.rowCount; row++) { + final long merge = grid.mergeFactor(row); + assertEquals(0, grid.columnCount % merge); + if (!grid.isPolarRow(row)) { + assertTrue(grid.columnCount / merge >= 2); + } + } + } + } + + /** + * Children exactly cover their parent, including merged and polar cells. + */ + @Test + public void testChildrenCoverParent() { + final List<SmcZone> zones = new ArrayList<>(); + for (int level = 0; level <= 2; level++) { + zones.addAll(allZones(level)); + } + zones.addAll(rowZones(7, grid(7).rowCount - 1)); + zones.addAll(rowZones(7, grid(7).rowCount - 2)); + zones.add(grid(6).zoneAt(10, 60.1)); + zones.add(grid(5).zoneAt(10, 75.2)); // Parallel 75.52° crosses the upper child row only. + zones.add(grid(6).zoneAt(10, -82.9)); + for (SmcZone zone : zones) { + final List<SmcZone> children = zone.getChildren(); + assertTrue(children.size() >= 2, zone::toString); + double area = 0; + for (SmcZone child : children) { + assertEquals(zone, child.getFirstParent()); + assertTrue(child.south() >= zone.south() && child.north() <= zone.north(), child::toString); + assertTrue(child.west() >= zone.west() && child.east() <= zone.east(), child::toString); + area += child.getAreaMetersSquare(); + } + assertEquals(zone.getAreaMetersSquare(), area, 1e-12 * zone.getAreaMetersSquare(), zone::toString); + } + } + + /** + * Neighborhood is symmetric, across the seam, merge boundaries and polar rings. + */ + @Test + public void testNeighborSymmetry() { + final List<SmcZone> zones = new ArrayList<>(allZones(2)); + for (long row : new long[] {0, 1, 2, 383, 384, 640, 641, 765, 766, 767}) { + zones.addAll(rowZones(7, row)); + } + for (SmcZone zone : zones) { + for (SmcZone neighbor : zone.getNeighbors()) { + assertTrue(neighbor.getNeighbors().contains(zone), () -> zone + " is not a neighbor of " + neighbor); + } + } + final SmcDgg grid = grid(2); + assertTrue(grid.zone(10, 0).getNeighbors().contains(grid.zone(10, grid.columnCount - 1))); + } + + /** + * The zone count computed per merge band equals the number of enumerated zones. + */ + @Test + public void testZoneCount() throws TransformException { + assertEquals(34, grid(0).getZoneCount()); + for (int level = 0; level <= 4; level++) { + try (Stream<Zone> zones = grid(level).getZones()) { + assertEquals(grid(level).getZoneCount(), zones.count()); + } + } + } + + /** + * Tests the long and text identifiers. + */ + @Test + public void testIdentifiers() throws Exception { + final DiscreteGlobalGridReferenceSystem.Coder coder = SMC.createCoder(); + coder.setPrecisionLevel(7); + assertEquals("7-0-384", coder.encode(new DirectPosition2D(CommonCRS.WGS84.normalizedGeographic(), 0.1, 0.1))); + assertEquals("7-0-767", coder.encode(new DirectPosition2D(CommonCRS.WGS84.normalizedGeographic(), 45, 90))); + + final SmcDggh hierarchy = SMC.dggs.dggh; + final SmcDgg finest = grid(SMC.dggs.dggh.size() - 1); + final List<SmcZone> zones = new ArrayList<>(allZones(1)); + zones.add(finest.zoneAt(179.9, 89.9)); + zones.add(finest.zoneAt(-0.1, -89.99)); + zones.add(finest.zoneAt(0, 90)); + for (SmcZone zone : zones) { + final long id = zone.getLongIdentifier(); + assertTrue(id >= 0); + assertEquals(zone, hierarchy.decode(id)); + assertEquals(zone, hierarchy.parse(zone.getTextIdentifier())); + } + assertThrows(IllegalArgumentException.class, () -> hierarchy.parse("7-8-767")); + assertThrows(IllegalArgumentException.class, () -> hierarchy.parse("7-0")); + assertThrows(IllegalArgumentException.class, () -> hierarchy.parse("a-b-c")); + assertThrows(IllegalArgumentException.class, () -> hierarchy.parse("27-0-0")); + assertThrows(IllegalArgumentException.class, () -> hierarchy.decode(-1)); + } + + /** + * Polar envelopes reach the pole and cells ending on the anti-meridian end at 180°. + */ + @Test + public void testEnvelopes() { + final SmcZone polar = grid(3).zoneAt(0, 90); + assertEquals(SmcZone.POLAR_CAP, polar.getShapeType()); + Envelope envelope = polar.getEnvelope(); + assertEquals(90, envelope.getMaximum(1)); + assertEquals(-180, envelope.getMinimum(0)); + assertEquals(180, envelope.getMaximum(0)); + + envelope = grid(0).zoneAt(170, 10).getEnvelope(); + assertEquals(135, envelope.getMinimum(0)); + assertEquals(180, envelope.getMaximum(0)); + assertEquals(0, envelope.getMinimum(1)); + assertEquals(30, envelope.getMaximum(1)); + } + + /** + * Enabled for SMC, which passes the spatial search test disabled for other reference systems. + */ + @Test + @Override + public void testSearchEnvelope() throws TransformException, IncommensurableException { + super.testSearchEnvelope(); + } + + /** + * Enabled for SMC, which passes the cell geometry test disabled for other reference systems. + */ + @Test + @Override + public void testPickingInCellGeometry() throws TransformException, IncommensurableException { + super.testPickingInCellGeometry(); + } + + /** + * The precision of level 7 is its cell height, about 25 km. + */ + @Test + public void testPrecision() { + assertEquals(26000, grid(7).getPrecision().getValue().doubleValue(), 500); + } + + private static List<SmcZone> allZones(final int level) { + final List<SmcZone> zones = new ArrayList<>(); + for (long row = 0; row < grid(level).rowCount; row++) { + zones.addAll(rowZones(level, row)); + } + return zones; + } + + private static List<SmcZone> rowZones(final int level, final long row) { + final List<SmcZone> zones = new ArrayList<>(); + grid(level).addZones(zones, row, 0, grid(level).columnCount); + return zones; + } +}
