From e6ac273e24c4672bbc02ef0f97c00b16df225bb1 Mon Sep 17 00:00:00 2001 From: Jia Yu Date: Tue, 24 Nov 2026 01:15:21 -0800 Subject: [PATCH 1/3] [GH-3146] Write row group statistics for geography columns in GeoParquet 2.0 files The Parquet library collects geospatial statistics for a GEOMETRY column and has no algorithm for a GEOGRAPHY column, and it drops statistics that a writer gives it for one. Sedona computes the bounding box and the types of the geographies of each row group itself, with the edges on the sphere, and puts them into the row groups before the footer of the file is written. --- .../tutorial/files/geoparquet-sedona-spark.md | 2 + .../files/geoparquet-sedona-spark.zh.md | 2 + .../sql/sedona_sql/types/GeographyBounds.java | 262 +++++++++++++++ .../FirstGeometryOutputWriter.scala | 21 +- .../geoparquet/GeoParquetFileFormat.scala | 6 +- .../geoparquet/GeoParquetWriteSupport.scala | 67 +++- .../GeographyRowGroupStatistics.scala | 267 +++++++++++++++ .../GeoParquetGeographyStatisticsSuite.scala | 312 ++++++++++++++++++ .../types/GeographyBoundsTest.scala | 261 +++++++++++++++ 9 files changed, 1186 insertions(+), 14 deletions(-) create mode 100644 spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/GeographyBounds.java create mode 100644 spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeographyRowGroupStatistics.scala create mode 100644 spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetGeographyStatisticsSuite.scala create mode 100644 spark/common/src/test/scala/org/apache/spark/sql/sedona_sql/types/GeographyBoundsTest.scala diff --git a/docs/tutorial/files/geoparquet-sedona-spark.md b/docs/tutorial/files/geoparquet-sedona-spark.md index b4fdd84b801..90d73ac43c7 100644 --- a/docs/tutorial/files/geoparquet-sedona-spark.md +++ b/docs/tutorial/files/geoparquet-sedona-spark.md @@ -353,6 +353,8 @@ Set `geoparquet.crs` or `geoparquet.crs.` to state the CRS yourself A geography column is stored in the `GEOGRAPHY` logical type with spherical edges, as WKB, and the GeoParquet metadata lists it with `"edges": "spherical"`. A file can have geography columns and no geometry column. Sedona writes no `bbox` for a geography column, because the `bbox` of the GeoParquet metadata is planar. +The row groups of a geography column have geospatial statistics as well. The Parquet library has no algorithm for a geography column, so Sedona computes them: the geometry types, and a bounding box in longitude and latitude. The box covers the edges of the geographies on the sphere and not only their vertices. It reaches a pole for a polygon around that pole, and its `xmin` is above its `xmax` when it crosses the antimeridian, as the Parquet format defines. It has no bounds for Z and M. The Parquet options `parquet.column.statistics.enabled` and `parquet.column.statistics.enabled#` turn these statistics off with the value `false`, as they do for the statistics of the Parquet library. An encrypted file gets none. + The CRS of a geography column follows the rules of a geometry column, and `geoparquet.crs` and `geoparquet.crs.` apply to it as well. There is one difference on Spark 4.1: a geography without an SRID is written as OGC:CRS84, and so is a column without any geography in the file. The `GEOGRAPHY` logical type takes a geographic CRS, with longitudes from -180 to 180 and latitudes from -90 to 90. Sedona's own geography type on Spark 4.1 takes any SRID and any coordinates, so a write fails for a geography column whose CRS is a projected one, and for a geography outside these bounds. diff --git a/docs/tutorial/files/geoparquet-sedona-spark.zh.md b/docs/tutorial/files/geoparquet-sedona-spark.zh.md index 245485ab458..d146ae95367 100644 --- a/docs/tutorial/files/geoparquet-sedona-spark.zh.md +++ b/docs/tutorial/files/geoparquet-sedona-spark.zh.md @@ -348,6 +348,8 @@ Sedona 必须在写出第一行之前知道 CRS,因此会把第一个几何对 地理列以 WKB 存入边为球面(spherical)的 `GEOGRAPHY` 逻辑类型,GeoParquet 元数据中该列带有 `"edges": "spherical"`。文件可以只有地理列而没有几何列。Sedona 不为地理列写出 `bbox`,因为 GeoParquet 元数据中的 `bbox` 是平面的。 +地理列的行组同样带有地理空间统计信息。Parquet 库没有针对地理列的算法,因此由 Sedona 计算:几何类型,以及以经纬度表示的边界框。该边界框覆盖地理对象在球面上的边,而不仅是顶点。多边形包围极点时,边界框延伸到该极点;跨越 180° 经线时,其 `xmin` 大于 `xmax`,与 Parquet 格式的定义一致。边界框不含 Z 和 M 的范围。把 Parquet 选项 `parquet.column.statistics.enabled` 或 `parquet.column.statistics.enabled#` 设为 `false` 即可关闭这些统计信息,与关闭 Parquet 库自身的统计信息相同。加密文件不带这些统计信息。 + 地理列的 CRS 遵循几何列的规则,`geoparquet.crs` 和 `geoparquet.crs.` 同样适用。在 Spark 4.1 上有一点不同:没有 SRID 的地理对象按 OGC:CRS84 写出,文件中没有任何地理对象的列也是如此。 `GEOGRAPHY` 逻辑类型要求使用地理 CRS,经度范围为 -180 到 180,纬度范围为 -90 到 90。Spark 4.1 上 Sedona 自有的地理类型接受任意 SRID 和任意坐标,因此如果地理列的 CRS 是投影 CRS,或者某个地理对象超出上述范围,写入会失败。 diff --git a/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/GeographyBounds.java b/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/GeographyBounds.java new file mode 100644 index 00000000000..058d4257936 --- /dev/null +++ b/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/GeographyBounds.java @@ -0,0 +1,262 @@ +/* + * 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.spark.sql.sedona_sql.types; + +import com.google.common.geometry.S2EdgeUtil; +import com.google.common.geometry.S2LatLng; +import com.google.common.geometry.S2LatLngRect; +import java.io.IOException; +import org.apache.sedona.common.S2Geography.WKBReader; +import org.locationtech.jts.io.InStream; + +/** + * The bounding box, in degrees of longitude and latitude, of geographies with edges on the sphere. + * It is the box that the statistics of a Parquet GEOGRAPHY column hold: it has the edges of the + * geographies and not only their vertices, it reaches a pole for a polygon around that pole, and + * its western bound is above its eastern bound when it crosses the antimeridian. + * + *

A point is added from its coordinates, without an object for it. A line and a ring give their + * vertices to the edge bounder of S2, which has the bounds of the edges between them. Only a + * polygon whose ring spans half of all longitudes or more is read into its S2 form, which tells + * which side of such a ring is the inside and whether a pole is in it. + */ +public final class GeographyBounds { + /** + * What the box grows by on every side, in radians, when S2 has computed any of it. S2 works in + * radians, and a coordinate that goes from degrees to radians and back can come out some 1e-15 + * radians off. The margin keeps every coordinate inside the box as it is written. + */ + private static final double MARGIN = 1e-14; + + /** A little less than pi, so that rounding keeps a ring of half of all longitudes above it. */ + private static final double HALF_OF_ALL_LONGITUDES = Math.PI - 1e-9; + + private final WKBReader reader = new WKBReader(); + private final Slice slice = new Slice(); + + // The points, by the sign of their longitude. The two ranges give the box of the points both + // ways around the sphere, in the coordinates that the points have. + private double westMin; + private double westMax; + private double eastMin; + private double eastMax; + private double latMin; + private double latMax; + private boolean antimeridian; + // The other geographies + private S2LatLngRect shapes; + private boolean unknown; + + public GeographyBounds() { + reset(); + } + + /** Forgets the geographies added so far. */ + public void reset() { + westMin = Double.POSITIVE_INFINITY; + westMax = Double.NEGATIVE_INFINITY; + eastMin = Double.POSITIVE_INFINITY; + eastMax = Double.NEGATIVE_INFINITY; + latMin = Double.POSITIVE_INFINITY; + latMax = Double.NEGATIVE_INFINITY; + antimeridian = false; + shapes = S2LatLngRect.empty(); + unknown = false; + } + + /** + * Adds the geography that {@code wkb} holds as ISO WKB from {@code offset} to its end. The WKB is + * well-formed: {@link GeographyWkbScanner#scan} has walked it. + */ + public void add(byte[] wkb, int offset) { + if (unknown) return; + try { + if (!addShapes(wkb, offset)) { + slice.set(wkb, offset); + shapes = shapes.union(reader.read(slice).region().getRectBound()); + } + } catch (Exception | AssertionError e) { + // Without the bounds of one geography there is no box for all of them + unknown = true; + } + } + + /** + * Adds the points, lines and polygons of a geography from their coordinates. + * + * @return false for a geography that has to be read into its S2 form instead + */ + private boolean addShapes(byte[] wkb, int offset) { + int position = offset; + long pending = 1; + while (pending-- > 0) { + boolean little = wkb[position] == 1; + int code = readInt(wkb, position + 1, little); + int layout = code / 1000; + int width = (layout == 0 ? 2 : layout == 3 ? 4 : 3) * 8; + position += 5; + switch (code % 1000) { + case 1: + addPoint(readDouble(wkb, position, little), readDouble(wkb, position + 8, little)); + position += width; + break; + case 2: + { + int count = readInt(wkb, position, little); + shapes = shapes.union(edges(wkb, position + 4, count, width, little)); + position += 4 + count * width; + break; + } + case 3: + { + int rings = readInt(wkb, position, little); + position += 4; + for (int ring = 0; ring < rings; ring++) { + int count = readInt(wkb, position, little); + // The polygon is within its first ring. The other rings are holes in it. + if (ring == 0 && count > 0) { + S2LatLngRect bound = edges(wkb, position + 4, count, width, little); + // The inside of a ring is its smaller side. With edges over less than half of + // all longitudes that side has no pole, and it is within the bounds of the + // edges: the other side has every meridian that the edges do not reach, which + // is more than half of the sphere. + if (bound.lng().getLength() >= HALF_OF_ALL_LONGITUDES) return false; + shapes = shapes.union(bound); + } + position += 4 + count * width; + } + break; + } + default: + pending += readInt(wkb, position, little); + position += 4; + } + } + return true; + } + + /** The bounds of the edges between {@code count} vertices in a row. */ + private static S2LatLngRect edges( + byte[] wkb, int position, int count, int width, boolean little) { + if (count == 0) return S2LatLngRect.empty(); + S2EdgeUtil.RectBounder bounder = new S2EdgeUtil.RectBounder(); + for (int at = position, end = position + count * width; at < end; at += width) { + bounder.addPoint( + S2LatLng.fromDegrees(readDouble(wkb, at + 8, little), readDouble(wkb, at, little))); + } + return bounder.getBound(); + } + + private void addPoint(double longitude, double latitude) { + // The coordinates of an empty point are not numbers + if (Double.isNaN(longitude) || Double.isNaN(latitude)) return; + if (longitude < 0) { + if (longitude < westMin) westMin = longitude; + if (longitude > westMax) westMax = longitude; + } else { + if (longitude < eastMin) eastMin = longitude; + if (longitude > eastMax) eastMax = longitude; + } + if (latitude < latMin) latMin = latitude; + if (latitude > latMax) latMax = latitude; + // The antimeridian is longitude 180 and longitude -180 + if (longitude == 180 || longitude == -180) antimeridian = true; + } + + /** + * The box of the geographies added since the last {@link #reset}. + * + * @return the western, eastern, southern and northern bound in this order, or null when no + * geography with a coordinate was added or one of them could not be read. The western bound + * is above the eastern bound for a box that crosses the antimeridian. + */ + public double[] box() { + if (unknown) return null; + boolean points = latMin <= latMax; + if (!points && shapes.isEmpty()) return null; + double west = 0; + double east = 0; + if (points) { + boolean hasWest = westMin <= westMax; + boolean hasEast = eastMin <= eastMax; + west = hasWest ? westMin : eastMin; + east = hasEast ? eastMax : westMax; + // The other way around the sphere, across the antimeridian, when that is the shorter one + if (hasWest && hasEast && (180 - eastMin) + (westMax + 180) < east - west) { + west = eastMin; + east = westMax; + } + if (shapes.isEmpty() && !antimeridian) return new double[] {west, east, latMin, latMax}; + } + S2LatLngRect all = shapes; + if (points) { + all = + all.union( + new S2LatLngRect( + S2LatLng.fromDegrees(latMin, west), S2LatLng.fromDegrees(latMax, east))); + } + all = all.expanded(S2LatLng.fromRadians(MARGIN, MARGIN)); + double south = Math.max(-90, all.latLo().degrees()); + double north = Math.min(90, all.latHi().degrees()); + if (all.lng().isFull()) return new double[] {-180, 180, south, north}; + return new double[] { + Math.max(-180, Math.min(180, all.lngLo().degrees())), + Math.max(-180, Math.min(180, all.lngHi().degrees())), + south, + north + }; + } + + private static int readInt(byte[] bytes, int at, boolean little) { + int value = 0; + for (int i = 0; i < 4; i++) { + value = value << 8 | (bytes[little ? at + 3 - i : at + i] & 0xff); + } + return value; + } + + private static double readDouble(byte[] bytes, int at, boolean little) { + long value = 0; + for (int i = 0; i < 8; i++) { + value = value << 8 | (bytes[little ? at + 7 - i : at + i] & 0xffL); + } + return Double.longBitsToDouble(value); + } + + /** The bytes of an array from an offset on, for a reader of WKB. */ + private static final class Slice implements InStream { + private byte[] bytes; + private int position; + + void set(byte[] bytes, int offset) { + this.bytes = bytes; + this.position = offset; + } + + @Override + public int read(byte[] buffer) throws IOException { + if (buffer.length > bytes.length - position) { + throw new IOException("The WKB ends before the geography does"); + } + System.arraycopy(bytes, position, buffer, 0, buffer.length); + position += buffer.length; + return buffer.length; + } + } +} diff --git a/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/FirstGeometryOutputWriter.scala b/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/FirstGeometryOutputWriter.scala index 5a9135c3d14..dd1b989e5b9 100644 --- a/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/FirstGeometryOutputWriter.scala +++ b/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/FirstGeometryOutputWriter.scala @@ -25,6 +25,7 @@ import org.apache.hadoop.fs.Path import org.apache.hadoop.mapreduce.{RecordWriter, TaskAttemptContext} import org.apache.sedona.sql.utils.GeographySerializer import org.apache.parquet.hadoop.ParquetOutputFormat +import org.apache.parquet.hadoop.api.WriteSupport import org.apache.parquet.hadoop.codec.CodecConfig import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.expressions.{UnsafeProjection, UnsafeRow} @@ -33,7 +34,8 @@ import org.apache.spark.sql.sedona_sql.types.SpatialTypeSupport import org.apache.spark.sql.types.StructType /** - * Writes a GeoParquet 2 file that has GeometryUDT or GeographyUDT columns without a CRS option. + * Writes a GeoParquet 2 file that has GeometryUDT or GeographyUDT columns without a CRS option, + * or geography columns whose row groups get statistics. * * GeoParquet 2 states the CRS of a geometry column in the Parquet schema, which the Parquet * writer needs before the first row. A GeometryUDT column has an SRID on each geometry only. This @@ -45,7 +47,8 @@ import org.apache.spark.sql.types.StructType * bytes. A column that has shown no geometry by then is written with an unknown CRS. * * @param columns - * the ordinals of the columns to look up, see [[GeoParquetWriteSupport.columnsWithoutCrs]] + * the ordinals of the columns to look up, see [[GeoParquetWriteSupport.columnsWithoutCrs]]. + * Without any, the file is opened at its first row. */ class FirstGeometryOutputWriter( val path: String, @@ -118,8 +121,20 @@ class FirstGeometryOutputWriter( GeoParquetWriteSupport.FIRST_GEOMETRY_SRID_KEY + ordinal, srids.get(ordinal).map(_.toString).getOrElse(GeoParquetWriteSupport.NO_FIRST_GEOMETRY)) } - recordWriter = new ParquetOutputFormat[InternalRow]() + // The write support is the one that the configuration names, as the Parquet library makes + // it. It is made here to give it the writer of the file. + val writeSupport = ParquetOutputFormat + .getWriteSupportClass(fileConfiguration) + .getDeclaredConstructor() + .newInstance() + .asInstanceOf[WriteSupport[InternalRow]] + recordWriter = new ParquetOutputFormat[InternalRow](writeSupport) .getRecordWriter(fileConfiguration, new Path(path), CodecConfig.from(context).getCodec) + writeSupport match { + case geoParquet: GeoParquetWriteSupport => + geoParquet.collectGeographyStatistics(recordWriter) + case _ => + } try heldBack.foreach(recordWriter.write(null, _)) catch { case error: Throwable => diff --git a/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetFileFormat.scala b/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetFileFormat.scala index 81d68c36a61..f8b6680df20 100644 --- a/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetFileFormat.scala +++ b/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetFileFormat.scala @@ -179,7 +179,11 @@ class GeoParquetFileFormat(val spatialFilter: Option[GeoParquetSpatialFilter]) // the first row val columns = GeoParquetWriteSupport.columnsWithoutCrs(dataSchema, context.getConfiguration) - if (columns.isEmpty) new ParquetOutputWriter(path, context) + // The row groups of its geography columns get statistics from Sedona, which needs the + // Parquet writer of the file for them + val statistics = + GeoParquetWriteSupport.collectsGeographyStatistics(dataSchema, context.getConfiguration) + if (columns.isEmpty && !statistics) new ParquetOutputWriter(path, context) else new FirstGeometryOutputWriter(path, context, dataSchema, columns) } diff --git a/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetWriteSupport.scala b/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetWriteSupport.scala index 49c1b909349..0ae56843e54 100644 --- a/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetWriteSupport.scala +++ b/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeoParquetWriteSupport.scala @@ -126,6 +126,11 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging { private val geographyColumnTypes: mutable.Map[Int, mutable.BitSet] = mutable.LinkedHashMap.empty private var geographyColumnCrs: Map[Int, Option[JValue]] = Map.empty + // The geography columns whose row groups get statistics, by their ordinal, and the statistics + // once the writer of the file has given the row groups of the file, see + // collectGeographyStatistics. Null without them. + private var geographyStatisticsColumns: Seq[Int] = Seq.empty + private var geographyStatistics: GeographyRowGroupStatistics = _ private val geoParquetColumnCoveringMap: mutable.Map[String, Covering] = mutable.Map.empty private val generatedCoveringColumnOrdinals: mutable.Map[Int, Int] = mutable.Map.empty private var geoParquetCoveringMode: String = GEOPARQUET_COVERING_MODE_AUTO @@ -262,6 +267,9 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging { } ordinal -> crs }.toMap + geographyStatisticsColumns = geographyColumnTypes.keys.toSeq.filter { ordinal => + GeographyRowGroupStatistics.enabled(configuration, schema(ordinal).name) + } Option(configuration.get(GEOPARQUET_COVERING_KEY)).foreach { coveringColumnName => if (geometryColumnInfoMap.size > 1) { throw new IllegalArgumentException( @@ -324,11 +332,31 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging { new WriteContext(messageType, metadata.asJava) } + /** + * Collects the statistics of the row groups of the geography columns, which the Parquet library + * does not collect, for the file that `recordWriter` writes with this write support. Called + * once the writer exists and before it has a row. Without the call, or when the row groups of + * the writer cannot be reached, the file has no such statistics. + */ + private[geoparquet] def collectGeographyStatistics(recordWriter: AnyRef): Unit = { + if (geographyStatisticsColumns.nonEmpty) { + GeographyRowGroupStatistics.rowGroupsOf(recordWriter).foreach { rowGroups => + val columns = new Array[String](schema.length) + geographyStatisticsColumns.foreach(ordinal => columns(ordinal) = schema(ordinal).name) + geographyStatistics = new GeographyRowGroupStatistics(columns, rowGroups) + } + } + } + override def prepareForWrite(recordConsumer: RecordConsumer): Unit = { this.recordConsumer = recordConsumer + // The Parquet library calls this at the start of every row group + if (geographyStatistics != null) geographyStatistics.endRowGroup() } override def finalizeWrite(): WriteSupport.FinalizedWriteContext = { + // The Parquet library has flushed the last row group, and writes the footer after this + if (geographyStatistics != null) geographyStatistics.write() val metadata = new util.HashMap[String, String]() if (geometryColumnInfoMap.nonEmpty || geographyColumnTypes.nonEmpty) { // A geometry column comes first. A file can have geography columns alone. @@ -387,6 +415,7 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging { consumeMessage { writeFields(row, schema, rootFieldWriters) } + if (geographyStatistics != null) geographyStatistics.endRow() } private def writeFields( @@ -675,8 +704,10 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging { } case dt if rootOrdinal.exists(geographyColumnTypes.contains) => - val column = schema(rootOrdinal.get).name - val typeCodes = geographyColumnTypes(rootOrdinal.get) + val columnOrdinal = rootOrdinal.get + val column = schema(columnOrdinal).name + val collectsStatistics = geographyStatisticsColumns.contains(columnOrdinal) + val typeCodes = geographyColumnTypes(columnOrdinal) val typeSrid = SpatialTypeSupport.geographySrid(dt) val firstSrid = firstGeometrySrids.get(rootOrdinal.get).flatten val native = SpatialTypeSupport.isNativeGeography(dt) @@ -707,15 +738,18 @@ class GeoParquetWriteSupport extends WriteSupport[InternalRow] with Logging { // Spark has checked the coordinates of a value of its native geography type. Sedona's // own type takes any, and a GEOGRAPHY column takes longitudes and latitudes. val scanned = GeographyWkbScanner.scan(bytes, offset, !native, column) - if ((scanned & GeographyWkbScanner.NOT_ISO) == 0) { - recordConsumer.addBinary( - Binary.fromConstantByteArray(bytes, offset, bytes.length - offset)) - } else { - val wkb = java.util.Arrays.copyOfRange(bytes, offset, bytes.length) - recordConsumer.addBinary( - Binary.fromConstantByteArray(PublicWkbHeaderAdapter.toIsoWkbInPlace(wkb))) + val typeCode = scanned & ~GeographyWkbScanner.NOT_ISO + if ((scanned & GeographyWkbScanner.NOT_ISO) != 0) { + bytes = PublicWkbHeaderAdapter.toIsoWkbInPlace( + java.util.Arrays.copyOfRange(bytes, offset, bytes.length)) + offset = 0 + } + recordConsumer.addBinary( + Binary.fromConstantByteArray(bytes, offset, bytes.length - offset)) + typeCodes += typeCode + if (collectsStatistics && geographyStatistics != null) { + geographyStatistics.add(columnOrdinal, bytes, offset, typeCode) } - typeCodes += scanned & ~GeographyWkbScanner.NOT_ISO } case t: UserDefinedType[_] => makeWriter(t.sqlType) @@ -996,6 +1030,19 @@ object GeoParquetWriteSupport { } } + /** + * Whether a write of `schema` has geography columns whose row groups get statistics from + * Sedona: the geography columns at the root of the schema of a GeoParquet 2 file, unless the + * statistics of the Parquet library are turned off for them. + */ + def collectsGeographyStatistics(schema: StructType, configuration: Configuration): Boolean = { + val version = Option(configuration.get(GEOPARQUET_VERSION_KEY)).getOrElse(VERSION) + GeoParquetMetaData.usesGeospatialTypes(version) && schema.fields.exists { field => + SpatialTypeSupport.isGeography(field.dataType) && + GeographyRowGroupStatistics.enabled(configuration, field.name) + } + } + /** The CRS option of each of `columns` that has one, under the key [[setWriteOptions]] set. */ private[geoparquet] def columnCrsOptions( configuration: Configuration, diff --git a/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeographyRowGroupStatistics.scala b/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeographyRowGroupStatistics.scala new file mode 100644 index 00000000000..526a8f5864d --- /dev/null +++ b/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeographyRowGroupStatistics.scala @@ -0,0 +1,267 @@ +/* + * 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.spark.sql.execution.datasources.geoparquet + +import java.lang.reflect.Modifier +import java.util.concurrent.atomic.AtomicBoolean + +import scala.collection.JavaConverters._ +import scala.collection.mutable +import scala.util.{Failure, Success, Try} + +import org.apache.hadoop.conf.Configuration +import org.apache.parquet.hadoop.ParquetFileWriter +import org.apache.parquet.hadoop.metadata.{BlockMetaData, ColumnChunkMetaData, ColumnPath} +import org.apache.spark.internal.Logging +import org.apache.spark.sql.sedona_sql.types.GeographyBounds + +/** + * The geospatial statistics of the row groups of the geography columns of one file: the bounding + * box and the type codes of the geographies of each row group. + * + * The Parquet library collects these statistics for a GEOMETRY column and has no algorithm for a + * GEOGRAPHY column, whose edges are on the sphere, and it drops statistics that a writer gives it + * for one. Sedona therefore collects them while it writes the values, and puts them into the row + * groups that the Parquet library has finished, before that library writes the footer of the file + * from those row groups. See [[GeographyRowGroupStatistics.rowGroupsOf]] for how it gets at them. + * + * @param columns + * the names of the geography columns, by their ordinal in the schema, null for other columns + * @param rowGroups + * the row groups that the Parquet library has finished, which it writes the footer from + */ +private[geoparquet] class GeographyRowGroupStatistics( + columns: Array[String], + rowGroups: java.util.List[BlockMetaData]) { + import GeographyRowGroupStatistics.Column + + private val ordinals = columns.indices.filter(columns(_) != null).toArray + private val bounds = columns.map(name => if (name == null) null else new GeographyBounds) + private val types = columns.map(name => if (name == null) null else mutable.BitSet.empty) + private var rows = 0L + private val finished = mutable.ArrayBuffer.empty[(Long, Map[ColumnPath, Column])] + + /** + * Adds a geography of the column at `ordinal`, which `wkb` holds as ISO WKB from `offset` on. + */ + def add(ordinal: Int, wkb: Array[Byte], offset: Int, typeCode: Int): Unit = { + bounds(ordinal).add(wkb, offset) + types(ordinal) += typeCode + } + + def endRow(): Unit = rows += 1 + + /** Ends the row group of the rows since the last call. Without such rows there is none. */ + def endRowGroup(): Unit = if (rows > 0) { + val found = ordinals.map { ordinal => + val column = Column(Option(bounds(ordinal).box()), types(ordinal).toSet) + bounds(ordinal).reset() + types(ordinal).clear() + ColumnPath.get(columns(ordinal)) -> column + }.toMap + finished += rows -> found + rows = 0 + } + + /** Ends the last row group and gives the row groups of the file their statistics. */ + def write(): Unit = { + endRowGroup() + GeographyRowGroupStatistics.write(rowGroups, finished.toSeq) + } +} + +object GeographyRowGroupStatistics extends Logging { + + /** + * The statistics of a column in one row group: the western, eastern, southern and northern + * bound of its geographies, None without a coordinate, and their ISO type codes. + */ + case class Column(box: Option[Array[Double]], types: Set[Int]) + + /** + * The key of the Parquet library that turns the statistics of the columns on and off, and with + * `#` and the name of a column after it those of that column. + */ + private val STATISTICS_ENABLED = "parquet.column.statistics.enabled" + + /** Whether a write with `configuration` collects the statistics of `column`. */ + def enabled(configuration: Configuration, column: String): Boolean = + library.isDefined && Option(configuration.get(STATISTICS_ENABLED + "#" + column)) + .map(_.trim.toBoolean) + .getOrElse(configuration.getBoolean(STATISTICS_ENABLED, true)) + + /** + * The classes of the geospatial statistics, which parquet-java has since 1.16.0. Sedona also + * compiles against older versions, so they are reached by reflection. + */ + private class Library { + private def load(name: String): Class[_] = + Class.forName( + "org.apache.parquet.column.statistics.geospatial." + name, + false, + classOf[ColumnChunkMetaData].getClassLoader) + + private val boxClass = load("BoundingBox") + private val typesClass = load("GeospatialTypes") + private val statisticsClass = load("GeospatialStatistics") + private val newBox = boxClass.getConstructor(Seq.fill(8)(java.lang.Double.TYPE): _*) + private val newTypes = typesClass.getConstructor(classOf[java.util.Set[_]]) + private val newStatistics = statisticsClass.getConstructor(boxClass, typesClass) + private val sizeStatistics = classOf[ColumnChunkMetaData].getMethod("getSizeStatistics") + private val newChunk = classOf[ColumnChunkMetaData].getMethods + .find { method => + method.getName == "get" && Modifier.isStatic(method.getModifiers) && + method.getParameterCount == 13 && method.getParameterTypes.last == statisticsClass + } + .getOrElse(throw new NoSuchMethodException("ColumnChunkMetaData.get")) + + /** A copy of `chunk` with the statistics of `column`. */ + def withStatistics(chunk: ColumnChunkMetaData, column: Column): ColumnChunkMetaData = { + val nan = Double.box(Double.NaN) + val box = column.box.map { case Array(west, east, south, north) => + // The box has no bounds of Z and M + newBox.newInstance( + Double.box(west), + Double.box(east), + Double.box(south), + Double.box(north), + nan, + nan, + nan, + nan) + } + val types = newTypes.newInstance(column.types.map(Int.box).asJava) + val statistics = + newStatistics.newInstance(box.orNull.asInstanceOf[AnyRef], types.asInstanceOf[AnyRef]) + newChunk + .invoke( + null, + chunk.getPath, + chunk.getPrimitiveType, + chunk.getCodec, + chunk.getEncodingStats, + chunk.getEncodings, + chunk.getStatistics, + Long.box(chunk.getFirstDataPageOffset), + Long.box(chunk.getDictionaryPageOffset), + Long.box(chunk.getValueCount), + Long.box(chunk.getTotalSize), + Long.box(chunk.getTotalUncompressedSize), + sizeStatistics.invoke(chunk), + statistics.asInstanceOf[AnyRef]) + .asInstanceOf[ColumnChunkMetaData] + } + } + + private lazy val library: Option[Library] = Try(new Library).toOption + + private val warned = new AtomicBoolean(false) + + private def warn(reason: String, error: Throwable = null): Unit = { + if (warned.compareAndSet(false, true)) { + val message = s"Writing GeoParquet files without the row group statistics of their " + + s"geography columns: $reason. The files are complete without them." + if (error == null) logWarning(message) else logWarning(message, error) + } + } + + private def field(target: AnyRef, name: String): AnyRef = { + var owner: Class[_] = target.getClass + while (owner != null) { + try { + val found = owner.getDeclaredField(name) + found.setAccessible(true) + return found.get(target) + } catch { + case _: NoSuchFieldException => owner = owner.getSuperclass + } + } + throw new NoSuchFieldException(s"${target.getClass.getName}.$name") + } + + /** + * The row groups that the Parquet library has finished for the file of `recordWriter`, a writer + * of `ParquetOutputFormat`. The library adds a row group to this list when it flushes one, and + * writes the footer from the list when the file is closed. + * + * The library has no public way to the list, so this reads three private fields of it, which + * have these names in parquet-java 1.16.0 and 1.17.0. None when they are not there, and for an + * encrypted file, whose column chunks are of another kind. A file is then written as the + * Parquet library writes it, without statistics for its geography columns. + */ + def rowGroupsOf(recordWriter: AnyRef): Option[java.util.List[BlockMetaData]] = { + Try { + val fileWriter = field(field(recordWriter, "internalWriter"), "parquetFileWriter") + .asInstanceOf[ParquetFileWriter] + if (fileWriter.getEncryptor != null) None + else { + field(fileWriter, "blocks") match { + case rowGroups: java.util.List[_] => + Some(rowGroups.asInstanceOf[java.util.List[BlockMetaData]]) + case other => throw new ClassCastException(s"The row groups are $other") + } + } + } match { + case Success(rowGroups) => rowGroups + case Failure(error) => + warn("the row groups of the Parquet writer were not found", error) + None + } + } + + /** + * Replaces the row groups of `rowGroups` by copies that have the statistics of `finished`, + * which has the number of rows and the statistics of each row group in the order of the file. + * The row groups stay as they are if the two do not describe the same row groups. + */ + private def write( + rowGroups: java.util.List[BlockMetaData], + finished: Seq[(Long, Map[ColumnPath, Column])]): Unit = { + val existing = rowGroups.asScala.toSeq + if (existing.map(_.getRowCount) != finished.map(_._1)) { + warn( + s"the Parquet writer has row groups of ${existing.map(_.getRowCount).mkString(", ")} " + + s"rows, and the statistics are of ${finished.map(_._1).mkString(", ")} rows") + return + } + Try { + existing.zip(finished).map { case (rowGroup, (_, columns)) => + val copy = new BlockMetaData + copy.setRowCount(rowGroup.getRowCount) + copy.setTotalByteSize(rowGroup.getTotalByteSize) + copy.setPath(rowGroup.getPath) + copy.setOrdinal(rowGroup.getOrdinal) + copy.setRowIndexOffset(rowGroup.getRowIndexOffset) + rowGroup.getColumns.asScala.foreach { chunk => + columns.get(chunk.getPath) match { + // A row group of nulls has nothing to state + case Some(column) if column.box.isDefined || column.types.nonEmpty => + copy.addColumn(library.get.withStatistics(chunk, column)) + case _ => copy.addColumn(chunk) + } + } + copy + } + } match { + case Success(copies) => + copies.zipWithIndex.foreach { case (copy, index) => rowGroups.set(index, copy) } + case Failure(error) => warn("they could not be added to the row groups", error) + } + } +} diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetGeographyStatisticsSuite.scala b/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetGeographyStatisticsSuite.scala new file mode 100644 index 00000000000..69544bb9feb --- /dev/null +++ b/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetGeographyStatisticsSuite.scala @@ -0,0 +1,312 @@ +/* + * 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.sedona.sql + +import java.io.File +import java.nio.file.Files + +import org.apache.commons.io.FileUtils +import org.apache.hadoop.conf.Configuration +import org.apache.hadoop.fs.Path +import org.apache.parquet.hadoop.ParquetFileReader +import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData +import org.apache.parquet.hadoop.util.HadoopInputFile +import org.apache.spark.sql.DataFrame +import org.apache.spark.sql.execution.datasources.geoparquet.{GeographyRowGroupStatistics, ParquetGeospatialTypes} + +import scala.collection.JavaConverters._ +import scala.util.Random + +/** + * The Parquet library collects no statistics for a GEOGRAPHY column. Sedona gives the row groups + * of a GeoParquet 2 file the bounding box and the geospatial types of their geographies itself. + */ +class GeoParquetGeographyStatisticsSuite extends TestBaseScala { + + /** The bounding box of a row group, with `xmin` above `xmax` across the antimeridian. */ + private case class Box(xmin: Double, xmax: Double, ymin: Double, ymax: Double) { + def contains(x: Double, y: Double): Boolean = { + val inX = if (xmin <= xmax) x >= xmin && x <= xmax else x >= xmin || x <= xmax + inX && y >= ymin && y <= ymax + } + } + + /** The geospatial statistics of a column in one row group. */ + private case class RowGroup(rows: Long, box: Option[Box], types: Set[Int]) + + private def withDirectory(run: File => Unit): Unit = { + val directory = Files.createTempDirectory("geoparquet-geography-statistics").toFile + try run(directory) + finally FileUtils.deleteDirectory(directory) + } + + private def writeVersion2(df: DataFrame, path: String, options: (String, String)*): Unit = + df.coalesce(1) + .write + .format("geoparquet") + .option("geoparquet.version", "2.0.0") + .options(options.toMap) + .save(path) + + /** The statistics that the footer of the one file under `path` has for `column`. */ + private def rowGroups(path: String, column: String = "geography"): Seq[RowGroup] = { + val files = new File(path).listFiles().filter(_.getName.endsWith(".parquet")) + assert(files.length == 1) + val reader = ParquetFileReader.open( + HadoopInputFile.fromPath(new Path(files.head.getPath), new Configuration())) + val blocks = + try reader.getFooter.getBlocks.asScala.toSeq + finally reader.close() + // Sedona also compiles against Parquet libraries without geospatial statistics + val statistics = classOf[ColumnChunkMetaData].getMethod("getGeospatialStatistics") + def number(box: AnyRef, name: String): Double = + box.getClass.getMethod(name).invoke(box).asInstanceOf[Double] + blocks.map { block => + val chunk = block.getColumns.asScala.find(_.getPath.toDotString == column).get + val found = Option(statistics.invoke(chunk)) + val box = found + .flatMap(value => Option(value.getClass.getMethod("getBoundingBox").invoke(value))) + .filter(box => box.getClass.getMethod("isValid").invoke(box).asInstanceOf[Boolean]) + .filterNot(box => box.getClass.getMethod("isXYEmpty").invoke(box).asInstanceOf[Boolean]) + .map(box => + Box( + number(box, "getXMin"), + number(box, "getXMax"), + number(box, "getYMin"), + number(box, "getYMax"))) + val types = found + .flatMap(value => Option(value.getClass.getMethod("getGeospatialTypes").invoke(value))) + .map(types => + types.getClass + .getMethod("getTypes") + .invoke(types) + .asInstanceOf[java.util.Set[Integer]] + .asScala + .map(_.intValue) + .toSet) + .getOrElse(Set.empty[Int]) + RowGroup(block.getRowCount, box, types) + } + } + + private def geographies(wkts: String*): DataFrame = { + val rows = wkts.zipWithIndex.map { case (wkt, id) => + if (wkt == null) s"SELECT $id AS id, ST_GeogFromWKT(NULL, 4326) AS geography" + else s"SELECT $id AS id, ST_GeogFromWKT('$wkt', 4326) AS geography" + } + sparkSession.sql(rows.mkString(" UNION ALL ")) + } + + /** The one row group of the file that holds `wkts` in its column `geography`. */ + private def rowGroupOf(wkts: String*): RowGroup = { + var found: Option[RowGroup] = None + withDirectory { directory => + val path = new File(directory, "data").getPath + writeVersion2(geographies(wkts: _*), path) + val all = rowGroups(path) + assert(all.size == 1) + found = all.headOption + } + found.get + } + + private def near(actual: Double, expected: Double): Boolean = + math.abs(actual - expected) < 1e-9 + + describe("Row group statistics of geography columns in GeoParquet 2 files") { + if (ParquetGeospatialTypes.supported) { + it("gives a row group the bounds and the type of its points, as they are written") { + val group = rowGroupOf("POINT (10 20)", "POINT (-30 5)", "POINT (15 -40)") + assert(group.rows == 3) + // The coordinates of points are in the box as they are, without a margin + assert(group.box.contains(Box(-30, 15, -40, 20))) + assert(group.types == Set(1)) + } + + it("reads the file back as it is read without the statistics") { + withDirectory { directory => + val path = new File(directory, "data").getPath + writeVersion2(geographies("POINT (10 20)", null, "LINESTRING (0 0, 10 10)"), path) + val df = sparkSession.read.format("geoparquet").load(path) + val ewkt = + df.orderBy("id").selectExpr("ST_AsEWKT(geography)").collect().map(_.getString(0)) + assert( + ewkt.toSeq == Seq( + "SRID=4326; POINT (10 20)", + null, + "SRID=4326; LINESTRING (0 0, 10 10)")) + } + } + + it("follows an edge to the north of its end points") { + // The geodesic between two points on the 50th parallel that are 90 degrees apart reaches + // atan(tan(50) / cos(45)), about 59.32 degrees north + val box = rowGroupOf("LINESTRING (0 50, 90 50)").box.get + val north = + math.toDegrees(math.atan(math.tan(math.toRadians(50)) / math.cos(math.Pi / 4))) + assert(box.ymax >= north && box.ymax < north + 1e-6) + assert(box.ymin <= 50 && near(box.ymin, 50)) + assert(box.xmin <= 0 && near(box.xmin, 0)) + assert(box.xmax >= 90 && near(box.xmax, 90)) + } + + it("reaches the pole and all longitudes for a polygon around the pole") { + val group = rowGroupOf("POLYGON ((0 80, 90 80, 180 80, -90 80, 0 80))") + val box = group.box.get + assert(box.ymax == 90) + assert(box.xmin == -180 && box.xmax == 180) + assert(box.ymin <= 80 && near(box.ymin, 80)) + assert(group.types == Set(3)) + } + + it("writes a box across the antimeridian with xmin above xmax") { + val line = rowGroupOf("LINESTRING (170 10, -170 20)").box.get + assert(line.xmin > line.xmax) + assert(line.xmin <= 170 && near(line.xmin, 170)) + assert(line.xmax >= -170 && near(line.xmax, -170)) + assert(line.contains(180, 15) && line.contains(-180, 15) && !line.contains(0, 15)) + + val points = rowGroupOf("POINT (179 1)", "POINT (-179 2)").box.get + assert(points == Box(179, -179, 1, 2)) + } + + it("has a point on the antimeridian in the box as longitude 180 and as -180") { + Seq("POINT (180 5)", "POINT (-180 5)").foreach { wkt => + val box = rowGroupOf(wkt, "POINT (175 6)").box.get + assert(box.contains(180, 5) && box.contains(-180, 5) && box.contains(175, 6)) + assert(!box.contains(0, 5)) + } + } + + it("covers the members of a collection and of multi geographies") { + val collection = + rowGroupOf("GEOMETRYCOLLECTION (POINT (1 2), LINESTRING (3 4, 5 6))") + assert(collection.types == Set(7)) + assert(collection.box.get.contains(1, 2) && collection.box.get.contains(5, 6)) + assert(!collection.box.get.contains(7, 6)) + + val multi = rowGroupOf("MULTIPOINT ((1 2), (-3 4))", "MULTILINESTRING ((5 6, 7 8))") + assert(multi.types == Set(4, 5)) + assert(multi.box.get.contains(-3, 4) && multi.box.get.contains(7, 8)) + } + + it("gives each row group the bounds of its own rows") { + withDirectory { directory => + val path = new File(directory, "data").getPath + writeVersion2( + sparkSession.sql("""SELECT id, ST_GeogFromWKT( + | concat('POINT (', CAST(id * 0.25 AS DOUBLE), ' ', CAST(id * 0.125 AS DOUBLE), ')'), + | 4326) AS geography + |FROM range(600)""".stripMargin), + path, + "parquet.block.size" -> "4096", + "parquet.page.size" -> "512") + val groups = rowGroups(path) + assert(groups.size > 1) + assert(groups.map(_.rows).sum == 600) + var first = 0L + groups.foreach { group => + val last = first + group.rows - 1 + assert( + group.box.contains(Box(first * 0.25, last * 0.25, first * 0.125, last * 0.125))) + assert(group.types == Set(1)) + first = last + 1 + } + } + } + + it("writes the type and no box for empty geographies, and nothing for a row group of nulls") { + val empty = rowGroupOf("POINT EMPTY", "LINESTRING EMPTY") + assert(empty.box.isEmpty) + assert(empty.types == Set(1, 2)) + + val nulls = rowGroupOf(null, null) + assert(nulls == RowGroup(2, None, Set.empty)) + } + + it("writes the type code of a geography with a Z coordinate, and its box of X and Y") { + withDirectory { directory => + val path = new File(directory, "data").getPath + // POINT Z (1 2 3) + val pointZ = "01E9030000000000000000F03F00000000000000400000000000000840" + writeVersion2( + sparkSession.sql(s"SELECT 1 AS id, ST_GeogFromWKB(unhex('$pointZ')) AS geography"), + path) + assert(rowGroups(path) == Seq(RowGroup(1, Some(Box(1, 1, 2, 2)), Set(1001)))) + } + } + + it("covers every vertex of lines and polygons, wherever they are") { + val random = new Random(42) + def ordinate(range: Double): Double = + math.round((random.nextDouble() - 0.5) * 2 * range * 1e6) / 1e6 + val wkts = Seq.fill(60) { + val lon = ordinate(180) + val lat = ordinate(85) + def vertex(): (Double, Double) = { + val x = lon + ordinate(4) + (if (x > 180) x - 360 else if (x < -180) x + 360 else x, lat + ordinate(4)) + } + val vertices = Seq.fill(3)(vertex()) + def text(points: Seq[(Double, Double)]): String = + points.map { case (x, y) => s"$x $y" }.mkString(", ") + val wkt = + if (random.nextBoolean()) s"LINESTRING (${text(vertices)})" + else s"POLYGON ((${text(vertices :+ vertices.head)}))" + wkt -> vertices + } + wkts.grouped(10).foreach { some => + val box = rowGroupOf(some.map(_._1): _*).box.get + some.foreach { case (wkt, vertices) => + vertices.foreach { case (x, y) => + assert(box.contains(x, y), s"$box does not have ($x $y) of $wkt") + } + } + } + } + + it("leaves the statistics of a geometry column to the Parquet library") { + withDirectory { directory => + val path = new File(directory, "data").getPath + writeVersion2( + sparkSession.sql("""SELECT 1 AS id, ST_Point(1, 2) AS geometry, + |ST_GeogFromWKT('POINT (3 4)', 4326) AS geography""".stripMargin), + path) + assert(rowGroups(path, "geometry") == Seq(RowGroup(1, Some(Box(1, 1, 2, 2)), Set(1)))) + assert(rowGroups(path, "geography") == Seq(RowGroup(1, Some(Box(3, 3, 4, 4)), Set(1)))) + } + } + + it("writes no statistics for a column whose Parquet statistics are turned off") { + withDirectory { directory => + val path = new File(directory, "data").getPath + writeVersion2( + geographies("POINT (10 20)"), + path, + "parquet.column.statistics.enabled#geography" -> "false") + assert(rowGroups(path) == Seq(RowGroup(1, None, Set.empty))) + } + } + + it("finds no row groups in a writer of another kind, and writes without statistics then") { + assert(GeographyRowGroupStatistics.rowGroupsOf(new Object).isEmpty) + } + } + } +} diff --git a/spark/common/src/test/scala/org/apache/spark/sql/sedona_sql/types/GeographyBoundsTest.scala b/spark/common/src/test/scala/org/apache/spark/sql/sedona_sql/types/GeographyBoundsTest.scala new file mode 100644 index 00000000000..717d2d6f0c1 --- /dev/null +++ b/spark/common/src/test/scala/org/apache/spark/sql/sedona_sql/types/GeographyBoundsTest.scala @@ -0,0 +1,261 @@ +/* + * 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.spark.sql.sedona_sql.types + +import scala.util.{Random, Try} + +import com.google.common.geometry.{S1Interval, S2LatLngRect} +import org.apache.sedona.common.S2Geography.{WKBReader => GeographyReader} +import org.locationtech.jts.io.{ByteOrderValues, WKBWriter, WKTReader} +import org.scalatest.funsuite.AnyFunSuite + +class GeographyBoundsTest extends AnyFunSuite { + private def wkb(wkt: String, byteOrder: Int = ByteOrderValues.LITTLE_ENDIAN): Array[Byte] = + new WKBWriter(2, byteOrder).write(new WKTReader().read(wkt)) + + private def add(bounds: GeographyBounds, bytes: Array[Byte], offset: Int = 0): Unit = + bounds.add(bytes, offset) + + /** The box of the geographies of `wkts`: west, east, south, north. Null without one. */ + private def box(wkts: String*): Seq[Double] = { + val bounds = new GeographyBounds + wkts.foreach(wkt => add(bounds, wkb(wkt))) + Option(bounds.box()).map(_.toSeq).orNull + } + + private def contains(box: Seq[Double], x: Double, y: Double): Boolean = { + val Seq(west, east, south, north) = box + val inX = if (west <= east) x >= west && x <= east else x >= west || x <= east + inX && y >= south && y <= north + } + + private def near(actual: Double, expected: Double): Boolean = + math.abs(actual - expected) < 1e-9 + + test("has no box without a geography, and none for empty geographies") { + assert(box() == null) + assert(box("POINT EMPTY", "LINESTRING EMPTY", "POLYGON EMPTY") == null) + assert(box("GEOMETRYCOLLECTION EMPTY", "MULTIPOINT EMPTY") == null) + } + + test("gives the box of points in their own coordinates") { + assert(box("POINT (10.1 20.2)") == Seq(10.1, 10.1, 20.2, 20.2)) + assert( + box("POINT (10.1 20.2)", "POINT (-30.3 5)", "POINT (0 -40.4)") == + Seq(-30.3, 10.1, -40.4, 20.2)) + assert(box("POINT (-10 1)", "POINT (-30 2)") == Seq(-30.0, -10.0, 1.0, 2.0)) + assert(box("POINT (1e-10 1)", "POINT (-1e-10 2)") == Seq(-1e-10, 1e-10, 1.0, 2.0)) + } + + test("reads a point in either byte order, from an offset, and with more coordinates") { + val bounds = new GeographyBounds + add(bounds, wkb("POINT (1 2)", ByteOrderValues.BIG_ENDIAN)) + add(bounds, Array[Byte](9, 9, 9, 9) ++ wkb("POINT (3 4)"), offset = 4) + // ISO WKB of POINT ZM (5 6 7 8) + val pointZM = new WKBWriter(4, ByteOrderValues.LITTLE_ENDIAN) + .write(new WKTReader().read("POINT ZM (5 6 7 8)")) + val iso = PublicWkbHeaderAdapter.toIsoWkb(pointZM) + add(bounds, iso) + assert(bounds.box().toSeq == Seq(1.0, 5.0, 2.0, 6.0)) + } + + test("takes the shorter way around the sphere for points on both sides of the antimeridian") { + assert(box("POINT (179 1)", "POINT (-179 2)") == Seq(179.0, -179.0, 1.0, 2.0)) + assert( + box("POINT (170 1)", "POINT (-160 2)", "POINT (175 3)", "POINT (-175 0)") == + Seq(170.0, -160.0, 0.0, 3.0)) + // The way through the prime meridian is the shorter one here + assert(box("POINT (60 1)", "POINT (-60 2)") == Seq(-60.0, 60.0, 1.0, 2.0)) + } + + test("has a point on the antimeridian in the box as longitude 180 and as -180") { + Seq(Seq("POINT (180 5)"), Seq("POINT (-180 5)"), Seq("POINT (-180 5)", "POINT (175 6)")) + .foreach { wkts => + val found = box(wkts: _*) + assert(contains(found, 180, 5) && contains(found, -180, 5), wkts) + assert(!contains(found, 0, 5) && !contains(found, 170, 5), wkts) + } + } + + test("follows the edges of a line") { + val found = box("LINESTRING (0 50, 90 50)") + val north = math.toDegrees(math.atan(math.tan(math.toRadians(50)) / math.cos(math.Pi / 4))) + assert(found(3) >= north && found(3) < north + 1e-6) + assert(found(0) <= 0 && near(found(0), 0) && found(1) >= 90 && near(found(1), 90)) + assert(found(2) <= 50 && near(found(2), 50)) + } + + test("crosses the antimeridian for a line across it") { + val found = box("LINESTRING (170 10, -170 20)") + assert(found(0) > found(1)) + assert(found(0) <= 170 && near(found(0), 170) && found(1) >= -170 && near(found(1), -170)) + } + + test("reaches the pole and all longitudes for a polygon around a pole") { + val north = box("POLYGON ((0 80, 90 80, 180 80, -90 80, 0 80))") + assert(north(0) == -180 && north(1) == 180 && north(3) == 90) + assert(north(2) <= 80 && near(north(2), 80)) + val south = box("POLYGON ((0 -80, -90 -80, 180 -80, 90 -80, 0 -80))") + assert(south(0) == -180 && south(1) == 180 && south(2) == -90) + assert(south(3) >= -80 && near(south(3), -80)) + } + + test("has the vertices of lines and polygons in the box as they are written") { + val wkts = Seq( + "LINESTRING (10.1 20.2, 30.3 40.4)", + "POLYGON ((-5.5 -5.5, 7.7 -5.5, 7.7 8.8, -5.5 -5.5))", + "MULTIPOINT ((100.1 -60.6), (-120.2 70.7))") + val found = box(wkts: _*) + Seq((10.1, 20.2), (30.3, 40.4), (-5.5, -5.5), (7.7, 8.8), (100.1, -60.6), (-120.2, 70.7)) + .foreach { case (x, y) => assert(contains(found, x, y), s"($x $y)") } + } + + test("joins the points with the other geographies") { + val found = box("POINT (-20 -30)", "LINESTRING (10 20, 30 40)") + assert(contains(found, -20, -30) && contains(found, 30, 40)) + assert(near(found(0), -20) && near(found(1), 30) && near(found(2), -30) && near(found(3), 40)) + } + + test("starts again after a reset") { + val bounds = new GeographyBounds + add(bounds, wkb("POINT (1 2)")) + add(bounds, wkb("LINESTRING (170 10, -170 20)")) + bounds.reset() + assert(bounds.box() == null) + add(bounds, wkb("POINT (3 4)")) + assert(bounds.box().toSeq == Seq(3.0, 3.0, 4.0, 4.0)) + } + + test("has no box once a geography cannot be read, until a reset") { + val bounds = new GeographyBounds + add(bounds, wkb("POINT (1 2)")) + // A line that states two points and has the coordinates of none + bounds.add(wkb("LINESTRING (0 0, 1 1)").take(9), 0) + add(bounds, wkb("POINT (3 4)")) + assert(bounds.box() == null) + bounds.reset() + add(bounds, wkb("POINT (3 4)")) + assert(bounds.box().toSeq == Seq(3.0, 3.0, 4.0, 4.0)) + } + + /** + * The bounds that Sedona's reading of `wkt` into its S2 form gives, which is what the functions + * and the predicates of a geography work on. None for a geography that it does not read. + */ + private def reference(wkt: String): Option[S2LatLngRect] = + Try(new GeographyReader().read(wkb(wkt)).region().getRectBound).toOption + + /** + * Asserts that the box of `wkt` has all of its reference, and no more than `slack` degrees on + * any side. + * + * @return + * whether there is a reference for `wkt` + */ + private def assertCovers(wkt: String, slack: Double): Boolean = reference(wkt).exists { rect => + val found = box(wkt) + assert(found != null, wkt) + val Seq(west, east, south, north) = found + assert( + south <= rect.latLo().degrees() && north >= rect.latHi().degrees(), + s"$found $rect $wkt") + assert( + rect.latLo().degrees() - south <= slack && north - rect.latHi().degrees() <= slack, + wkt) + val longitudes = + if (west == -180 && east == 180) S1Interval.full() + else new S1Interval(math.toRadians(west), math.toRadians(east)) + assert(longitudes.contains(rect.lng()), s"$found $rect $wkt") + assert( + math.toDegrees(longitudes.getLength - rect.lng().getLength) <= 2 * slack, + s"$found $rect $wkt") + true + } + + private def wrap(longitude: Double): Double = + if (longitude > 180) longitude - 360 else if (longitude < -180) longitude + 360 else longitude + + private def text(vertices: Seq[(Double, Double)]): String = + vertices.map { case (x, y) => s"${wrap(x)} $y" }.mkString("(", ", ", ")") + + /** A ring around a centre, with its vertices in the order of their direction from it. */ + private def ring(random: Random, radius: Double): Seq[(Double, Double)] = { + val longitude = random.nextDouble() * 360 - 180 + val latitude = (random.nextDouble() * 2 - 1) * (89 - radius) + val count = 3 + random.nextInt(12) + val open = (0 until count).map { i => + val angle = 2 * math.Pi * (i + random.nextDouble() * 0.8) / count + val distance = radius * (0.3 + 0.7 * random.nextDouble()) + (longitude + distance * math.cos(angle), latitude + distance * math.sin(angle)) + } + val vertices = if (random.nextBoolean()) open else open.reverse + vertices :+ vertices.head + } + + test("has the bounds that the S2 form of lines gives, wherever they are") { + val random = new Random(7) + val compared = (0 until 300).count { _ => + val vertices = Seq.fill(2 + random.nextInt(6))( + (random.nextDouble() * 360 - 180, random.nextDouble() * 178 - 89)) + assertCovers(s"LINESTRING ${text(vertices)}", slack = 1e-9) + } + assert(compared == 300) + } + + test("has the bounds that the S2 form of polygons gives, in either direction of the ring") { + val random = new Random(11) + Seq(1.0, 10.0, 40.0, 80.0).foreach { radius => + val compared = (0 until 150).count { _ => + assertCovers(s"POLYGON (${text(ring(random, radius))})", slack = 1e-9) + } + // Sedona may not read a ring that crosses itself on the sphere + assert(compared > 120, s"radius $radius: $compared") + } + } + + test("has the bounds of a polygon whose ring is around more than half of the sphere") { + // A band from 60 degrees south to 60 degrees north over 300 degrees of longitude. The inside + // is the smaller side of the ring: both poles and the longitudes beyond 150. + val band = "POLYGON ((-150 -60, -90 -60, -30 -60, 30 -60, 90 -60, 150 -60, " + + "150 60, 90 60, 30 60, -30 60, -90 60, -150 60, -150 -60))" + assert(box(band) == Seq(-180.0, 180.0, -90.0, 90.0)) + assertCovers(band, slack = 1e-9) + // An edge takes the shorter way between its vertices, so this ring is across the + // antimeridian and 60 degrees of longitude wide + val narrow = "POLYGON ((-150 -80, 150 -80, 150 80, -150 80, -150 -80))" + assert(box(narrow).head > box(narrow)(1)) + assertCovers(narrow, slack = 1e-9) + // A ring along the tenth parallel, around the northern side + assertCovers("POLYGON ((0 10, 90 10, 180 10, -90 10, 0 10))", slack = 1e-9) + assertCovers("POLYGON ((0 10, -90 10, 180 10, 90 10, 0 10))", slack = 1e-9) + } + + test("is within the first ring of a polygon with holes, and has every member of a collection") { + // A hole takes nothing from the bounds here + assertCovers("POLYGON ((0 0, 20 0, 20 20, 0 20, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))", 1e-9) + assertCovers( + "MULTIPOLYGON (((0 0, 20 0, 20 20, 0 0)), ((170 -10, -170 -10, -170 5, 170 -10)))", + 1e-9) + assertCovers( + "GEOMETRYCOLLECTION (POINT (1 2), LINESTRING (3 4, 50 60), " + + "GEOMETRYCOLLECTION (POLYGON ((-5 -5, 7 -5, 7 8, -5 -5))))", + 1e-9) + assertCovers("MULTILINESTRING ((0 50, 90 50), (-100 -20, -110 -30))", 1e-9) + } +} From eed67075982da27d4c0bc89a947e664523f62412 Mon Sep 17 00:00:00 2001 From: Jia Yu Date: Wed, 25 Nov 2026 00:51:30 -0800 Subject: [PATCH 2/3] [GH-3146] Keep the box of a geography row group around what the predicates match A ring that halves the sphere gets the box of the whole sphere: Sedona does not read the inside of such a ring the same way everywhere. A ring without its closing vertex keeps the edge from its last vertex to its first. A coordinate that is not a number is left out by itself. The switch of the statistics of a column is read as the Parquet library reads it. A wide ring becomes a loop of S2, and no reader holds on to the WKB of a geography. --- .../sql/sedona_sql/types/GeographyBounds.java | 211 +++++++++++------- .../GeographyRowGroupStatistics.scala | 24 +- .../GeoParquetGeographyStatisticsSuite.scala | 79 ++++++- .../types/GeographyBoundsTest.scala | 80 +++++++ 4 files changed, 300 insertions(+), 94 deletions(-) diff --git a/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/GeographyBounds.java b/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/GeographyBounds.java index 058d4257936..3ccbb1b3c84 100644 --- a/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/GeographyBounds.java +++ b/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/GeographyBounds.java @@ -18,12 +18,16 @@ */ package org.apache.spark.sql.sedona_sql.types; +import com.google.common.geometry.R1Interval; +import com.google.common.geometry.S1Interval; +import com.google.common.geometry.S2; import com.google.common.geometry.S2EdgeUtil; import com.google.common.geometry.S2LatLng; import com.google.common.geometry.S2LatLngRect; -import java.io.IOException; -import org.apache.sedona.common.S2Geography.WKBReader; -import org.locationtech.jts.io.InStream; +import com.google.common.geometry.S2Loop; +import com.google.common.geometry.S2Point; +import java.util.ArrayList; +import java.util.List; /** * The bounding box, in degrees of longitude and latitude, of geographies with edges on the sphere. @@ -32,9 +36,9 @@ * its western bound is above its eastern bound when it crosses the antimeridian. * *

A point is added from its coordinates, without an object for it. A line and a ring give their - * vertices to the edge bounder of S2, which has the bounds of the edges between them. Only a - * polygon whose ring spans half of all longitudes or more is read into its S2 form, which tells - * which side of such a ring is the inside and whether a pole is in it. + * vertices to the edge bounder of S2, which has the bounds of the edges between them. Only a ring + * that spans half of all longitudes or more becomes a loop of S2, which tells which side of such a + * ring is the inside and whether a pole is in it. */ public final class GeographyBounds { /** @@ -47,9 +51,6 @@ public final class GeographyBounds { /** A little less than pi, so that rounding keeps a ring of half of all longitudes above it. */ private static final double HALF_OF_ALL_LONGITUDES = Math.PI - 1e-9; - private final WKBReader reader = new WKBReader(); - private final Slice slice = new Slice(); - // The points, by the sign of their longitude. The two ranges give the box of the points both // ways around the sphere, in the coordinates that the points have. private double westMin; @@ -87,22 +88,14 @@ public void reset() { public void add(byte[] wkb, int offset) { if (unknown) return; try { - if (!addShapes(wkb, offset)) { - slice.set(wkb, offset); - shapes = shapes.union(reader.read(slice).region().getRectBound()); - } - } catch (Exception | AssertionError e) { + addShapes(wkb, offset); + } catch (RuntimeException | AssertionError e) { // Without the bounds of one geography there is no box for all of them unknown = true; } } - /** - * Adds the points, lines and polygons of a geography from their coordinates. - * - * @return false for a geography that has to be read into its S2 form instead - */ - private boolean addShapes(byte[] wkb, int offset) { + private void addShapes(byte[] wkb, int offset) { int position = offset; long pending = 1; while (pending-- > 0) { @@ -119,7 +112,7 @@ private boolean addShapes(byte[] wkb, int offset) { case 2: { int count = readInt(wkb, position, little); - shapes = shapes.union(edges(wkb, position + 4, count, width, little)); + shapes = shapes.union(edges(wkb, position + 4, count, width, little, false)); position += 4 + count * width; break; } @@ -131,13 +124,7 @@ private boolean addShapes(byte[] wkb, int offset) { int count = readInt(wkb, position, little); // The polygon is within its first ring. The other rings are holes in it. if (ring == 0 && count > 0) { - S2LatLngRect bound = edges(wkb, position + 4, count, width, little); - // The inside of a ring is its smaller side. With edges over less than half of - // all longitudes that side has no pole, and it is within the bounds of the - // edges: the other side has every meridian that the edges do not reach, which - // is more than half of the sphere. - if (bound.lng().getLength() >= HALF_OF_ALL_LONGITUDES) return false; - shapes = shapes.union(bound); + shapes = shapes.union(ring(wkb, position + 4, count, width, little)); } position += 4 + count * width; } @@ -148,53 +135,118 @@ private boolean addShapes(byte[] wkb, int offset) { position += 4; } } - return true; } - /** The bounds of the edges between {@code count} vertices in a row. */ - private static S2LatLngRect edges( - byte[] wkb, int position, int count, int width, boolean little) { - if (count == 0) return S2LatLngRect.empty(); - S2EdgeUtil.RectBounder bounder = new S2EdgeUtil.RectBounder(); + /** + * The bounds of the edges between {@code count} vertices in a row, and with {@code close} of the + * edge from the last of them to the first. A vertex with a coordinate that is not a number has no + * edge, and gives its other coordinate as a point does. + */ + private S2LatLngRect edges( + byte[] wkb, int position, int count, int width, boolean little, boolean close) { + S2EdgeUtil.RectBounder bounder = null; + S2LatLng first = null; for (int at = position, end = position + count * width; at < end; at += width) { - bounder.addPoint( - S2LatLng.fromDegrees(readDouble(wkb, at + 8, little), readDouble(wkb, at, little))); + double longitude = readDouble(wkb, at, little); + double latitude = readDouble(wkb, at + 8, little); + if (Double.isNaN(longitude) || Double.isNaN(latitude)) { + addPoint(longitude, latitude); + } else { + S2LatLng vertex = S2LatLng.fromDegrees(latitude, longitude); + if (bounder == null) { + bounder = new S2EdgeUtil.RectBounder(); + first = vertex; + } + bounder.addPoint(vertex); + } } + if (bounder == null) return S2LatLngRect.empty(); + if (close) bounder.addPoint(first); return bounder.getBound(); } + /** The bounds of the inside of a ring. */ + private S2LatLngRect ring(byte[] wkb, int position, int count, int width, boolean little) { + // The last vertex of a ring of WKB repeats the first. Sedona's own writer of the WKB of a + // geography leaves it out, and the ring still has the edge from its last vertex to its first. + int last = position + (count - 1) * width; + boolean open = + readDouble(wkb, position, little) != readDouble(wkb, last, little) + || readDouble(wkb, position + 8, little) != readDouble(wkb, last + 8, little); + S2LatLngRect bound = edges(wkb, position, count, width, little, open); + // The inside of a ring is its smaller side. With edges over less than half of all longitudes + // that side has no pole, and it is within the bounds of the edges: the other side has every + // meridian that the edges do not reach, which is more than half of the sphere. + if (bound.lng().getLength() < HALF_OF_ALL_LONGITUDES) return bound; + + List vertices = new ArrayList<>(count); + for (int at = position, end = position + count * width; at < end; at += width) { + double longitude = readDouble(wkb, at, little); + double latitude = readDouble(wkb, at + 8, little); + if (Double.isNaN(longitude) || Double.isNaN(latitude)) continue; + S2Point vertex = S2LatLng.fromDegrees(latitude, longitude).toPoint(); + // A loop of S2 has no vertex twice in a row + if (vertices.isEmpty() || !vertex.equalsPoint(vertices.get(vertices.size() - 1))) { + vertices.add(vertex); + } + } + while (vertices.size() > 1 && vertices.get(vertices.size() - 1).equalsPoint(vertices.get(0))) { + vertices.remove(vertices.size() - 1); + } + // Without three vertices a ring has no inside + if (vertices.size() < 3) return bound; + S2Loop loop = new S2Loop(vertices); + double turning = loop.getTurningAngle(); + // The turning angle of a ring that halves the sphere is zero, and rounding gives it either + // sign. Sedona does not read the inside of such a ring the same way everywhere, and its two + // sides together are the sphere. + if (Math.abs(turning) <= 4 * S2.getTurningAngleMaxError(vertices.size())) { + return S2LatLngRect.full(); + } + // The inside of a loop of S2 is on its left. A negative turning angle has the larger side + // there. + if (turning < 0) loop.invert(); + return loop.getRectBound(); + } + + /** + * Adds the coordinates of a point. One that is not a number is left out by itself, as the Parquet + * format has it, and both of them are no numbers for an empty point. + */ private void addPoint(double longitude, double latitude) { - // The coordinates of an empty point are not numbers - if (Double.isNaN(longitude) || Double.isNaN(latitude)) return; - if (longitude < 0) { - if (longitude < westMin) westMin = longitude; - if (longitude > westMax) westMax = longitude; - } else { - if (longitude < eastMin) eastMin = longitude; - if (longitude > eastMax) eastMax = longitude; + if (!Double.isNaN(longitude)) { + if (longitude < 0) { + if (longitude < westMin) westMin = longitude; + if (longitude > westMax) westMax = longitude; + } else { + if (longitude < eastMin) eastMin = longitude; + if (longitude > eastMax) eastMax = longitude; + } + // The antimeridian is longitude 180 and longitude -180 + if (longitude == 180 || longitude == -180) antimeridian = true; + } + if (!Double.isNaN(latitude)) { + if (latitude < latMin) latMin = latitude; + if (latitude > latMax) latMax = latitude; } - if (latitude < latMin) latMin = latitude; - if (latitude > latMax) latMax = latitude; - // The antimeridian is longitude 180 and longitude -180 - if (longitude == 180 || longitude == -180) antimeridian = true; } /** * The box of the geographies added since the last {@link #reset}. * - * @return the western, eastern, southern and northern bound in this order, or null when no - * geography with a coordinate was added or one of them could not be read. The western bound - * is above the eastern bound for a box that crosses the antimeridian. + * @return the western, eastern, southern and northern bound in this order, or null when the + * geographies have no longitude or no latitude, or one of them could not be read. The western + * bound is above the eastern bound for a box that crosses the antimeridian. */ public double[] box() { if (unknown) return null; - boolean points = latMin <= latMax; - if (!points && shapes.isEmpty()) return null; + boolean hasWest = westMin <= westMax; + boolean hasEast = eastMin <= eastMax; + boolean longitudes = hasWest || hasEast; + boolean latitudes = latMin <= latMax; double west = 0; double east = 0; - if (points) { - boolean hasWest = westMin <= westMax; - boolean hasEast = eastMin <= eastMax; + if (longitudes) { west = hasWest ? westMin : eastMin; east = hasEast ? eastMax : westMax; // The other way around the sphere, across the antimeridian, when that is the shorter one @@ -202,14 +254,24 @@ public double[] box() { west = eastMin; east = westMax; } - if (shapes.isEmpty() && !antimeridian) return new double[] {west, east, latMin, latMax}; + } + if (shapes.isEmpty()) { + // A box has both dimensions + if (!longitudes || !latitudes) return null; + if (!antimeridian) return new double[] {west, east, latMin, latMax}; } S2LatLngRect all = shapes; - if (points) { - all = - all.union( - new S2LatLngRect( - S2LatLng.fromDegrees(latMin, west), S2LatLng.fromDegrees(latMax, east))); + if (longitudes || latitudes) { + // Points of which only one coordinate is a number widen that dimension alone + R1Interval latitude = + latitudes + ? new R1Interval(radians(latMin, S2.M_PI_2), radians(latMax, S2.M_PI_2)) + : shapes.lat(); + S1Interval longitude = + longitudes + ? new S1Interval(radians(west, S2.M_PI), radians(east, S2.M_PI)) + : shapes.lng(); + all = all.union(new S2LatLngRect(latitude, longitude)); } all = all.expanded(S2LatLng.fromRadians(MARGIN, MARGIN)); double south = Math.max(-90, all.latLo().degrees()); @@ -223,6 +285,10 @@ public double[] box() { }; } + private static double radians(double degrees, double limit) { + return Math.max(-limit, Math.min(limit, Math.toRadians(degrees))); + } + private static int readInt(byte[] bytes, int at, boolean little) { int value = 0; for (int i = 0; i < 4; i++) { @@ -238,25 +304,4 @@ private static double readDouble(byte[] bytes, int at, boolean little) { } return Double.longBitsToDouble(value); } - - /** The bytes of an array from an offset on, for a reader of WKB. */ - private static final class Slice implements InStream { - private byte[] bytes; - private int position; - - void set(byte[] bytes, int offset) { - this.bytes = bytes; - this.position = offset; - } - - @Override - public int read(byte[] buffer) throws IOException { - if (buffer.length > bytes.length - position) { - throw new IOException("The WKB ends before the geography does"); - } - System.arraycopy(bytes, position, buffer, 0, buffer.length); - position += buffer.length; - return buffer.length; - } - } } diff --git a/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeographyRowGroupStatistics.scala b/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeographyRowGroupStatistics.scala index 526a8f5864d..b9a399e6c13 100644 --- a/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeographyRowGroupStatistics.scala +++ b/spark/common/src/main/scala/org/apache/spark/sql/execution/datasources/geoparquet/GeographyRowGroupStatistics.scala @@ -94,17 +94,23 @@ object GeographyRowGroupStatistics extends Logging { */ case class Column(box: Option[Array[Double]], types: Set[Int]) - /** - * The key of the Parquet library that turns the statistics of the columns on and off, and with - * `#` and the name of a column after it those of that column. - */ + /** The key of the Parquet library that turns the statistics of the columns on and off. */ private val STATISTICS_ENABLED = "parquet.column.statistics.enabled" - /** Whether a write with `configuration` collects the statistics of `column`. */ - def enabled(configuration: Configuration, column: String): Boolean = - library.isDefined && Option(configuration.get(STATISTICS_ENABLED + "#" + column)) - .map(_.trim.toBoolean) - .getOrElse(configuration.getBoolean(STATISTICS_ENABLED, true)) + /** + * Whether a write with `configuration` collects the statistics of `column`, a column at the + * root of the schema. It follows the switch of the Parquet library for the statistics of that + * column, as that library reads it. + */ + def enabled(configuration: Configuration, column: String): Boolean = library.isDefined && { + // The key of one column has # and the path of the column after it, with a dot between the + // fields of the path. The path of a column at the root is its name, and a name with a dot + // is the path of a nested field, so such a column has no key of its own. + val key = STATISTICS_ENABLED + "#" + column + val ofColumn = !column.contains(".") && configuration.get(key) != null + // A value that is no boolean is the default of the Parquet library, which is true + configuration.getBoolean(if (ofColumn) key else STATISTICS_ENABLED, true) + } /** * The classes of the geospatial statistics, which parquet-java has since 1.16.0. Sedona also diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetGeographyStatisticsSuite.scala b/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetGeographyStatisticsSuite.scala index 69544bb9feb..f23afe4df3f 100644 --- a/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetGeographyStatisticsSuite.scala +++ b/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetGeographyStatisticsSuite.scala @@ -25,10 +25,11 @@ import org.apache.commons.io.FileUtils import org.apache.hadoop.conf.Configuration import org.apache.hadoop.fs.Path import org.apache.parquet.hadoop.ParquetFileReader -import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData +import org.apache.parquet.hadoop.metadata.{ColumnChunkMetaData, ColumnPath} import org.apache.parquet.hadoop.util.HadoopInputFile import org.apache.spark.sql.DataFrame import org.apache.spark.sql.execution.datasources.geoparquet.{GeographyRowGroupStatistics, ParquetGeospatialTypes} +import org.apache.spark.sql.sedona_sql.types.SpatialTypeSupport import scala.collection.JavaConverters._ import scala.util.Random @@ -78,7 +79,8 @@ class GeoParquetGeographyStatisticsSuite extends TestBaseScala { def number(box: AnyRef, name: String): Double = box.getClass.getMethod(name).invoke(box).asInstanceOf[Double] blocks.map { block => - val chunk = block.getColumns.asScala.find(_.getPath.toDotString == column).get + // A column at the root, whose name may have a dot + val chunk = block.getColumns.asScala.find(_.getPath == ColumnPath.get(column)).get val found = Option(statistics.invoke(chunk)) val box = found .flatMap(value => Option(value.getClass.getMethod("getBoundingBox").invoke(value))) @@ -304,6 +306,79 @@ class GeoParquetGeographyStatisticsSuite extends TestBaseScala { } } + it("has the points that ST_Intersects finds in a polygon in the box of the polygon") { + // A ring on a great circle, whose two sides are of one size, in both directions, and a + // ring that Sedona's own writer left open: its last edge is between its last vertex and + // its first, and goes north of both + // POLYGON ((-60 50, 0 -10, 60 50)), with no fourth vertex + val open = "010300000001000000030000000000000000004EC00000000000004940" + + "000000000000000000000000000024C00000000000004E400000000000004940" + val cases = Seq( + "ST_GeogFromWKT('POLYGON ((0 0, 90 10, 180 0, -90 -10, 0 0))', 4326)" -> "POINT (0 85)", + "ST_GeogFromWKT('POLYGON ((0 0, 90 10, 180 0, -90 -10, 0 0))', 4326)" -> "POINT (0 -85)", + "ST_GeogFromWKT('POLYGON ((0 0, -90 -10, 180 0, 90 10, 0 0))', 4326)" -> "POINT (0 85)", + "ST_GeogFromWKT('POLYGON ((0 0, -90 -10, 180 0, 90 10, 0 0))', 4326)" -> "POINT (0 -85)") ++ { + // Spark's native geography type does not take a ring that is not closed + if (SpatialTypeSupport.usesNativeTypes) Seq.empty + else Seq(s"ST_GeogFromWKB(unhex('$open'))" -> "POINT (0 60)") + } + cases.foreach { case (polygon, point) => + withDirectory { directory => + val path = new File(directory, "data").getPath + writeVersion2(sparkSession.sql(s"SELECT 1 AS id, $polygon AS geography"), path) + val matched = sparkSession.read + .format("geoparquet") + .load(path) + .where(s"ST_Intersects(geography, ST_GeogFromWKT('$point', 4326))") + .count() + val Array(x, y) = + point.stripPrefix("POINT (").stripSuffix(")").split(" ").map(_.toDouble) + val box = rowGroups(path).head.box.get + assert(matched == 0 || box.contains(x, y), s"$box of $polygon has no $point") + // The point is north of the vertices of the open ring, and within its last edge + assert(matched == 1 || !polygon.contains(open), s"$polygon has no $point") + } + } + } + + it("takes the switch of the statistics of a column from the path that the key names") { + withDirectory { directory => + val path = new File(directory, "data").getPath + // The Parquet library reads sample.location as the field location of the column + // sample, and not as the column of that name + writeVersion2( + sparkSession.sql("""SELECT 1 AS id, named_struct('location', 7) AS sample, + |ST_GeogFromWKT('POINT (23 45)', 4326) AS `sample.location`""".stripMargin), + path, + "parquet.column.statistics.enabled" -> "false", + "parquet.column.statistics.enabled#sample.location" -> "true") + assert(rowGroups(path, "sample.location") == Seq(RowGroup(1, None, Set.empty))) + } + } + + it("reads the value of the switch of the statistics as the Parquet library reads it") { + // A value that is no boolean leaves the statistics on, as they are without the key + Seq("", "yes", " TRUE ").foreach { value => + withDirectory { directory => + val path = new File(directory, "data").getPath + writeVersion2( + geographies("POINT (10 20)"), + path, + "parquet.column.statistics.enabled#geography" -> value) + assert(rowGroups(path).head.box.contains(Box(10, 10, 20, 20)), s"'$value'") + } + } + withDirectory { directory => + val path = new File(directory, "data").getPath + writeVersion2( + geographies("POINT (10 20)"), + path, + "parquet.column.statistics.enabled" -> "false", + "parquet.column.statistics.enabled#geography" -> "true") + assert(rowGroups(path).head.box.contains(Box(10, 10, 20, 20))) + } + } + it("finds no row groups in a writer of another kind, and writes without statistics then") { assert(GeographyRowGroupStatistics.rowGroupsOf(new Object).isEmpty) } diff --git a/spark/common/src/test/scala/org/apache/spark/sql/sedona_sql/types/GeographyBoundsTest.scala b/spark/common/src/test/scala/org/apache/spark/sql/sedona_sql/types/GeographyBoundsTest.scala index 717d2d6f0c1..eda09e6d07c 100644 --- a/spark/common/src/test/scala/org/apache/spark/sql/sedona_sql/types/GeographyBoundsTest.scala +++ b/spark/common/src/test/scala/org/apache/spark/sql/sedona_sql/types/GeographyBoundsTest.scala @@ -18,6 +18,8 @@ */ package org.apache.spark.sql.sedona_sql.types +import java.nio.{ByteBuffer, ByteOrder} + import scala.util.{Random, Try} import com.google.common.geometry.{S1Interval, S2LatLngRect} @@ -39,6 +41,39 @@ class GeographyBoundsTest extends AnyFunSuite { Option(bounds.box()).map(_.toSeq).orNull } + /** The WKB of a point with any coordinates, also ones that are not numbers. */ + private def pointWkb(x: Double, y: Double): Array[Byte] = + ByteBuffer + .allocate(21) + .order(ByteOrder.LITTLE_ENDIAN) + .put(1.toByte) + .putInt(1) + .putDouble(x) + .putDouble(y) + .array() + + /** + * The WKB of a line or a polygon with the vertices of `rings` as they are given: a ring is not + * closed for the caller, and a coordinate may be no number. + */ + private def shapeWkb(typeCode: Int, rings: Seq[(Double, Double)]*): Array[Byte] = { + val size = 5 + (if (typeCode == 3) 4 else 0) + rings.map(4 + _.size * 16).sum + val buffer = ByteBuffer.allocate(size).order(ByteOrder.LITTLE_ENDIAN) + buffer.put(1.toByte).putInt(typeCode) + if (typeCode == 3) buffer.putInt(rings.size) + rings.foreach { ring => + buffer.putInt(ring.size) + ring.foreach { case (x, y) => buffer.putDouble(x).putDouble(y) } + } + buffer.array() + } + + private def boxOf(wkbs: Array[Byte]*): Seq[Double] = { + val bounds = new GeographyBounds + wkbs.foreach(add(bounds, _)) + Option(bounds.box()).map(_.toSeq).orNull + } + private def contains(box: Seq[Double], x: Double, y: Double): Boolean = { val Seq(west, east, south, north) = box val inX = if (west <= east) x >= west && x <= east else x >= west || x <= east @@ -258,4 +293,49 @@ class GeographyBoundsTest extends AnyFunSuite { 1e-9) assertCovers("MULTILINESTRING ((0 50, 90 50), (-100 -20, -110 -30))", 1e-9) } + + test( + "is the whole sphere for a ring that halves the sphere, whose inside Sedona reads both ways") { + // The four vertices are on one great circle, so the two sides of the ring are of one size. + // Sedona's functions do not agree on the side that is the inside of such a ring. + val sphere = Seq(-180.0, 180.0, -90.0, 90.0) + assert(box("POLYGON ((0 0, 90 10, 180 0, -90 -10, 0 0))") == sphere) + assert(box("POLYGON ((0 0, -90 -10, 180 0, 90 10, 0 0))") == sphere) + // The equator + assert(box("POLYGON ((0 0, 90 0, 180 0, -90 0, 0 0))") == sphere) + } + + test("has the edge that closes a ring whose last vertex is not its first") { + // Sedona's own writer of the WKB of a geography leaves the last vertex of a ring out. The + // edge between the two vertices on the 50th parallel reaches atan(tan(50) / cos(60)). + val north = math.toDegrees(math.atan(math.tan(math.toRadians(50)) / 0.5)) + val open = boxOf(shapeWkb(3, Seq((-60.0, 50.0), (0.0, -10.0), (60.0, 50.0)))) + assert(open(3) >= north && open(3) < north + 1e-6) + assert(open == box("POLYGON ((-60 50, 0 -10, 60 50, -60 50))")) + // A ring around the pole, which takes the other way to its bounds + val pole = boxOf(shapeWkb(3, Seq((0.0, 80.0), (90.0, 80.0), (180.0, 80.0), (-90.0, 80.0)))) + assert(pole == box("POLYGON ((0 80, 90 80, 180 80, -90 80, 0 80))")) + assert(pole(3) == 90) + // The line of the same vertices has no such edge + val line = boxOf(shapeWkb(2, Seq((-60.0, 50.0), (0.0, -10.0), (60.0, 50.0)))) + assert(line(3) < 51) + } + + test("takes a coordinate that is a number from a point whose other coordinate is none") { + val nan = Double.NaN + assert(boxOf(pointWkb(75, nan), pointWkb(10, 20)) == Seq(10.0, 75.0, 20.0, 20.0)) + assert(boxOf(pointWkb(nan, 30), pointWkb(10, 20)) == Seq(10.0, 10.0, 20.0, 30.0)) + assert(boxOf(pointWkb(75, nan), pointWkb(nan, 30)) == Seq(75.0, 75.0, 30.0, 30.0)) + // A box has both dimensions + assert(boxOf(pointWkb(75, nan)) == null) + assert(boxOf(pointWkb(nan, 30)) == null) + // With a line, whose bounds S2 gives + val withLine = boxOf(pointWkb(75, nan), wkb("LINESTRING (10 20, 30 40)")) + assert(near(withLine(0), 10) && near(withLine(1), 75)) + assert(near(withLine(2), 20) && near(withLine(3), 40)) + // A vertex of a line, which takes no part in the edges of the line + val vertex = boxOf(shapeWkb(2, Seq((10.0, 20.0), (75.0, nan), (30.0, 40.0)))) + assert(near(vertex(0), 10) && near(vertex(1), 75)) + assert(near(vertex(2), 20) && near(vertex(3), 40)) + } } From a20095b4706185618aa4512b0ab5ab304a126ada Mon Sep 17 00:00:00 2001 From: Jia Yu Date: Wed, 25 Nov 2026 13:06:48 -0800 Subject: [PATCH 3/3] [GH-3146] Keep points on both longitudes of the antimeridian in the box of a geography row group A row group with a point on longitude 180, a point on longitude -180 and no other point had the longitudes of its points from 180 eastwards to -180. S2 reads the interval from pi to -pi as one without a longitude, so the box of the row group was the box of its lines and polygons alone, and the two points were outside of it. The interval is now the antimeridian. --- .../sql/sedona_sql/types/GeographyBounds.java | 15 ++++-- .../GeoParquetGeographyStatisticsSuite.scala | 5 ++ .../types/GeographyBoundsTest.scala | 53 +++++++++++++++++++ 3 files changed, 69 insertions(+), 4 deletions(-) diff --git a/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/GeographyBounds.java b/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/GeographyBounds.java index 3ccbb1b3c84..9fc0190bddb 100644 --- a/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/GeographyBounds.java +++ b/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/GeographyBounds.java @@ -267,10 +267,7 @@ public double[] box() { latitudes ? new R1Interval(radians(latMin, S2.M_PI_2), radians(latMax, S2.M_PI_2)) : shapes.lat(); - S1Interval longitude = - longitudes - ? new S1Interval(radians(west, S2.M_PI), radians(east, S2.M_PI)) - : shapes.lng(); + S1Interval longitude = longitudes ? longitudes(west, east) : shapes.lng(); all = all.union(new S2LatLngRect(latitude, longitude)); } all = all.expanded(S2LatLng.fromRadians(MARGIN, MARGIN)); @@ -285,6 +282,16 @@ public double[] box() { }; } + /** The longitudes from {@code west} eastwards to {@code east}, both in degrees. */ + private static S1Interval longitudes(double west, double east) { + double lo = radians(west, S2.M_PI); + double hi = radians(east, S2.M_PI); + // From longitude 180 to longitude -180 is the antimeridian alone, which points on both of + // them give. S2 reads an interval from pi to -pi as one without a longitude. + if (lo == S2.M_PI && hi == -S2.M_PI) return S1Interval.fromPoint(S2.M_PI); + return new S1Interval(lo, hi); + } + private static double radians(double degrees, double limit) { return Math.max(-limit, Math.min(limit, Math.toRadians(degrees))); } diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetGeographyStatisticsSuite.scala b/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetGeographyStatisticsSuite.scala index f23afe4df3f..52704837c52 100644 --- a/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetGeographyStatisticsSuite.scala +++ b/spark/common/src/test/scala/org/apache/sedona/sql/GeoParquetGeographyStatisticsSuite.scala @@ -194,6 +194,11 @@ class GeoParquetGeographyStatisticsSuite extends TestBaseScala { assert(box.contains(180, 5) && box.contains(-180, 5) && box.contains(175, 6)) assert(!box.contains(0, 5)) } + // Points on both of them, in a row group with a line that is elsewhere + val both = + rowGroupOf("POINT (-180 55)", "POINT (180 80)", "LINESTRING (10 1, 20 2)").box.get + assert(both.contains(-180, 55) && both.contains(180, 80) && both.contains(20, 2)) + assert(!both.contains(0, 30)) } it("covers the members of a collection and of multi geographies") { diff --git a/spark/common/src/test/scala/org/apache/spark/sql/sedona_sql/types/GeographyBoundsTest.scala b/spark/common/src/test/scala/org/apache/spark/sql/sedona_sql/types/GeographyBoundsTest.scala index eda09e6d07c..88c866b151a 100644 --- a/spark/common/src/test/scala/org/apache/spark/sql/sedona_sql/types/GeographyBoundsTest.scala +++ b/spark/common/src/test/scala/org/apache/spark/sql/sedona_sql/types/GeographyBoundsTest.scala @@ -128,6 +128,59 @@ class GeographyBoundsTest extends AnyFunSuite { } } + test("has points on both longitudes of the antimeridian in the box with other geographies") { + val line = "LINESTRING (10 1, 20 2)" + Seq( + Seq("POINT (-180 55)", "POINT (180 80)", line), + Seq(line, "POINT (180 80)", "POINT (-180 55)"), + Seq("POINT (-180 55)", "POINT (180 80)"), + Seq("MULTIPOINT ((180 80), (-180 55))", "POLYGON ((10 1, 20 1, 20 2, 10 1))")).foreach { + wkts => + val found = box(wkts: _*) + assert(contains(found, 180, 80) && contains(found, -180, 55), wkts) + } + val found = box("POINT (-180 55)", "POINT (180 80)", line) + assert(contains(found, 10, 1) && contains(found, 20, 2)) + // From the line to the antimeridian, the shorter way + assert(contains(found, 100, 30) && !contains(found, 0, 30) && !contains(found, -90, 30)) + // A point with no latitude has its longitude there as well + val nan = Double.NaN + val partial = boxOf(pointWkb(-180, nan), pointWkb(180, nan), wkb(line)) + assert(contains(partial, 180, 1) && contains(partial, -180, 2)) + } + + test("has every point and vertex in the box, also on the antimeridian and at a pole") { + val random = new Random(7) + val special = + Seq(-180.0, 180.0, 0.0, -0.0, Math.nextDown(180.0), Math.nextUp(-180.0), 90.0) + def longitude(): Double = + if (random.nextInt(3) == 0) special(random.nextInt(special.size)) + else random.nextDouble() * 360 - 180 + def latitude(): Double = random.nextInt(8) match { + case 0 => 90 + case 1 => -90 + case _ => random.nextDouble() * 180 - 90 + } + (1 to 2000).foreach { _ => + // Every fourth time the points are on the antimeridian alone, with either longitude + val antimeridian = random.nextInt(4) == 0 + val points = Seq.fill(random.nextInt(5))( + (if (antimeridian) special(random.nextInt(2)) else longitude(), latitude())) + val line = Seq.fill(if (random.nextBoolean()) 2 + random.nextInt(3) else 0)( + (longitude(), random.nextDouble() * 160 - 80)) + val wkbs = points.map { case (x, y) => + pointWkb(x, y) + } ++ + (if (line.isEmpty) Nil else Seq(shapeWkb(2, line))) + if (wkbs.nonEmpty) { + val found = boxOf(random.shuffle(wkbs): _*) + (points ++ line).foreach { case (x, y) => + assert(contains(found, x, y), s"($x $y) of $points and $line in $found") + } + } + } + } + test("follows the edges of a line") { val found = box("LINESTRING (0 50, 90 50)") val north = math.toDegrees(math.atan(math.tan(math.toRadians(50)) / math.cos(math.Pi / 4)))