This is an automated email from the ASF dual-hosted git repository. asf-gitbox-commits pushed a commit to branch feat/isea3h-geogrid in repository https://gitbox.apache.org/repos/asf/sis.git
commit cfef031e6898f6573da12a8f3698725b65124117 Author: jsorel <[email protected]> AuthorDate: Fri Nov 27 14:09:10 2026 +0100 feat(ISEA3H): add ISEA3H DGGRS by Franz-Benjamin Mocnik, original code from GeoGrid --- NOTICE | 4 + .../sis/referencing/dggs/isea/cells/GridCell.java | 132 ++++ .../dggs/isea/cells/GridCellIDType.java | 26 + .../dggs/isea/cells/GridCellMetaData.java | 70 ++ .../dggs/isea/examples/AdaptiveIDs.java | 36 ++ .../referencing/dggs/isea/examples/Example.java | 73 +++ .../dggs/isea/examples/SaveGridToDisk.java | 71 ++ .../dggs/isea/generic/Trigonometric.java | 49 ++ .../sis/referencing/dggs/isea/generic/Tuple.java | 37 ++ .../sis/referencing/dggs/isea/geo/WGS84.java | 30 + .../dggs/isea/geometry/FaceCoordinates.java | 54 ++ .../dggs/isea/geometry/GeoCoordinates.java | 63 ++ .../sis/referencing/dggs/isea/grids/ISEA3H.java | 713 +++++++++++++++++++++ .../sis/referencing/dggs/isea/package-info.java | 279 ++++++++ .../dggs/isea/projections/ISEAProjection.java | 511 +++++++++++++++ .../referencing/dggs/isea/grids/ISEA3HTest.java | 122 ++++ .../dggs/isea/projections/ISEAProjectionTest.java | 48 ++ parent/pom.xml | 9 + 18 files changed, 2327 insertions(+) diff --git a/NOTICE b/NOTICE index 264fbe7072..32042fab03 100644 --- a/NOTICE +++ b/NOTICE @@ -38,6 +38,10 @@ The test suite uses software developed by the JUnit community under Eclipse public license version 2. https://junit.org/junit5/ +The `org.apache.sis.referencing.dggs.isea` package contains code +adapted from GeoGrid ISEA Aperture 3 Hexagon Discrete Global Grid System in dual license MIT and Apache 2. +https://github.com/mocnik-science/geogrid + ------------------------------------------------------------- Optional modules NOT included unless explicitly requested diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/cells/GridCell.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/cells/GridCell.java new file mode 100644 index 0000000000..3856d5823a --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/cells/GridCell.java @@ -0,0 +1,132 @@ +/* + * 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.isea.cells; + +import org.apache.sis.referencing.dggs.isea.geometry.GeoCoordinates; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +/** + * Grid cell + * + * @author Franz-Benjamin Mocnik + */ +public class GridCell implements Comparable<GridCell>, Serializable { + private static final double _precision = 1e-9; + private static final double _precisionPerDefinition = 1e-5; + private final Integer _resolution; + private final double _lat; + private final double _lon; + private final boolean _isPentagon; + private Map<GridCellIDType, Long> _id = new HashMap(); + + public GridCell(int resolution, double lat, double lon, boolean isPentagon) throws Exception { + if (resolution < 1 || resolution > 22) throw new Exception("resolution must be between 1 and 22"); + this._resolution = resolution; + if (lat < -90 || lat > 90) throw new Exception("invalid latitude"); + if (lat < -90 + GridCell._precisionPerDefinition || lat > 90 - GridCell._precisionPerDefinition) lon = 0; + lon %= 360; + if (lon > 180) lon -= 360; + else if (lon < -180) lon += 360; + this._lat = lat; + this._lon = lon; + this._isPentagon = isPentagon; + } + + public GridCell(int resolution, GeoCoordinates c, boolean isPentagon) throws Exception { + this(resolution, c.getLat(), c.getLon(), isPentagon); + } + + public Integer getResolution() { + return this._resolution; + } + + public Double getLat() { + return this._lat; + } + + public Double getLon() { + return this._lon; + } + + public Boolean isPentagon() { + return this._isPentagon; + } + + /** + * Returns the ID of the cell. The ID consists of the following elements: + * <ul> + * <li>The leading sign is positive in case of a hexagon, and negative in case of a pentagon.</li> + * <li>This first two digits consist of the resolution incremented by 22 in case of negative latitude, by 44 in + * case of negative longitude, and by 66 in case of negative latitude and longitude. In case that the + * latitude/longitude is strictly less than .5e-6, or that the difference of longitude to 180 or -180 degrees is + * strictly less than .5e-6, the respective sign is always regarded as being positive.</li> + * <li>The consecutive digits consist of the latitude, with two pre-decimal and six decimal places.</li> + * <li>The consecutive digits consist of the longitude, with three pre-decimal and six decimal places. The + * longitude is per definition 0 if the latitude differs from -90 or 90 degrees by strictly less than + * .5e-6. The longitude is expected to be greater than -180 and strictly less than 180 degrees.</li> + * </ul> + * + * If the grid cell type ADAPTIVE_UNIQUE is provided, the values for latitude and longitude are only encoded with + * the precision required to guarantee uniqueness of the IDs. In case of ADAPTIVE_1_PERCENT, the values for + * latitude and longitude are encoded with two more decimal places as in the previous case. + * + * The ID is only valid for resolution smaller less or equal 22. + * + * @return ID of the cell + */ + public Long getID() { + return this.getID(GridCellIDType.NON_ADAPTIVE); + } + + public Long getID(GridCellIDType gridCellIDType) { + Long id = this._id.getOrDefault(gridCellIDType, null); + if (id == null) { + int numberOfDecimalPlaces = GridCellMetaData.getInstance().numberOfDecimalPlaces(this.getResolution(), gridCellIDType); + double precisionPerDefinition = .5 * Math.pow(10, -numberOfDecimalPlaces); + long sgnLat = (this._lat <= -precisionPerDefinition) ? 22 : 0; + long sgnLon = (this._lon <= -precisionPerDefinition && 180 - Math.abs(this._lon) >= precisionPerDefinition) ? 44 : 0; + id = (this._isPentagon ? -1 : 1) * ((this._resolution.longValue() + sgnLat + sgnLon) * (long) Math.pow(10, 2 * numberOfDecimalPlaces + 5) + Math.abs(Math.round((this._lat + this._precision) * Math.pow(10, numberOfDecimalPlaces))) * (long) Math.pow(10, numberOfDecimalPlaces + 3) + Math.abs(Math.round((this._lon + this._precision) * Math.pow(10, numberOfDecimalPlaces)))); + this._id.put(gridCellIDType, id); + } + return id; + } + + public boolean equals(Object o) { + return (o instanceof GridCell) && ((GridCell) o).getID().equals(this.getID()); + } + + public int hashCode() { + return Long.hashCode(this.getID()); + } + + @Override + public String toString() { + return String.format("resolution %d lat %f lon %f - %d", this._resolution, this._lat, this._lon, this.getID()); + } + + @Override + public int compareTo(GridCell o) { + int d = Integer.compare(this._resolution, o._resolution); + if (d != 0) return d; + d = (Math.abs(this._lat - o._lat) < GridCell._precision) ? 0 : Double.compare(this._lat, o._lat); + if (d != 0) return d; + return (Math.abs(this._lon - o._lon) < GridCell._precision) ? 0 : Double.compare(this._lon, o._lon); + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/cells/GridCellIDType.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/cells/GridCellIDType.java new file mode 100644 index 0000000000..e77a0e50d3 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/cells/GridCellIDType.java @@ -0,0 +1,26 @@ +/* + * 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.isea.cells; + +/** + * ID type for a grid cell + */ +public enum GridCellIDType { + NON_ADAPTIVE, + ADAPTIVE_UNIQUE, + ADAPTIVE_1_PERCENT, +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/cells/GridCellMetaData.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/cells/GridCellMetaData.java new file mode 100644 index 0000000000..892b4e3edc --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/cells/GridCellMetaData.java @@ -0,0 +1,70 @@ +/* + * 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.isea.cells; + +import org.apache.sis.referencing.dggs.isea.geo.WGS84; +import org.apache.sis.referencing.dggs.isea.grids.ISEA3H; + +import java.util.HashMap; +import java.util.Map; + +/** + * Meta data for a grid cell + * + * @author Franz-Benjamin Mocnik + */public class GridCellMetaData { + private static GridCellMetaData _gridCellMetaData = new GridCellMetaData(); + private static final int _maxNumberOfDecimalPlaces = 6; + private Map<Integer, Integer> _numberOfDecimalPlaces = new HashMap(); + + private GridCellMetaData() {} + + /** + * Get an instance of this (singleton) class + * + * @return singleton class + */ + public static GridCellMetaData getInstance() { + return GridCellMetaData._gridCellMetaData; + } + + /** + * Returns the number of decimal places to be used for the ID for a given resolution and a given ID type + * + * @param resolution + * @param gridCellIDType + * @return number of decimal places + */ + public int numberOfDecimalPlaces(int resolution, GridCellIDType gridCellIDType) { + if (gridCellIDType == GridCellIDType.NON_ADAPTIVE) return this._maxNumberOfDecimalPlaces; + int nodp; + if (this._numberOfDecimalPlaces.containsKey(resolution)) nodp = this._numberOfDecimalPlaces.get(resolution); + else { + double distBetweenCells = 2 * (new ISEA3H(resolution)).lowerBoundForLengthOfASideOfHexagonalCellOnSphere(); + nodp = (int)Math.ceil(-Math.log10(distBetweenCells / (2 * Math.PI * WGS84.radiusAuthalic / 360))); + this._numberOfDecimalPlaces.put(resolution, nodp); + } + switch (gridCellIDType) { + case ADAPTIVE_UNIQUE: + return Math.max(Math.min(nodp, this._maxNumberOfDecimalPlaces), 0); + case ADAPTIVE_1_PERCENT: + return Math.max(Math.min(nodp + 2, this._maxNumberOfDecimalPlaces), 0); + default: + return this._maxNumberOfDecimalPlaces; + } + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/examples/AdaptiveIDs.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/examples/AdaptiveIDs.java new file mode 100644 index 0000000000..2b729a3b89 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/examples/AdaptiveIDs.java @@ -0,0 +1,36 @@ +/* + * 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.isea.examples; + +import org.apache.sis.referencing.dggs.isea.cells.GridCellIDType; +import org.apache.sis.referencing.dggs.isea.cells.GridCellMetaData; + +/** + * Computes the number of decimal places needed at a given resolution, depending on the type of cell ID. + * + * @author Franz-Benjamin Mocnik + */ +public class AdaptiveIDs { + public static void main(String[] args) throws Exception { + for (int resolution = 1; resolution <= 22; resolution++) { + System.out.println("====== " + resolution); + System.out.println(GridCellMetaData.getInstance().numberOfDecimalPlaces(resolution, GridCellIDType.NON_ADAPTIVE)); + System.out.println(GridCellMetaData.getInstance().numberOfDecimalPlaces(resolution, GridCellIDType.ADAPTIVE_UNIQUE)); + System.out.println(GridCellMetaData.getInstance().numberOfDecimalPlaces(resolution, GridCellIDType.ADAPTIVE_1_PERCENT)); + } + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/examples/Example.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/examples/Example.java new file mode 100644 index 0000000000..25169daf25 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/examples/Example.java @@ -0,0 +1,73 @@ +/* + * 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.isea.examples; + +import org.apache.sis.referencing.dggs.isea.cells.GridCell; +import org.apache.sis.referencing.dggs.isea.geometry.FaceCoordinates; +import org.apache.sis.referencing.dggs.isea.geometry.GeoCoordinates; +import org.apache.sis.referencing.dggs.isea.grids.ISEA3H; +import org.apache.sis.referencing.dggs.isea.projections.ISEAProjection; + +import java.util.Collection; + +/** + * Demonstrates the use of the projection from the sphere to the icosahedron and back, as well as the use of the ISEA3H + * grid. + * + * @author Franz-Benjamin Mocnik + */ +public class Example { + public static void main(String[] args) throws Exception { + // PROJECTION + ISEAProjection p = new ISEAProjection(); + + // project coordinates from the sphere to the icosahedron and back + for (int i = 0; i < 1; i++) { + GeoCoordinates c = new GeoCoordinates(Math.random() * 180 - 90, Math.random() * 360); + FaceCoordinates c2 = p.sphereToIcosahedron(c); + GeoCoordinates c3 = p.icosahedronToSphere(c2); + System.out.println(c); + System.out.println(c2); + System.out.println(c3); + System.out.println("------"); + } + + // GRID + ISEA3H g = new ISEA3H(14); + + // print properties of the grid + System.out.format("number of hexagon cells: %d%n", g.numberOfHexagonalCells()); + System.out.format("number of pentagon cells: %d%n", g.numberOfPentagonalCells()); + System.out.format("diameter of a hexagon cell: %f%n", g.diameterOfHexagonalCellOnIcosahedron()); + System.out.format("area of a hexagon cell: %f%n", g.areaOfAHexagonalCell()); + System.out.println("------"); + + // get cells in given bounds + Collection<GridCell> cells = g.cellsForBound(41, 42, 6, 7); + System.out.println(cells.size()); + System.out.println("------"); + + // determine cell for geographic coordinates + for (int i = 0; i < 1; i++) { + double lat = Math.random() * 180 - 90; + double lon = Math.random() * 360; + GridCell c = g.cellForLocation(lat, lon); + System.out.println(c); + System.out.println("------"); + } + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/examples/SaveGridToDisk.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/examples/SaveGridToDisk.java new file mode 100644 index 0000000000..0b4d705959 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/examples/SaveGridToDisk.java @@ -0,0 +1,71 @@ +/* + * 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.isea.examples; + +import org.apache.sis.referencing.dggs.isea.grids.ISEA3H; +import org.apache.sis.referencing.dggs.isea.cells.GridCellIDType; + +import java.io.File; +import java.io.IOException; + +/** + * Run this class in order to compute the number of cells in a grid for a given resolution, and check for non-unique IDs + * per face of the icosahedron. + * + * The output is written to result.txt, the result, to result.log. + * + * @author Franz-Benjamin Mocnik + */ +public class SaveGridToDisk { + private static final String path = "data"; + private static final int resolutionMax = 14; + + public static void main(String[] args) throws Exception { + if (!new File(SaveGridToDisk.path).exists()) new File(SaveGridToDisk.path).mkdirs(); + + for (int r = 1; r <= resolutionMax; r++) { + SaveGridToDisk._log("# resolution %d", r); + + long x = System.currentTimeMillis(); + + ISEA3H g = new ISEA3H(r); + g.cellIDs(String.format("%s/grid-%d", path, r), GridCellIDType.NON_ADAPTIVE); + + SaveGridToDisk._log("computation: %d ms", System.currentTimeMillis() - x); + x = System.currentTimeMillis(); + + SaveGridToDisk._exec("echo \"# resolution %d\" >> result.txt", r); + SaveGridToDisk._exec("sort --numeric-sort --merge --batch-size=100000 grid-%d.* --unique | wc -l >> result.txt", r); + SaveGridToDisk._exec("for i in {0..19}; do sort --numeric-sort --merge --batch-size=100000 grid-%d.face$i.* | uniq -d | wc -l; done >> result.txt", r); + SaveGridToDisk._exec("rm grid-%d.*", r); + + SaveGridToDisk._log("evaluation: %d ms", System.currentTimeMillis() - x); + } + } + + private static void _log(String message, Object... args) throws IOException, InterruptedException { + System.out.format(message + "\n", args); + SaveGridToDisk._exec("echo \"%s\" >> result.log", String.format(message, args)); + } + + private static void _exec(String cmd, Object... args) throws IOException, InterruptedException { + ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", String.format(cmd, args)); + processBuilder.directory(new File(SaveGridToDisk.path)); + Process process = processBuilder.start(); + process.waitFor(); + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/generic/Trigonometric.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/generic/Trigonometric.java new file mode 100644 index 0000000000..b5df58b32f --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/generic/Trigonometric.java @@ -0,0 +1,49 @@ +/* + * 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.isea.generic; + +/** + * Trigonometric functions with degree instead of radians + * + * @author Franz-Benjamin Mocnik + */ +public class Trigonometric { + public static double sin(double x) { + return Math.sin(Math.toRadians(x)); + } + public static double cos(double x) { + return Math.cos(Math.toRadians(x)); + } + public static double tan(double x) { + return Math.tan(Math.toRadians(x)); + } + public static double cot(double x) { + return 1 / Trigonometric.tan(x); + } + public static double asin(double x) { + return Math.toDegrees(Math.asin(x)); + } + public static double acos(double x) { + return Math.toDegrees(Math.acos(x)); + } + public static double atan(double x) { + return Math.toDegrees(Math.atan(x)); + } + public static double atan2(double y, double x) { + return Math.toDegrees(Math.atan2(y, x)); + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/generic/Tuple.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/generic/Tuple.java new file mode 100644 index 0000000000..7ffa7a616e --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/generic/Tuple.java @@ -0,0 +1,37 @@ +/* + * 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.isea.generic; + +/** + * + * @author Franz-Benjamin Mocnik + */ +public class Tuple<T1, T2> { + public final T1 _1; + public final T2 _2; + + public Tuple(T1 arg1, T2 arg2){ + super(); + this._1 = arg1; + this._2 = arg2; + } + + @Override + public String toString() { + return String.format("(%s, %s)", this._1, this._2); + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/geo/WGS84.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/geo/WGS84.java new file mode 100644 index 0000000000..48a5e263c6 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/geo/WGS84.java @@ -0,0 +1,30 @@ +/* + * 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.isea.geo; + +/** + * Data about the World Geodetic System (WGS) 84 reference ellipsoid + * + * @author Franz-Benjamin Mocnik + */ +public class WGS84 { + public static final double semiMajorAxis = 6378.137; // [km] + public static final double inverseFlattening = 1 / 298.257223563; // [] + public static final double semiMinorAxis = (1 - inverseFlattening) * WGS84.semiMajorAxis; // [km] + public static final double radiusAuthalic = 6371.0071809184728409; // [km] + public static final double areaOfEarth = 510065621.72408837080; // [km^2] +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/geometry/FaceCoordinates.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/geometry/FaceCoordinates.java new file mode 100644 index 0000000000..963d275c2d --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/geometry/FaceCoordinates.java @@ -0,0 +1,54 @@ +/* + * 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.isea.geometry; + +/** + * Cartesian Coordinates of a location on a face of a platonic solid. + * + * @author Franz-Benjamin Mocnik + */ +public class FaceCoordinates { + private final Integer _face; + private final Double _x; + private final Double _y; + + public FaceCoordinates(Integer face, Double x, Double y) { + this._face = face; + this._x = x; + this._y = y; + } + + public Integer getFace() { + return this._face; + } + + public Double getX() { + return this._x; + } + + public Double getY() { + return this._y; + } + + public Double distanceTo(FaceCoordinates c) { + return Math.sqrt(Math.pow(this._x - c.getX(), 2) + Math.pow(this._y - c.getY(), 2)); + } + @Override + public String toString() { + return String.format("face %d x %f y %f", this._face, this._x, this._y); + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/geometry/GeoCoordinates.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/geometry/GeoCoordinates.java new file mode 100644 index 0000000000..87ae22de53 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/geometry/GeoCoordinates.java @@ -0,0 +1,63 @@ +/* + * 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.isea.geometry; + +import org.apache.sis.referencing.dggs.isea.generic.Trigonometric; +import org.apache.sis.referencing.dggs.isea.geo.WGS84; + +/** + * Geographic coordinates of a location on Earth. + * + * @author Franz-Benjamin Mocnik + */ +public class GeoCoordinates implements Comparable<GeoCoordinates> { + private final Double _lat; + private final Double _lon; + + public GeoCoordinates(Double lat, Double lon) throws Exception { + if (lat < -90 || lat > 90) throw new Exception("invalid latitude"); + lon %= 360; + if (lon > 180) lon -= 360; + else if (lon < -180) lon += 360; + this._lat = lat; + this._lon = lon; + } + + public Double getLat() { + return this._lat; + } + + public Double getLon() { + return this._lon; + } + + public Double distanceTo(GeoCoordinates other) { + return WGS84.radiusAuthalic * 2 * Math.asin(Math.sqrt(Math.pow(Trigonometric.sin((this.getLat() - other.getLat()) / 2), 2) + Math.pow(Trigonometric.sin((this.getLon() - other.getLon()) / 2), 2) * Trigonometric.cos(this.getLat()) * Trigonometric.cos(other.getLat()))); + } + + @Override + public String toString() { + return String.format("lat %f lon %f", this._lat, this._lon); + } + + @Override + public int compareTo(GeoCoordinates o) { + int d = Double.compare(this._lat, o._lat); + if (d != 0) return d; + return Double.compare(this._lon, o._lon); + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/grids/ISEA3H.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/grids/ISEA3H.java new file mode 100644 index 0000000000..e71b1f9e93 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/grids/ISEA3H.java @@ -0,0 +1,713 @@ +/* + * 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.isea.grids; + +import org.apache.sis.referencing.dggs.isea.cells.GridCell; +import org.apache.sis.referencing.dggs.isea.cells.GridCellIDType; +import org.apache.sis.referencing.dggs.isea.generic.Tuple; +import org.apache.sis.referencing.dggs.isea.geo.WGS84; +import org.apache.sis.referencing.dggs.isea.geometry.FaceCoordinates; +import org.apache.sis.referencing.dggs.isea.geometry.GeoCoordinates; +import org.apache.sis.referencing.dggs.isea.projections.ISEAProjection; +import org.locationtech.jts.geom.Coordinate; +import org.locationtech.jts.geom.Geometry; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +/** + * ISEA Aperture 3 Hexagon (ISEA3H) Discrete Global Grid System (DGGS) + * + * The ISEA3H grid is constructed by using the icosahedron Snyder equal-area (ISEA) projection to map the surface of the + * globe to the icosahedron. Thereby, the orientation of the icosahedron is chosen such that the north and the south + * poles are mapped to the edge midpoints of the icosahedron. The equator is thus mapped symmetrically. A grid + * (aperture 3) is constructed on the icosahedron, and this grid is mapped back by the inverse projection to the globe. + * + * The cells of the grid are identified by the resolution and their center points. + * + * The ISEA3H has been proposed by: + * + * Kevin Sahr, Denis White, and A. Jon Kimerling: Geodesic Discrete Global Grid Systems. Cartography and Geographic + * Information Science, 30(2), 121–134, 2003. doi:10.1559/152304003100011090 + * + * @author Franz-Benjamin Mocnik + */ +public class ISEA3H { + private static final double _precision = 1e-9; + private final ISEAProjection _projection = new ISEAProjection(); + private final int _resolution; // resolution + private final long _numberOfHexagonalCells; + private final int _numberOfPentagonalCells = 12; + private final double _l0; // length of the triangle base at resolution 1 + private final double _inverseSqrt3l0; // 1 / \sqrt{3} * l_0 + private final double _l; // length of the triangle base at the given resolution + private final double _l2; // l / 2 + private final double _l6; // l / 6 + private final double _l23; // l * 2 / 3 + private final double _inverseSqrt3 = 1 / Math.sqrt(3); // 1 / \sqrt{3} + private final double _inverseSqrt3l; // 1 / \sqrt{3} * l + private final double _inverseSqrt3l2; // 1 / (2 \sqrt{3}) * l + private final double _triangleA; // l_0 / 2 // half base + private final double _triangleB; // 1/\sqrt{3} * l_0 // distance center point to tip + private final double _triangleC; // 1/(2 \sqrt{3}) * l_0 // distance base to center point + private final double _triangleBCA; // (_triangleB + _triangleC) / _triangleA + private int _numberOfThreads = 8; + + public ISEA3H(int resolution) { + this(resolution, true); + } + + public ISEA3H(int resolution, boolean rotatedProjection) { + if (rotatedProjection) this._projection.setOrientationSymmetricEquator(); + this._resolution = resolution; + long numberOfHexagonalCells = 1; + for (int i = 1; i < this._resolution; i++) numberOfHexagonalCells = 3 * numberOfHexagonalCells + 1; + this._numberOfHexagonalCells = 20 * numberOfHexagonalCells; + this._l0 = this._projection.lengthOfTriangleBase(); + this._inverseSqrt3l0 = this._inverseSqrt3 * this._l0; + this._l = Math.pow(this._inverseSqrt3, this._resolution - 1) * this._l0; + this._l2 = this._l / 2.; + this._l6 = this._l / 6.; + this._l23 = this._l * 2 / 3.; + this._inverseSqrt3l = Math.pow(this._inverseSqrt3, this._resolution) * this._l0; + this._inverseSqrt3l2 = this._inverseSqrt3l / 2.; + this._triangleA = this._l0 / 2.; + this._triangleB = this._inverseSqrt3l0; + this._triangleC = this._inverseSqrt3l0 / 2.; + this._triangleBCA = (this._triangleB + this._triangleC) / this._triangleA; + } + + /** + * Get the resolution. + */ + public Integer getResolution() { + return this._resolution; + } + + /** + * Set the number of threads. + * + * By default, 8 threads are used. + * + * @param n + */ + public void setNumberOfThreads(int n) { + this._numberOfThreads = n; + } + + /** + * Get the number of threads. + * + * @return + */ + public int getNumberOfThreads() { + return this._numberOfThreads; + } + + /** + * @return diameter of a hexagonal cell on the icosahedron, in kilometres + */ + public double diameterOfHexagonalCellOnIcosahedron() { + return this._l23; + } + + /** + * @return length of a side of a hexagonal cell on the icosahedron, in kilometres + */ + public double lengthOfASideOfHexagonalCellOnIcosahedron() { + return this._l / 3; + } + + /** + * @return lower bound for the length of a side of a hexagonal cell on the sphere, in kilometres + */ + public double lowerBoundForLengthOfASideOfHexagonalCellOnSphere() { + return this._projection.sphericalDistanceFromCenterToVerticesOnSphere() * WGS84.radiusAuthalic * 2 * Math.PI / (360 * Math.sqrt(Math.pow(3, this._resolution - 1) * 5)); + } + + /** + * Returns the area of a hexagonal cell. The cells should all have the same area by construction, because the ISEA + * projection is equal-area. + * + * @return area of a hexagonal cell, in square kilometres + */ + public double areaOfAHexagonalCell() { + return WGS84.areaOfEarth / (this._numberOfHexagonalCells + 5 / 6. * this._numberOfPentagonalCells); + } + + /** + * Returns the area of a pentagonal cell. The cells should all have the same area by construction, because the ISEA + * projection is equal-area. + * + * @return area of a pentagonal cell, in in kilometres + */ + public double areaOfAPentagonalCell() { + return 5 / 6. * this.areaOfAHexagonalCell(); + } + + /** + * @return number of hexagonal cells + */ + public long numberOfHexagonalCells() { + return this._numberOfHexagonalCells; + } + + /** + * @return number of pentagonal cells + */ + public int numberOfPentagonalCells() { + return this._numberOfPentagonalCells; + } + + /** + * Returns the grid cell for a given location + * + * @param lat latitude + * @param lon longitude + * @return corresponding grid cell + * @throws Exception + */ + public GridCell cellForLocation(double lat, double lon) throws Exception { + return this.cellForLocation(new GeoCoordinates(lat, lon)); + } + + /** + * Returns the grid cell for a given location + * + * @param c geographic coordinates + * @return corresponding grid cell + * @throws Exception + */ + public GridCell cellForLocation(GeoCoordinates c) throws Exception { + FaceCoordinates fc = this.cellForLocation(this._projection.sphereToIcosahedron(c)); + return this._newGridCell(this._projection.icosahedronToSphere(fc), fc); + } + + /** + * Returns the coordinates of the center of the corresponding grid cell for given coordinates in the face + * + * @param c face coordinates + * @return face coordinates of the center of the corresponding grid cell + * @throws Exception + */ + public FaceCoordinates cellForLocation(FaceCoordinates c) { + double x = (this._coordinatesNotSwapped()) ? c.getX() : c.getY(); + double y = (this._coordinatesNotSwapped()) ? c.getY() : c.getX(); + int nxCenter = (int) Math.round(x / this._l2); + double xCenter = nxCenter * this._l2; + if (Math.abs(x - xCenter) <= this._l6) { + int nyCenter12 = (int) Math.round(((nxCenter % 2 == 0) ? y : y - this._inverseSqrt3l2) / this._inverseSqrt3l); + double yCenter12 = nyCenter12 * this._inverseSqrt3l + ((nxCenter % 2 == 0) ? 0 : this._inverseSqrt3l2); + return this._faceCoordinatesSwapByResolution(c.getFace(), xCenter, yCenter12); + } else { + int nyCenter1 = (int) Math.round(y / this._inverseSqrt3l); + double yCenter1 = nyCenter1 * this._inverseSqrt3l; + int nyCenter2 = (int) Math.round((y - this._inverseSqrt3l2) / this._inverseSqrt3l); + double yCenter2 = nyCenter2 * this._inverseSqrt3l + this._inverseSqrt3l2; + FaceCoordinates cCandidate1 = this._faceCoordinatesSwapByResolution(c.getFace(), xCenter, (nxCenter % 2 == 0) ? yCenter1 : yCenter2); + FaceCoordinates cCandidate2 = this._faceCoordinatesSwapByResolution(c.getFace(), (x > xCenter) ? xCenter + this._l2 : xCenter - this._l2, (nxCenter % 2 != 0) ? yCenter1 : yCenter2); + return (c.distanceTo(cCandidate1) < c.distanceTo(cCandidate2)) ? cCandidate1 : cCandidate2; + } + } + + /** + * The following equality holds: cellForLocation = _getCoordinatesOfCenter . _integerForFaceCoordinates + * + * However, the method cellForLocation is defined separately to speed up computations. + * + * @param face face to compute the coordinates on + * @param nx steps into the direction of the vertex of the hexagon + * @param ny steps into the direction of the edge of the hexagon + * @return coordinates on the face + */ + private FaceCoordinates _getCoordinatesOfCenter(int face, int nx, int ny) { + double x = nx * this._l2; + double y = (ny + ((nx % 2 == 0) ? 0 : .5)) * this._inverseSqrt3l; + return this._faceCoordinatesSwapByResolution(face, x, y); + } + + private FaceCoordinates _getCoordinatesOfCenter2(int face, int nx, int ny, int orientation) { + double x = nx * this._l2; + double y = (ny - orientation * ((nx % 2 == 0) ? 0 : .5)) * this._inverseSqrt3l; + return this._faceCoordinatesSwapByResolution(face, x, y); + } + + private Tuple<Integer, Integer> _integerForFaceCoordinates(FaceCoordinates c) { + double x = (this._coordinatesNotSwapped()) ? c.getX() : c.getY(); + double y = (this._coordinatesNotSwapped()) ? c.getY() : c.getX(); + int nxCenter = (int) Math.round(x / this._l2); + double xCenter = nxCenter * this._l2; + if (Math.abs(x - xCenter) <= this._l6) return new Tuple(nxCenter, (int) Math.round(((nxCenter % 2 == 0) ? y : y - this._inverseSqrt3l2) / this._inverseSqrt3l)); + else { + int nyCenter1 = (int) Math.round(y / this._inverseSqrt3l); + double yCenter1 = nyCenter1 * this._inverseSqrt3l; + int nyCenter2 = (int) Math.round((y - this._inverseSqrt3l2) / this._inverseSqrt3l); + double yCenter2 = nyCenter2 * this._inverseSqrt3l + this._inverseSqrt3l2; + FaceCoordinates cCandidate1 = this._faceCoordinatesSwapByResolution(c.getFace(), xCenter, (nxCenter % 2 == 0) ? yCenter1 : yCenter2); + FaceCoordinates cCandidate2 = this._faceCoordinatesSwapByResolution(c.getFace(), (x > xCenter) ? xCenter + this._l2 : xCenter - this._l2, (nxCenter % 2 != 0) ? yCenter1 : yCenter2); + return (c.distanceTo(cCandidate1) < c.distanceTo(cCandidate2)) ? new Tuple(nxCenter, (nxCenter % 2 == 0) ? nyCenter1 : nyCenter2) : new Tuple((x > xCenter) ? nxCenter + 1 : nxCenter - 1, (nxCenter % 2 != 0) ? nyCenter1 : nyCenter2); + } + } + + /** + * Returns the grid cell for the centroid of a given geometry + * + * @param g geometry + * @return corresponding grid cell + * @throws Exception + */ + public GridCell cellForCentroid(Geometry g) throws Exception { + Coordinate c = g.getCentroid().getCoordinate(); + return this.cellForLocation(c.y, c.x); + } + + /** + * Returns all cells. + * + * @return cells + */ + public Collection<GridCell> cells() throws Exception { + return this.cellsForBound(-90, 90, -180, 180); + } + + /** + * Returns cell IDs. + * + * Same as cells, apart that this method returns only IDs and is much more memory efficient. + * + * @return IDs of cells + */ + public Collection<Long> cellIDs() throws Exception { + return this.cellIDs(GridCellIDType.NON_ADAPTIVE); + } + public Collection<Long> cellIDs(GridCellIDType gridCellIDType) throws Exception { + return this.cellIDsForBound(-90, 90, -180, 180, gridCellIDType); + } + + /** + * Save cell IDs to disk. + * + * For each face, one file is created. The cell IDs in the different files are not unique and non-unique IDs need to + * be removed. + * + * @param file prefix of the files + * @return IDs of cells + */ + public void cellIDs(String file) throws Exception { + this.cellIDs(file, GridCellIDType.NON_ADAPTIVE); + } + public void cellIDs(String file, GridCellIDType gridCellIDType) throws Exception { + this._cells(new CellAggregatorByCellIDsToFile(file, gridCellIDType)).closeFile(); + } + + /** + * Returns cells that are inside the bounds, or at least very near. + * + * Note that the result should, in fact, include all cells whose center points are inside the given bounds, but also + * cells nearby. Observe that it can, however, not be guaranteed that all such cells are returned if the longitude + * range is less than 360 degrees or the latitude range is less than 180 degrees. + * + * @param lat0 + * @param lat1 + * @param lon0 + * @param lon1 + * @return cells inside the bounds + */ + public Collection<GridCell> cellsForBound(double lat0, double lat1, double lon0, double lon1) throws Exception { + if (lat1 - lat0 >= 180 && lon1 - lon0 >= 360) return this._cells(new CellAggregatorByCells()).getCells(); + else return this._cellsForBound(new CellAggregatorByCells(), lat0, lat1, lon0, lon1).cellAggregator.getCells(); + } + + /** + * Returns cell IDs that are inside the bounds, or at least very near. + * + * Same as cellsForBound, apart that this method returns only IDs and is much more memory efficient. + * + * @param lat0 + * @param lat1 + * @param lon0 + * @param lon1 + * @return IDs of cells inside the bounds + */ + public Collection<Long> cellIDsForBound(double lat0, double lat1, double lon0, double lon1) throws Exception { + return this.cellIDsForBound(lat0, lat1, lon0, lon1, GridCellIDType.NON_ADAPTIVE); + } + public Collection<Long> cellIDsForBound(double lat0, double lat1, double lon0, double lon1, GridCellIDType gridCellIDType) throws Exception { + if (lat1 - lat0 >= 180 && lon1 - lon0 >= 360) return this._cells(new CellAggregatorByCellIDs(gridCellIDType)).getCellIDs(); + else return this._cellsForBound(new CellAggregatorByCellIDs(gridCellIDType), lat0, lat1, lon0, lon1).cellAggregator.getCellIDs(); + } + + private <T extends CellAggregator> ResultCellForBound<T> _cellsForBound(T ca, double lat0, double lat1, double lon0, double lon1) throws Exception { + // compute center of bounding box + double lat = (lat0 + lat1) / 2.; + double lon = (lon0 + lon1 + ((lon0 <= lon1) ? 0 : 360)) / 2.; + if (lon > 360) lon -= 360; + FaceCoordinates fc = this._projection.sphereToIcosahedron(new GeoCoordinates(lat, lon)); + // compute + return _cellsForBound(new ResultCellForBound<>(ca), fc, lat0, lat1, lon0, lon1); + } + + private <T extends CellAggregator> T _cells(T ca) throws Exception { + ISEA3H t = this; + ExecutorService executor = Executors.newFixedThreadPool(this._numberOfThreads); + List<Future<T>> futureList = new ArrayList<>(); + for (int face = 0; face < this._projection.numberOfFaces(); face++) { + final int f = face; + futureList.add(executor.submit(new Callable<T>() { + public T call() throws Exception { + return t._cellsForFace(new ResultCellForBound<T>((T) ca.cloneEmpty()), f).cellAggregator; + } + })); + } + for (Future<T> future : futureList) ca.addAll(future.get()); + executor.shutdown(); + return ca; + } + + private <T extends CellAggregator> ResultCellForBound<T> _cellsForBound(ResultCellForBound<T> result, FaceCoordinates fcStart, double lat0, double lat1, double lon0, double lon1) throws Exception { + // if fcStart is already in result, skip the computation + if (result.visitedCells.contains(fcStart.getFace())) return result; + result.visitedCells.add(fcStart.getFace()); + + // prepare dNs + List<Tuple<Integer, Integer>> dNs = new ArrayList<>(); + dNs.add(new Tuple(1, 1)); + dNs.add(new Tuple(-1, 1)); + dNs.add(new Tuple(1, -1)); + dNs.add(new Tuple(-1, -1)); + + // compute starting coordinates + Tuple<Integer, Integer> fcn = this._integerForFaceCoordinates(fcStart); + if (!this._isCoordinatesInFace(this._getCoordinatesOfCenter(fcStart.getFace(), fcn._1, fcn._2))) { + if (this._isCoordinatesInFace(this._getCoordinatesOfCenter(fcStart.getFace(), fcn._1 - 1, fcn._2))) fcn = new Tuple(fcn._1 - 1, fcn._2); + else if (this._isCoordinatesInFace(this._getCoordinatesOfCenter(fcStart.getFace(), fcn._1 + 1, fcn._2))) fcn = new Tuple(fcn._1 + 1, fcn._2); + else if (this._isCoordinatesInFace(this._getCoordinatesOfCenter(fcStart.getFace(), fcn._1, fcn._2 - 1))) fcn = new Tuple(fcn._1, fcn._2 - 1); + else if (this._isCoordinatesInFace(this._getCoordinatesOfCenter(fcStart.getFace(), fcn._1, fcn._2 + 1))) fcn = new Tuple(fcn._1, fcn._2 + 1); + else if (this._isCoordinatesInFace(this._getCoordinatesOfCenter(fcStart.getFace(), fcn._1 - 1, fcn._2 - 1))) fcn = new Tuple(fcn._1 -1, fcn._2 - 1); + else if (this._isCoordinatesInFace(this._getCoordinatesOfCenter(fcStart.getFace(), fcn._1 + 1, fcn._2 - 1))) fcn = new Tuple(fcn._1 + 1, fcn._2 - 1); + else if (this._isCoordinatesInFace(this._getCoordinatesOfCenter(fcStart.getFace(), fcn._1 - 1, fcn._2 + 1))) fcn = new Tuple(fcn._1 - 1, fcn._2 + 1); + else if (this._isCoordinatesInFace(this._getCoordinatesOfCenter(fcStart.getFace(), fcn._1 + 1, fcn._2 + 1))) fcn = new Tuple(fcn._1 + 1, fcn._2 + 1); + } + + // collect cells + int face = fcStart.getFace(); + for (Tuple<Integer, Integer> dN : dNs) { + FaceCoordinates fc; + GeoCoordinates gc; + Set<Integer> success = new HashSet(); + Set<Integer> successLast; + boolean hasFoundInside; + boolean hasFoundOutsideX = false; + boolean hasFoundOutsideY = false; + Map<Integer, FaceCoordinates> faceTodo = new HashMap(); + int nx = fcn._1 - dN._1 + ((dN._1 < 0) ? dN._1 : 0); + while (true) { + nx += dN._1; + int ny = fcn._2 - dN._2; + successLast = success; + Integer maxMinValue = (!successLast.isEmpty()) ? ((dN._2 >= 0) ? Collections.max(successLast) : Collections.min(successLast)) : null; + success = new HashSet<>(); + hasFoundInside = false; + while (true) { + ny += dN._2; + fc = this._getCoordinatesOfCenter(face, nx, ny); + gc = this._projection.icosahedronToSphere(fc); + if (this._isInside(gc, lat0, lat1, lon0, lon1)) hasFoundInside = true; + else if (hasFoundInside || maxMinValue == null || ((dN._2 >= 0) ? ny > maxMinValue : ny < maxMinValue)) break; + else continue; + if (this._isCoordinatesInFace(fc)) { + success.add(ny); + result.cellAggregator.add(face, this._newGridCell(gc, fc)); + } else { + if ((!hasFoundOutsideX && ny != fcn._2) || (!hasFoundOutsideY && ny == fcn._2)) { + if (ny != fcn._2) hasFoundOutsideX = true; + else hasFoundOutsideY = true; + FaceCoordinates fc2 = this._projection.sphereToIcosahedron(gc); + if (faceTodo.containsKey(fc2.getFace())) faceTodo.put(fc2.getFace(), fc2); + else { + int sizeBefore = result.cellAggregator.size(); + result = this._cellsForBound(result, fc2, lat0, lat1, lon0, lon1); + if (result.cellAggregator.size() != sizeBefore) faceTodo.put(fc2.getFace(), null); + } + } + if (!success.isEmpty()) break; + } + } + if (success.isEmpty()) break; + } + for (Map.Entry<Integer, FaceCoordinates> e : faceTodo.entrySet()) if (e.getValue() != null && !result.cellAggregator.contains(this.cellForLocation(this._projection.icosahedronToSphere(e.getValue())))) result = this._cellsForBound(result, e.getValue(), lat0, lat1, lon0, lon1); + } + + return result; + } + + private <T extends CellAggregator> ResultCellForBound<T> _cellsForFace(ResultCellForBound<T> result, int face) throws Exception { + int d = this._projection.faceOrientation(face); + boolean notSwapped = (this._coordinatesNotSwapped()); + + // compute + FaceCoordinates fc; + GeoCoordinates gc; + int nyMax = (int) Math.round((notSwapped ? Math.pow(3, (this._resolution - 1) / 2.) : 2 * Math.pow(3, (this._resolution - 2) / 2.))); + int nyMin = -(int) (notSwapped ? (nyMax - 1) / 2. : nyMax / 2.); + int nxMin = 0; + int nxMax = 0; + int counter = 0; + for (int ny = nyMax; ny >= nyMin; ny--) { + if (notSwapped) { + if (counter == 1) { + nxMax++; + nxMin = -nxMax; + } + if (counter == 3) { + nxMax++; + nxMin = -nxMax; + counter = 0; + } + counter++; + } else { + nxMin = (d > 0) ? -(int)Math.floor((nyMax - ny) / 2.) : -(int)Math.ceil((nyMax - ny) / 2.); + nxMax = (d > 0) ? (int)Math.ceil((nyMax - ny) / 2.) : (int)Math.floor((nyMax - ny) / 2.); + } + for (int nx = nxMin; nx <= nxMax; nx++) { + fc = this._getCoordinatesOfCenter2(face, notSwapped ? nx : d * ny, notSwapped ? d * ny : nx, d); + gc = this._projection.icosahedronToSphere(fc); + result.cellAggregator.add(face, this._newGridCell(gc, fc)); + } + } + + return result; + } + + private class ResultCellForBound<T extends CellAggregator> { + public final T cellAggregator; + public final Set<Integer> visitedCells = new HashSet(); + + public ResultCellForBound(T cellAggregator) { + this.cellAggregator = cellAggregator; + } + } + + private interface CellAggregator<T> { + public abstract CellAggregator<T> cloneEmpty(); + public abstract void add(int face, GridCell c) throws Exception; + public abstract void addAll(T ca); + public abstract int size(); + public abstract boolean contains(GridCell c); + } + + private class CellAggregatorByCells implements CellAggregator<CellAggregatorByCells> { + private Set<GridCell> _cells = new HashSet(); + + @Override + public CellAggregator<CellAggregatorByCells> cloneEmpty() { + return new CellAggregatorByCells(); + } + + @Override + public void add(int face, GridCell c) { + this._cells.add(c); + } + + @Override + public void addAll(CellAggregatorByCells ca) { + this._cells.addAll(ca.getCells()); + } + + @Override + public int size() { + return this._cells.size(); + } + + @Override + public boolean contains(GridCell c) { + return this._cells.contains(c); + } + + public Set<GridCell> getCells() { + return this._cells; + } + } + + private class CellAggregatorByCellIDs implements CellAggregator<CellAggregatorByCellIDs> { + private Set<Long> _cells = new HashSet(); + private GridCellIDType _gridCellIDType; + + public CellAggregatorByCellIDs(GridCellIDType gridCellIDType) { + this._gridCellIDType = gridCellIDType; + } + + @Override + public CellAggregator<CellAggregatorByCellIDs> cloneEmpty() { + return new CellAggregatorByCellIDs(this._gridCellIDType); + } + + @Override + public void add(int face, GridCell c) { + this._cells.add(c.getID(this._gridCellIDType)); + } + + @Override + public void addAll(CellAggregatorByCellIDs ca) { + this._cells.addAll(ca.getCellIDs()); + } + + @Override + public int size() { + return this._cells.size(); + } + + @Override + public boolean contains(GridCell c) { + return this._cells.contains(c.getID(this._gridCellIDType)); + } + + public Set<Long> getCellIDs() { + return this._cells; + } + } + + private class CellAggregatorByCellIDsToFile implements CellAggregator<CellAggregatorByCellIDsToFile> { + private ArrayList<Long> _cells = new ArrayList<>(); + private List<CellAggregatorByCellIDsToFile> _caList = new ArrayList(); + private final String _filename; + private GridCellIDType _gridCellIDType; + private Integer _face = null; + private int _chunk = 0; + private static final int _chunkSize = 10000000; + + public CellAggregatorByCellIDsToFile(String filename, GridCellIDType gridCellIDType) { + this._filename = filename; + this._gridCellIDType = gridCellIDType; + } + + @Override + public CellAggregator<CellAggregatorByCellIDsToFile> cloneEmpty() { + return new CellAggregatorByCellIDsToFile(this._filename, this._gridCellIDType); + } + + @Override + public void add(int face, GridCell c) throws IOException { + this._face = face; + this._cells.add(c.getID(this._gridCellIDType)); + if (this._cells.size() >= this._chunkSize) this._writeChunkToFile(); + } + + @Override + public void addAll(CellAggregatorByCellIDsToFile ca) { + this._caList.add(ca); + } + + @Override + public int size() { + return 0; + } + + @Override + public boolean contains(GridCell c) { + return false; + } + + private void _writeChunkToFile() throws IOException { + Collections.sort(this._cells); + File file = new File(this._filename + ".face" + this._face + "." + this._chunk); + try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file))){ + for (Long a : this._cells) { + bufferedWriter.append(a.toString()); + bufferedWriter.newLine(); + } + } + this._chunk++; + this._cells = new ArrayList<>(); + } + + public void closeFile() throws IOException { + if (this._cells.size() > 0) this._writeChunkToFile(); + for (CellAggregatorByCellIDsToFile ca : this._caList) ca.closeFile(); + } + } + + private boolean _isInside(GeoCoordinates c, double lat0, double lat1, double lon0, double lon1) { + boolean bLat = lat0 <= c.getLat() && c.getLat() <= lat1; + boolean bLon = (lon0 <= lon1) ? lon0 <= c.getLon() && c.getLon() <= lon1 : lon0 < c.getLon() || c.getLon() < lon1; + return bLat && bLon; + } + + private GridCell _newGridCell(GeoCoordinates gc, FaceCoordinates fc) throws Exception { + int d = this._projection.faceOrientation(fc); + boolean isPentagon = (Math.abs(Math.abs(fc.getX()) - this._triangleA) < ISEA3H._precision && Math.abs(fc.getY() + d * this._triangleC) < ISEA3H._precision) || (Math.abs(fc.getX()) < ISEA3H._precision && Math.abs(fc.getY() - d * this._triangleB) < ISEA3H._precision); + return new GridCell(this._resolution, gc, isPentagon); + } + + /** + * Returns a buffer for a bounding box of geographic coordinates that needs to be considered in order to ensure + * that all grid cells, whose center point is within the given bounding box, are contained in the bounding box or + * the buffer + * + * @param lat0 + * @param lat1 + * @param lon0 + * @param lon1 + * @return buffer + * @throws Exception + */ + public Double bufferEstimator(double lat0, double lat1, double lon0, double lon1) throws Exception { + lat0 = Math.max(lat0, -90); + lat1 = Math.min(lat1, 90); + if (lon1 - lon0 >= 360) { + lon0 = -180; + lon1 = 180; + } + FaceCoordinates southWest = this._projection.sphereToIcosahedron(new GeoCoordinates(lat0, lon0)); + FaceCoordinates northEast = this._projection.sphereToIcosahedron(new GeoCoordinates(lat1, lon1)); + GeoCoordinates southWest2 = this._projection.icosahedronToSphere(new FaceCoordinates(southWest.getFace(), southWest.getX() - this.diameterOfHexagonalCellOnIcosahedron() / 2, southWest.getY() - this.diameterOfHexagonalCellOnIcosahedron() / 2)); + GeoCoordinates northEast2 = this._projection.icosahedronToSphere(new FaceCoordinates(northEast.getFace(), northEast.getX() - this.diameterOfHexagonalCellOnIcosahedron() / 2, northEast.getY() - this.diameterOfHexagonalCellOnIcosahedron() / 2)); + List<Double> l = new ArrayList<>(); + l.add(Math.abs(southWest2.getLat() - lat0)); + l.add(Math.abs(southWest2.getLon() - lon0)); + l.add(Math.abs(northEast2.getLat() - lat1)); + l.add(Math.abs(northEast2.getLon() - lon1)); + Optional<Double> result = l.stream().max(Double::compareTo); + return (result.isPresent()) ? result.get() : null; + } + + private boolean _isCoordinatesInFace(FaceCoordinates c) { + int d = this._projection.faceOrientation(c); + + // test whether coordinate is left of the triangle, right of the triangle, or below the triangle + if (d * c.getY() > c.getX() * this._triangleBCA + this._triangleB + ISEA3H._precision) return false; + if (d * c.getY() > -c.getX() * this._triangleBCA + this._triangleB + ISEA3H._precision) return false; + if (d * c.getY() < -this._triangleC - ISEA3H._precision) return false; + + return true; + } + + private FaceCoordinates _faceCoordinatesSwapByResolution(int face, double x, double y) { + return new FaceCoordinates(face, this._coordinatesNotSwapped() ? x : y, this._coordinatesNotSwapped() ? y : x); + } + + private boolean _coordinatesNotSwapped() { + return this._resolution % 2 != 0; + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/package-info.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/package-info.java new file mode 100644 index 0000000000..484dd04e1a --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/package-info.java @@ -0,0 +1,279 @@ +/* + * 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. + */ + +/** + * + * <h2>Origin</h2> + * ISEA package takes it's origin from the Geogrid project. + * https://github.com/mocnik-science/geogrid + * + * Provides methods to generate and handle the ISEA Aperture 3 Hexagon Discrete Global Grid System + * (ISEA3H DGGS) using the Inverse Snyder Equal-Area Projection (ISEA) in dual license MIT and Apache 2. + * + * <h2>Scientific Publications</h2> + * + * <p>An overview of the ISEA3H DGGS and the identifier scheme used in this library can be found in:</p> + * <ul> + * <li>F-B Mocnik: <a href="http://doi.org/10.1080/15230406.2018.1455157"><b>A Novel Identifier Scheme for the + * ISEA Aperture 3 Hexagon Discrete Global Grid System.</b></a> Cartography and Geographic Information + * Science 46(3), 2019, 227–291</li> + * </ul> + * + * <p>The ISEA3H has originally been proposed by:</p> + * <ul> + * <li>K Sahr, D White, and AJ Kimerling: <a href="http://doi.org/10.1559/152304003100011090"><b>Geodesic + * Discrete Global Grid Systems</b></a>. Cartography and Geographic Information Science, 30(2), 2003, + * 121–134. doi:10.1559/152304003100011090</li> + * </ul> + * + * <p>The projection has been proposed and has been described in detail by:</p> + * <ul> + * <li>JP Snyder: <a href="http://doi.org/10.3138/27H7-8K88-4882-1752"><b>An equal-area map projection for + * polyhedral globes</b></a>. Cartographica, 29(1), 1992, 10–21. + * doi:10.3138/27H7-8K88-4882-1752</li> + * </ul> + * + * <h2>Short Overview</h2> + * + * <h3>ISEA Projection</h3> + * + * <p>The ISEA projection maps the regular icosahedron to the sphere. A hexagonal grid introduced on the + * icosahedron can thus be mapped to the sphere as well. As the ISEA projection and the ISEA3H grid are thus + * strongly interlinked, this library offers an implementation of both, the ISEA projection and the ISEA3H + * grid.</p> + * + * <p>A location on the icosahedron can be mapped to the sphere, as in the following example of the coordinate + * {@code (20.3, 12.5)} on face {@code 2}:</p> + * + * <pre>{@code + * ISEAProjection projection = new ISEAProjection(); + * GeoCoordinates c = projection.icosahedronToSphere(new FaceCoordinates(2, 20.3, 12.5)); + * c.getLat(); // 52.739063 + * c.getLon(); // 0.315051 + * }</pre> + * + * <p>The resulting geographic coordinates can be projected back to the icosahedron:</p> + * + * <pre>{@code + * FaceCoordinates c2 = projection.sphereToIcosahedron(c); + * c2.getFace(); // 2 + * c2.getX(); // 20.3 + * c2.getY(); // 12.5 + * }</pre> + * + * <h3>ISEA3H DGGS: Determining the Cell for a Given Location</h3> + * + * <p>When the grid cell containing a given location should be determined, the method + * {@code cellForLocation} can be used, either for a pair of coordinates, or an instance of + * {@code GeoCoordinates}:</p> + * + * <pre>{@code + * GridCell gc1 = grid.cellForLocation(41.5, 6.5); + * GridCell gc2 = grid.cellForLocation(new GeoCoordinates(41.5, 6.5)); + * }</pre> + * + * <p>The cell containing the centroid of a {@code Geometry} (from the + * <a href="https://github.com/locationtech/jts">JTS Topology Suite</a>) can be determined accordingly:</p> + * + * <pre>{@code + * grid.cellForCentroid(g); + * }</pre> + * + * <h3>ISEA3H DGGS: Computing the Cells</h3> + * + * <p>The grid cells of the ISEA3H for a given boundary box can easily be computed as follows:</p> + * + * <pre>{@code + * ISEA3H grid = new ISEA3H(10); + * Collection<GridCell> cells = grid.cellsForBound(41, 42, 6, 7); + * }</pre> + * + * <p>Observe that the constructor of the class {@code ISEA3H} accepts the grid resolution as a parameter. The + * method {@code cellsForBound} computes, in this case, all cells that are (about) contained in the area between + * {@code 41} and {@code 42} degree latitude and {@code 6} and {@code 7} degree longitude. If all cells should be + * computed, the method {@code cells} can be used instead:</p> + * + * <pre>{@code + * Collection<GridCell> cellsAll = grid.cells(); + * }</pre> + * + * <p>The resulting collection of cells contains instances of {@code GridCell}. Such an instance contains + * information about the centroid of the grid cell, the grid resolution, whether it is a hexagon (or a pentagon) + * cell, and an identifier (ID):</p> + * + * <pre>{@code + * for (GridCell gc : cells) { + * gc.getLat(); + * gc.getLon(); + * gc.getResolution(); + * gc.isPentagon(); + * gc.getID(); + * } + * }</pre> + * + * <p>Different types of cell IDs can be used:</p> + * + * <table> + * <caption>Types of cell IDs</caption> + * <tr><th>Type of ID</th><th>Description</th><th>Typical use</th></tr> + * <tr><td>{@code NON_ADAPTIVE}</td> + * <td><i>Non-adaptive IDs</i> include the geometry of the cell in a high precision.</td> + * <td>Perfect rendering of the grid cells</td></tr> + * <tr><td>{@code ADAPTIVE_1_PERCENT}</td> + * <td><i>Adaptive 1% IDs</i> include the geometry in a scale dependent but yet reasonable precision.</td> + * <td>Rendering of the grid cells on a website</td></tr> + * <tr><td>{@code ADAPTIVE_UNIQUE}</td> + * <td><i>Adaptive unique IDs</i> aim at being as short as possible while preserving uniqueness.</td> + * <td>Comparison of whether two cells are identical</td></tr> + * </table> + * + * <p>Further information can be found in:</p> + * <ul> + * <li>F-B Mocnik: <a href="http://doi.org/10.1080/15230406.2018.1455157"><b>A Novel Identifier Scheme for the + * ISEA Aperture 3 Hexagon Discrete Global Grid System.</b></a> Cartography and Geographic Information + * Science 46(3), 2019, 227–291</li> + * </ul> + * + * <p>By default, non-adaptive IDs are returned. The type of ID can though be inserted explicitly as follows:</p> + * + * <pre>{@code + * gc.getID(NON_ADAPTIVE); + * gc.getID(ADAPTIVE_1_PERCENT); + * gc.getID(ADAPTIVE_UNIQUE); + * }</pre> + * + * <h3>ISEA3H DGGS: Computing Cell IDs Only</h3> + * + * <p>In case that just the identifiers (IDs) of the cells should be computed, two more efficient methods can be + * used:</p> + * + * <pre>{@code + * ISEA3H grid = new ISEA3H(10); + * Collection<Long> cells = grid.cellIDsForBound(41, 42, 6, 7); + * Collection<Long> cells2 = grid.cellIDsForBound(41, 42, 6, 7, ADAPTIVE_UNIQUE); + * Collection<Long> cellsAll = grid.cellIDs(); + * Collection<Long> cellsAll2 = grid.cellIDs(ADAPTIVE_UNIQUE); + * }</pre> + * + * <p>The IDs can even be saved to the hard disc:</p> + * + * <pre>{@code + * ISEA3H grid = new ISEA3H(10); + * grid.cellIDs("path/filename"); + * grid.cellIDs("path/filename2", ADAPTIVE_UNIQUE); + * }</pre> + * + * <p>Each of the created files contains only IDs that refer to one face of the icosahedron, and the data is + * divided into a number of chunks. The same ID can occur multiple times (for different faces) when it refers to + * a cell that is partially contained in different faces. The files are named as {@code filename.face.chunk_number}. + * The first part of this name refers to the filename provided in the method {@code cellIDs}; the second part, to + * the face to which the IDs contained in the file belong to; and the third part consists of consecutive numbers + * to distinguish the chunks.</p> + * + * <h2>ISEA Projection</h2> + * + * <h3>Properties</h3> + * + * <p>Many properties of the ISEA projection are provided by an instance of the {@code ISEAProjection}. The + * following table provides an overview over some of them:</p> + * + * <table> + * <caption>Properties of the ISEA projection</caption> + * <tr><th>Function</th><th>Description</th></tr> + * <tr><td>{@code numberOfFaces()}</td><td>Number of faces of the icosahedron</td></tr> + * <tr><td>{@code maximumAngularDistortion()}</td><td>Maximum angular distortion</td></tr> + * <tr><td>{@code maximumScaleVariation()}</td><td>Maximum scale variation</td></tr> + * <tr><td>{@code miniumScaleVariation()}</td><td>Minimum scale variation</td></tr> + * <tr><td>{@code lengthOfTriangleBase()}</td><td>Length of the bases of the triangles of the icosahedron</td></tr> + * <tr><td>{@code sphericalDistanceFromCenterToVerticesOnSphere()}</td> + * <td>Spherical distance from center of a face to any of its vertices on the sphere; in degrees</td></tr> + * </table> + * + * <h3>Orientation</h3> + * + * <p>The ISEA projection maps from the icosahedron to the sphere. By default, two of the vertices of the faces of + * the icosahedron are mapped to the poles. Another orientation might, however, be useful in many cases, as, for + * example, in the case of the ISEA3H DGGS: distortions are especially large at the vertices of the faces, and one + * aims at mapping the vertices to places that are within the oceans. Such an ‘ideal’ choice of an orientation can + * be reached by:</p> + * + * <pre>{@code + * ISEAProjection projection = new ISEAProjection(); + * projection.setOrientationSymmetricEquator(); + * }</pre> + * + * <p>If the orientation is to be set manually by shifting the orientation relative to the standard orientation + * (two of the vertices are mapped to the poles), the following method shifts every location by the angle + * {@code orientationLon} in the direction of positive longitude, and thereafter by the angle {@code orientationLat} + * in direction of positive latitude:</p> + * + * <pre>{@code + * projection.setOrientation(orientationLat, orientationLon); + * }</pre> + * + * <h2>ISEA3H DGGS</h2> + * + * <h3>Properties</h3> + * + * <p>Many properties of the ISEA3H DGGS are provided by an instance of the {@code ISEA3H}. The following table + * provides an overview over some of them:</p> + * + * <table> + * <caption>Properties of the ISEA3H DGGS</caption> + * <tr><th>Function</th><th>Description</th></tr> + * <tr><td>{@code diameterOfHexagonalCellOnIcosahedron()}</td> + * <td>Diameter of a hexagonal cell on the icosahedron, in kilometres</td></tr> + * <tr><td>{@code lengthOfASideOfHexagonalCellOnIcosahedron()}</td> + * <td>Length of a side of a hexagonal cell on the icosahedron, in kilometres</td></tr> + * <tr><td>{@code lowerBoundForLengthOfASideOfHexagonalCellOnSphere()}</td> + * <td>Lower bound for the length of a side of a hexagonal cell on the sphere, in kilometres</td></tr> + * <tr><td>{@code areaOfAHexagonalCell()}</td> + * <td>Area of a hexagonal cell; the cells have all the same area by construction, because the ISEA + * projection is equal-area, in square kilometres</td></tr> + * <tr><td>{@code areaOfAPentagonalCell()}</td> + * <td>Area of a pentagonal cell; the cells have all the same area by construction, because the ISEA + * projection is equal-area, in square kilometres</td></tr> + * <tr><td>{@code numberOfHexagonalCells()}</td><td>Number of hexagonal cells</td></tr> + * <tr><td>{@code numberOfPentagonalCells()}</td><td>Number of pentagonal cells</td></tr> + * </table> + * + * <h3>Threads</h3> + * + * <p>Some of the computations can be executed in parallel. The number of threads can be set as follows:</p> + * + * <pre>{@code + * ISEA3H grid = new ISEA3H(10); + * grid.setNumberOfThreads(8); + * }</pre> + * + * <p>By default, 8 threads are used.</p> + * + * + * <h2>License</h2> + * + * <p>In 2017–2019, this software has been supported by the DFG project <i>A framework for measuring the fitness + * for purpose of OpenStreetMap data based on intrinsic quality indicators</i> (FA 1189/3-1).</p> + * + * <p>All commits after 9/2019 (c) by Franz-Benjamin Mocnik, 2019.<br> + * All commits before 8/2019 (c) by Heidelberg University, 2017–2019.</p> + * + * <p>The code is licensed both under the <a href="https://github.com/mocnik-science/geogrid/blob/master/LICENSE">MIT + * license</a> and under the <a href="https://www.apache.org/licenses/LICENSE-2.0">Apache 2.0 license</a>.</p> + * + * @author Franz-Benjamin Mocnik, <a href="mailto:[email protected]">[email protected]</a> + */ +package org.apache.sis.referencing.dggs.isea; diff --git a/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/projections/ISEAProjection.java b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/projections/ISEAProjection.java new file mode 100644 index 0000000000..ff66034fb1 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/main/org/apache/sis/referencing/dggs/isea/projections/ISEAProjection.java @@ -0,0 +1,511 @@ +/* + * 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.isea.projections; + +import org.apache.sis.referencing.dggs.isea.generic.Trigonometric; +import org.apache.sis.referencing.dggs.isea.geo.WGS84; +import org.apache.sis.referencing.dggs.isea.geometry.FaceCoordinates; +import org.apache.sis.referencing.dggs.isea.geometry.GeoCoordinates; + +import java.util.ArrayList; +import java.util.List; + +/** + * Icosahedron Snyder equal-area (ISEA) projection + * + * The ISEA projection is a projects a sphere on the icosahedron. Thereby the size of areas mapped to the icosahedron + * are preserved. Angles and distances are however slightly distorted. The angular distortion is below 17.27 degree, and + * the scale variation is less than 16.3 per cent. + * + * The projection has been proposed and has been described in detail by: + * + * John P. Snyder: An equal-area map projection for polyhedral globes. Cartographica, 29(1), 10–21, 1992. + * doi:10.3138/27H7-8K88-4882-1752 + * + * Another description and improvements can be found in: + * + * Erika Harrison, Ali Mahdavi-Amiri, and Faramarz Samavati: Optimization of inverse Snyder polyhedral projection. + * International Conference on Cyberworlds 2011. doi:10.1109/CW.2011.36 + * + * Erika Harrison, Ali Mahdavi-Amiri, and Faramarz Samavati: Analysis of inverse Snyder optimizations. + * In: Marina L. Gavrilova, and C. J. Kenneth Tan (Eds): Transactions on Computational Science XVI. Heidelberg, + * Springer, 2012. pp. 134–148. doi:10.1007/978-3-642-32663-9_8 + * + * @author Franz-Benjamin Mocnik + */ +public class ISEAProjection { + // constants + private static final double _goldenRatio = (1 + Math.sqrt(5)) / 2.; + // radius + private final double _RR_earth = (1 / (2 * Math.sqrt(5)) + 1 / 6.) * Math.sqrt(Math.PI * Math.sqrt(3)); // R' / R + private final double _R; // R' + private final double _R_earth = WGS84.radiusAuthalic; // R // authalic sphere radius for WGS84 [km] + // faces + private final int _numberOfFaces = 20; + // orientation + private double _orientationLat = 0; + private double _orientationLon = 0; + // spherical constants + private final double _g; // g + private final int _G = 36; // G + private final int _theta = 30; // \theta + // distortion + private final double _omega = 17.27; // \omega + private final double _a = 1.163; // a + private final double _b = .860; // b + // face constants + private final double __E; // E + private final double __F = Trigonometric.atan(1 / (2 * Math.pow(ISEAProjection._goldenRatio, 2))); // F = \atan(1 / (2 \phi^2)) where \phi = (1 + \sqrt{5}) / 2 is the golden ratio; needs some thinking to derive + // alternative computation F = 90 + g - 2 * \atan(\phi); formula can easily be derived from the cartesian coordinates of the vertices of the icosahedron + private final double __G; // G // this value incorporates R', and not R, as is stated wrongly in the paper by Snyder + private final int __X = 36; // half the difference in latitude between two horizontally adjacent faces + private final double[] __lats = new double[20]; + private final int[] __lons = new int[20]; + // precision + private static final double _precision = 1e-9; + private static final double _precisionPerDefinition = 1e-5; + // computed values + private final double _2R; // 2 R' + private final double __EF; // E - F + private final int _AzMax = 2 * (90 - this._theta); // 2 (90 - \theta) + private final double _tan_g; // \tan g + private final double _cosG = Trigonometric.cos(this._G); // \cos G + private final double _cotTheta = Trigonometric.cot(this._theta); // \cot \theta + private final double _2cotTheta = 2 * this._cotTheta; // 2 \cot \theta + private final double _pi_R_earth2_180 = Math.PI * Math.pow(this._R_earth, 2) / 180; // \pi R^2 / 180 + private final double _R_tan_g; // R' \tan g + private final double _R_tan_g_2; // R'^2 * \tan^2 g + private final double _sinG_cos_g; // \sin G \cos g + private final double _G_180 = this._G - 180.; // G - 180 + + public ISEAProjection() { + // computations + this._g = this.__F + 2 * Trigonometric.atan(ISEAProjection._goldenRatio) - 90; + this._R = this._RR_earth * this._R_earth; + this.__E = 90 - this._g; + this.__G = this._R * Trigonometric.tan(this._g) * Math.sqrt(3) / 2.; + this._2R = 2 * this._R; + this.__EF = this.__E - this.__F; + this._tan_g = Trigonometric.tan(this._g); + this._R_tan_g = this._R * this._tan_g; + this._R_tan_g_2 = Math.pow(this._R_tan_g, 2); + this._sinG_cos_g = Trigonometric.sin(this._G) * Trigonometric.cos(this._g); + + // angles of the faces + this.__lats[0] = this.__E; + this.__lats[1] = this.__E; + this.__lats[2] = this.__E; + this.__lats[3] = this.__E; + this.__lats[4] = this.__E; + this.__lats[5] = this.__F; + this.__lats[6] = this.__F; + this.__lats[7] = this.__F; + this.__lats[8] = this.__F; + this.__lats[9] = this.__F; + this.__lats[10] = -this.__F; + this.__lats[11] = -this.__F; + this.__lats[12] = -this.__F; + this.__lats[13] = -this.__F; + this.__lats[14] = -this.__F; + this.__lats[15] = -this.__E; + this.__lats[16] = -this.__E; + this.__lats[17] = -this.__E; + this.__lats[18] = -this.__E; + this.__lats[19] = -this.__E; + this.__lons[0] = -4 * this.__X; + this.__lons[1] = -2 * this.__X; + this.__lons[2] = 0; + this.__lons[3] = 2 * this.__X; + this.__lons[4] = 4 * this.__X; + this.__lons[5] = -4 * this.__X; + this.__lons[6] = -2 * this.__X; + this.__lons[7] = 0; + this.__lons[8] = 2 * this.__X; + this.__lons[9] = 4 * this.__X; + this.__lons[10] = -3 * this.__X; + this.__lons[11] = -this.__X; + this.__lons[12] = this.__X; + this.__lons[13] = 3 * this.__X; + this.__lons[14] = 5 * this.__X; + this.__lons[15] = -3 * this.__X; + this.__lons[16] = -this.__X; + this.__lons[17] = this.__X; + this.__lons[18] = 3 * this.__X; + this.__lons[19] = 5 * this.__X; + } + + /** + * @return spherical distance from center of a face to any of its vertices on the sphere; in degrees + */ + public double sphericalDistanceFromCenterToVerticesOnSphere() { + return this._g; + } + + /** + * @return number of faces of the icosahedron + */ + public int numberOfFaces() { + return this._numberOfFaces; + } + + /** + * Sets the orientation of the icosahedron. + * + * One corner of the icosahedron is, by default, facing to the north pole, and one to the south pole. The provided + * orientation is relative to the default orientation. + * + * The orientation shifts every location by the angle <code>orientationLon</code> in direction of positive + * longitude, and thereafter by the angle <code>orientationLat</code> in direction of positive latitude. + * + * @param orientationLat + * @param orientationLon + */ + public void setOrientation(double orientationLat, double orientationLon) { + this._orientationLat = orientationLat; + this._orientationLon = orientationLon; + } + + /** + * Sets the orientation of the icosahedron such that the north and the south poles are mapped to the edge midpoints + * of the icosahedron. The equator is thus mapped symmetrically. + */ + public void setOrientationSymmetricEquator() { + this.setOrientation((this.__E + this.__F) / 2., -11.25); + } + + /** + * Only for internal use! + * Changes the orientation of geocoordinates, that is, rotates the coordinate system + * + * @param c + * @return + * @throws Exception + */ + public GeoCoordinates _changeOrientation(GeoCoordinates c) throws Exception { + if (this._orientationLat == 0 && this._orientationLon == 0) return c; + double sinOrientationLat = Trigonometric.sin(this._orientationLat); + double cosOrientationLat = Trigonometric.cos(this._orientationLat); + double sinLat1 = Trigonometric.sin(c.getLat()); + double cosLat1 = Trigonometric.cos(c.getLat()); + double lon1 = c.getLon() + this._orientationLon; + double sinLon1 = Trigonometric.sin(lon1); + double cosLon1 = Trigonometric.cos(lon1); + double lat2 = Trigonometric.asin(sinLat1 * cosOrientationLat + cosLon1 * cosLat1 * sinOrientationLat); + double lon2 = Trigonometric.atan2(sinLon1 * cosLat1, cosLon1 * cosLat1 * cosOrientationLat - sinLat1 * sinOrientationLat); + return new GeoCoordinates(lat2, lon2); + } + + /** + * Only for internal use! + * Inverse of _changeOrientation + * + * @param c + * @return + * @throws Exception + */ + public GeoCoordinates _revertOrientation(GeoCoordinates c) throws Exception { + if (this._orientationLat == 0 && this._orientationLon == 0) return (c.getLat() < -90 + ISEAProjection._precisionPerDefinition || c.getLat() > 90 - ISEAProjection._precisionPerDefinition) ? new GeoCoordinates(c.getLat(), 0.) : c; + double lon = c.getLon(); + if (c.getLat() < -90 + ISEAProjection._precisionPerDefinition || c.getLat() > 90 - ISEAProjection._precisionPerDefinition) lon = 0; + if (this._orientationLat == 0 && this._orientationLon == 0) return c; + double sinOrientationLat = Trigonometric.sin(-this._orientationLat); + double cosOrientationLat = Trigonometric.cos(this._orientationLat); + double sinLat1 = Trigonometric.sin(c.getLat()); + double cosLat1 = Trigonometric.cos(c.getLat()); + double sinLon1 = Trigonometric.sin(lon); + double cosLon1 = Trigonometric.cos(lon); + double lat2 = Trigonometric.asin(sinLat1 * cosOrientationLat + cosLon1 * cosLat1 * sinOrientationLat); + double lon2 = Trigonometric.atan2(sinLon1 * cosLat1, cosLon1 * cosLat1 * cosOrientationLat - sinLat1 * sinOrientationLat); + return new GeoCoordinates(lat2, lon2 - this._orientationLon); + } + + /** + * The projection distorts angles. This method returns the maximum angular distortion. + * + * @return maximum angular distortion + */ + public double maximumAngularDistortion() { + return this._omega; + } + + /** + * The projection distorts scale. This method returns the maximum scale variation. + * + * @return maximum scale variation + */ + public double maximumScaleVariation() { + return this._a; + } + + /** + * The projection distorts scale. This method returns the minimum scale variation. + * + * @return minimum scale variation + */ + public double miniumScaleVariation() { + return this._b; + } + + /** + * Returns the length of the bases of the triangles of the icosahedron. + * + * @return length of the bases of the triangles + */ + public double lengthOfTriangleBase() { + return 2 * this.__G; + } + + /** + * Converts geographic coordinates to coordinates on the icosahedron. + * + * @param c geographic coordinates + * @return coordinates on the icosahedron + * @throws Exception + */ + public FaceCoordinates sphereToIcosahedron(GeoCoordinates c) throws Exception { + return this._sphereToIcosahedron(this._changeOrientation(c)); + } + + /** + * Converts geographic coordinates to coordinates on the icosahedron. + * + * @param c coordinates on the icosahedron + * @return geographic coordinates + * @throws Exception + */ + public GeoCoordinates icosahedronToSphere(FaceCoordinates c) throws Exception { + return this._revertOrientation(this._icosahedronToSphere(c)); + } + + private FaceCoordinates _sphereToIcosahedron(GeoCoordinates c) { + double sinLat = Trigonometric.sin(c.getLat()); + double cosLat = Trigonometric.cos(c.getLat()); + for (int face : this._guessFace(c)) { + double lat0 = this.getLat(face); + double lon0 = this.getLon(face); + double sinLat0 = Trigonometric.sin(lat0); + double cosLat0 = Trigonometric.cos(lat0); + double sinLonLon0 = Trigonometric.sin(c.getLon() - lon0 ); + double cosLonLon0 = Trigonometric.cos(c.getLon() - lon0 ); + double Az_earth = Trigonometric.atan2(cosLat * sinLonLon0, cosLat0 * sinLat - sinLat0 * cosLat * cosLonLon0); // Az + double AzAdjustment = (this.faceOrientation(face) > 0) ? 0 : 180; + Az_earth += AzAdjustment; + while (Az_earth < 0) { + AzAdjustment += this._AzMax; + Az_earth += this._AzMax; + } + while (Az_earth > this._AzMax) { + AzAdjustment -= this._AzMax; + Az_earth -= this._AzMax; + } + double sinAz_earth = Trigonometric.sin(Az_earth); // \sin Az + double cosAz_earth = Trigonometric.cos(Az_earth); // \cos Az + double z = Trigonometric.acos(sinLat0 * sinLat + cosLat0 * cosLat * cosLonLon0); // z + double q = Trigonometric.atan2(this._tan_g, cosAz_earth + sinAz_earth * this._cotTheta); // q + if (z > q + ISEAProjection._precision) continue; + double H = this._compute_H(sinAz_earth, cosAz_earth); // H + double area = (Az_earth + this._G_180 + H) * this._pi_R_earth2_180; // A_G and A_{ABD} + double Az = Trigonometric.atan2(2 * area, this._R_tan_g_2 - area * this._2cotTheta); // Az' + double sinAz = Trigonometric.sin(Az); // \sin Az' + double cosAz = Trigonometric.cos(Az); // \cos Az' + double f = this._compute_f(sinAz, cosAz, sinAz_earth, cosAz_earth); // f + double rho = this._2R * f * Trigonometric.sin(z / 2.); // \rho + Az -= AzAdjustment; + double x = rho * Trigonometric.sin(Az); // x + double y = rho * Trigonometric.cos(Az); // y + return new FaceCoordinates(face, x, y); + } + return null; + } + + private List<Integer> _guessFace(GeoCoordinates c) { + List<Integer> result = new ArrayList<>(); + if (c.getLat() > this.__EF) { + if (c.getLon() < -108) { + result.add(0); + result.add(5); + } else if (c.getLon() < -36) { + result.add(1); + result.add(6); + } else if (c.getLon() < 36) { + result.add(2); + result.add(7); + } else if (c.getLon() < 108) { + result.add(3); + result.add(8); + } else { + result.add(4); + result.add(9); + } + } else if (c.getLat() < -this.__EF) { + if (c.getLon() < -144) { + result.add(19); + result.add(14); + } else if (c.getLon() < -72) { + result.add(15); + result.add(10); + } else if (c.getLon() < 0) { + result.add(16); + result.add(11); + } else if (c.getLon() < 72) { + result.add(17); + result.add(12); + } else if (c.getLon() < 144) { + result.add(18); + result.add(13); + } else { + result.add(19); + result.add(14); + } + } else { + if (c.getLon() < -144) { + result.add(5); + result.add(14); + } else if (c.getLon() < -108) { + result.add(5); + result.add(10); + } else if (c.getLon() < -72) { + result.add(6); + result.add(10); + } else if (c.getLon() < -36) { + result.add(6); + result.add(11); + } else if (c.getLon() < 0) { + result.add(7); + result.add(11); + } else if (c.getLon() < 36) { + result.add(7); + result.add(12); + } else if (c.getLon() < 72) { + result.add(8); + result.add(12); + } else if (c.getLon() < 108) { + result.add(8); + result.add(13); + } else if (c.getLon() < 144) { + result.add(9); + result.add(13); + } else { + result.add(9); + result.add(14); + } + } + for (int f = 0; f < this._numberOfFaces; f++) result.add(f); + return result; + } + + private GeoCoordinates _icosahedronToSphere(FaceCoordinates c) throws Exception { + double Az = Trigonometric.atan2(c.getX(), c.getY()); // Az' + double rho = Math.sqrt(Math.pow(c.getX(), 2) + Math.pow(c.getY(), 2)); // \rho + double AzAdjustment = (this.faceOrientation(c) > 0) ? 0 : 180; + Az += AzAdjustment; + while (Az < 0) { + AzAdjustment += this._AzMax; + Az += this._AzMax; + } + while (Az > this._AzMax) { + AzAdjustment -= this._AzMax; + Az -= this._AzMax; + } + double sinAz = Trigonometric.sin(Az); // \sin Az' + double cosAz = Trigonometric.cos(Az); // \cos Az' + double cotAz = cosAz / sinAz; // \cot Az' + double area = this._R_tan_g_2 / (2 * (cotAz + this._cotTheta)); // A_G or A_{ABD} + double deltaAz = 10 * ISEAProjection._precision; + double area_pi_R_earth2_180_G_180 = area / this._pi_R_earth2_180 - this._G_180; + double Az_earth = Az; + while (Math.abs(deltaAz) > ISEAProjection._precision) { + double H = this._compute_H(Trigonometric.sin(Az_earth), Trigonometric.cos(Az_earth)); // H + double FAz_earth = area_pi_R_earth2_180_G_180 - H - Az_earth; // F(Az) or g(Az) + double F2Az_earth = (Trigonometric.cos(Az_earth) * this._sinG_cos_g + Trigonometric.sin(Az_earth) * this._cosG) / Trigonometric.sin(H) - 1; // F'(Az) or g'(Az) + deltaAz = - FAz_earth / F2Az_earth; // \Delta Az^0 or \Delta Az + Az_earth += deltaAz; + } + double sinAz_earth = Trigonometric.sin(Az_earth); // \sin Az + double cosAz_earth = Trigonometric.cos(Az_earth); // \cos Az + double f = this._compute_f(sinAz, cosAz, sinAz_earth, cosAz_earth); // f + double z = 2 * Trigonometric.asin(rho / (this._2R * f)); // z + Az_earth -= AzAdjustment; + double sinLat0 = Trigonometric.sin(this._getLat(c)); // \sin \phi_0 + double cosLat0 = Trigonometric.cos(this._getLat(c)); // \cos \phi_0 + double sinZ = Trigonometric.sin(z); // \sin z + double cosZ = Trigonometric.cos(z); // \cos z + double lat = Trigonometric.asin(sinLat0 * cosZ + cosLat0 * sinZ * Trigonometric.cos(Az_earth)); // \phi + double lon = this._getLon(c) + Trigonometric.atan2(Trigonometric.sin(Az_earth) * sinZ * cosLat0, cosZ - sinLat0 * Trigonometric.sin(lat)); // \lambda + return new GeoCoordinates(lat, lon); + } + + /** + * Returns orientation of a face. + * + * @param fc + * @return 1 for upright, and -1 for upside down + */ + public int faceOrientation(FaceCoordinates fc) { + return this.faceOrientation(fc.getFace()); + } + + /** + * Returns orientation of a face. + * + * @param face + * @return 1 for upright, and -1 for upside down + */ + public int faceOrientation(int face) { + return (face <= 4 || (10 <= face && face <= 14)) ? 1 : -1; + } + + private double _compute_H(double sinAz_earth, double cosAz_earth) { + return Trigonometric.acos(sinAz_earth * this._sinG_cos_g - cosAz_earth * this._cosG); // H + } + private double _compute_f(double sinAz, double cosAz, double sinAz_earth, double cosAz_earth) { + return this._compute_d(sinAz, cosAz) / (2 * this._R * Trigonometric.sin(this._compute_q(sinAz_earth, cosAz_earth) / 2)); // f + } + private double _compute_d(double sinAz, double cosAz) { + return this._R_tan_g / (cosAz + sinAz * this._cotTheta); // d' + } + private double _compute_q(double sinAz_earth, double cosAz_earth) { + return Trigonometric.atan2(this._tan_g, (cosAz_earth + sinAz_earth * this._cotTheta)); // q + } + + private double _getLat(FaceCoordinates c) { + return this.getLat(c.getFace()); + } + private double _getLon(FaceCoordinates c) { + return this.getLon(c.getFace()); + } + + /** + * Returns latitude for face + * + * @param face + * @return latitude + */ + public double getLat(int face) { + return this.__lats[face]; + } + + /** + * Returns longitude for face + * + * @param face + * @return longitude + */ + public double getLon(int face) { + return this.__lons[face]; + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/isea/grids/ISEA3HTest.java b/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/isea/grids/ISEA3HTest.java new file mode 100644 index 0000000000..8c2a220778 --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/isea/grids/ISEA3HTest.java @@ -0,0 +1,122 @@ +/* + * 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.isea.grids; + +// Test dependencies +import org.apache.sis.referencing.dggs.isea.geo.WGS84; +import org.apache.sis.referencing.dggs.isea.geometry.FaceCoordinates; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * + * @author Franz-Benjamin Mocnik + */ +public class ISEA3HTest { + private final double _precision = 1e-9; + private final double _precision2 = 1e-15; + private final int _iterations = 1000000; + + @Disabled + @Test + public void numberOfCellsByNumber() { + this.numberOfCellsByNumber(false); + } + + @Disabled + @Test + public void numberOfCellsByNumberRotated() { + this.numberOfCellsByNumber(true); + } + + public void numberOfCellsByNumber(boolean rotatedProjection) { + this._numberOfCellsByNumber(1, 20, rotatedProjection); + this._numberOfCellsByNumber(2, 80, rotatedProjection); + this._numberOfCellsByNumber(3, 260, rotatedProjection); + this._numberOfCellsByNumber(4, 800, rotatedProjection); + this._numberOfCellsByNumber(15, 143489060, rotatedProjection); + this._numberOfCellsByNumber(16, 430467200, rotatedProjection); + } + + public void _numberOfCellsByNumber(int resolution, int numberOfHexagonalCells, boolean rotatedProjection) { + ISEA3H grid = new ISEA3H(resolution, rotatedProjection); + assertEquals(grid.numberOfHexagonalCells(), numberOfHexagonalCells); + assertEquals(grid.numberOfPentagonalCells(), 12); + } + + @Disabled + @Test + public void numberOfCellsByArea() { + this.numberOfCellsByArea(false); + } + + @Disabled + @Test + public void numberOfCellsByAreaRotated() { + this.numberOfCellsByArea(true); + } + + public void numberOfCellsByArea(boolean rotatedProjection) { + for (int r = 1; r < 19; r++) this._numberOfCellsByArea(r, rotatedProjection); + } + + public void _numberOfCellsByArea(int resolution, boolean rotatedProjection) { + ISEA3H grid = new ISEA3H(resolution, rotatedProjection); + assertTrue(grid.numberOfHexagonalCells() * grid.areaOfAHexagonalCell() + grid.numberOfPentagonalCells() * grid.areaOfAPentagonalCell() - WGS84.areaOfEarth < WGS84.areaOfEarth * this._precision2); + } + + @Disabled + @Test + public void numberOfCellsByGrid() throws Exception { + this.numberOfCellsByGrid(false); + } + + @Disabled + @Test + public void numberOfCellsByGridRotated() throws Exception { + this.numberOfCellsByGrid(true); + } + + public void numberOfCellsByGrid(boolean rotatedProjection) throws Exception { + for (int r = 1; r <= 12; r++) this._numberOfCellsByGrid(r, rotatedProjection); + } + + public void _numberOfCellsByGrid(int resolution, boolean rotatedProjection) throws Exception { + ISEA3H grid = new ISEA3H(resolution, rotatedProjection); + long cells = grid.cells().size(); + long cellsExpected = grid.numberOfHexagonalCells() + grid.numberOfPentagonalCells(); + System.out.format("resolution %d - %d - %d\n", resolution, cells, cellsExpected); + assertEquals(cells, cellsExpected); + } + + @Test + public void pointsInGridCells() throws Exception { + this._pointsInGridCells(1); + this._pointsInGridCells(12); + this._pointsInGridCells(13); + this._pointsInGridCells(16); + } + + private void _pointsInGridCells(int resolution) throws Exception { + ISEA3H grid = new ISEA3H(resolution); + for (int i = 0; i < this._iterations; i++) { + FaceCoordinates c = new FaceCoordinates(1, Math.random() * 100 - 50, Math.random() * 100 - 50); + assertTrue(c.distanceTo(grid.cellForLocation(c)) <= grid.diameterOfHexagonalCellOnIcosahedron() / 2. + this._precision); + } + } +} diff --git a/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/isea/projections/ISEAProjectionTest.java b/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/isea/projections/ISEAProjectionTest.java new file mode 100644 index 0000000000..abb1e77dba --- /dev/null +++ b/incubator/src/org.apache.sis.referencing.dggs/test/org/apache/sis/referencing/dggs/isea/projections/ISEAProjectionTest.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.isea.projections; + +import org.apache.sis.referencing.dggs.isea.generic.Trigonometric; +import org.apache.sis.referencing.dggs.isea.geometry.FaceCoordinates; +import org.apache.sis.referencing.dggs.isea.geometry.GeoCoordinates; + +// Test dependencies +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Disabled; + +/** + * + * @author Franz-Benjamin Mocnik + */ +public class ISEAProjectionTest { + private final double _precision = 1e-9; + private final int _iterations = 1000000; + + @Test + public void projectionApartFromPoles() throws Exception { + ISEAProjection p = new ISEAProjection(); + p.setOrientationSymmetricEquator(); + for (int i = 0; i < this._iterations; i++) { + GeoCoordinates c = new GeoCoordinates(Math.random() * 179.99 - 89.995, Math.random() * 360); + FaceCoordinates c2 = p.sphereToIcosahedron(c); + GeoCoordinates c3 = p.icosahedronToSphere(c2); + assertTrue(Math.abs(c3.getLat() - c.getLat()) < this._precision); + assertTrue((Math.abs(c3.getLon() - c.getLon()) % 360) * Trigonometric.cos(c.getLat()) < this._precision); + } + } +} diff --git a/parent/pom.xml b/parent/pom.xml index 21483755aa..3388f57a3a 100644 --- a/parent/pom.xml +++ b/parent/pom.xml @@ -418,6 +418,15 @@ <role>developer</role> </roles> </contributor> + <contributor> + <name>Dr Franz-Benjamin Mocnik</name> + <organization>Faculty of Digital and Analytical Sciences, Paris Lodron University of Salzburg, Austria</organization> + <organizationUrl>https://www.plus.ac.at</organizationUrl> + <timezone>+2</timezone> + <roles> + <role>developer</role> + </roles> + </contributor> </contributors> <!-- ===================================================================
