Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/tutorial/files/geoparquet-sedona-spark.md
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,8 @@ Set `geoparquet.crs` or `geoparquet.crs.<column_name>` 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#<column_name>` 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.<column_name>` 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.
Expand Down
2 changes: 2 additions & 0 deletions docs/tutorial/files/geoparquet-sedona-spark.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -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#<column_name>` 设为 `false` 即可关闭这些统计信息,与关闭 Parquet 库自身的统计信息相同。加密文件不带这些统计信息。

地理列的 CRS 遵循几何列的规则,`geoparquet.crs` 和 `geoparquet.crs.<column_name>` 同样适用。在 Spark 4.1 上有一点不同:没有 SRID 的地理对象按 OGC:CRS84 写出,文件中没有任何地理对象的列也是如此。

`GEOGRAPHY` 逻辑类型要求使用地理 CRS,经度范围为 -180 到 180,纬度范围为 -90 到 90。Spark 4.1 上 Sedona 自有的地理类型接受任意 SRID 和任意坐标,因此如果地理列的 CRS 是投影 CRS,或者某个地理对象超出上述范围,写入会失败。
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,314 @@
/*
* 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.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 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.
* 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.
*
* <p>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 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 {
/**
* 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;

// 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 {
addShapes(wkb, offset);
} catch (RuntimeException | AssertionError e) {
// Without the bounds of one geography there is no box for all of them
unknown = true;
}
}

private void 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, false));
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) {
shapes = shapes.union(ring(wkb, position + 4, count, width, little));
}
position += 4 + count * width;
}
break;
}
default:
pending += readInt(wkb, position, little);
position += 4;
}
}
}

/**
* 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) {
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<S2Point> 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) {
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;
}
}

/**
* 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 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 hasWest = westMin <= westMax;
boolean hasEast = eastMin <= eastMax;
boolean longitudes = hasWest || hasEast;
boolean latitudes = latMin <= latMax;
double west = 0;
double east = 0;
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
if (hasWest && hasEast && (180 - eastMin) + (westMax + 180) < east - west) {
west = eastMin;
east = westMax;
}
}
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 (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 ? longitudes(west, east) : shapes.lng();
all = all.union(new S2LatLngRect(latitude, longitude));
}
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
};
}

/** 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)));
}

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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand All @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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 =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
Loading
Loading