You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sedona.apache.org by ji...@apache.org on 2026/09/15 06:01:23 UTC
(sedona) branch master updated: [GH-3370] GeoPandas: add distributed coverage simplification (#3371)
This is an automated email from the ASF dual-hosted git repository.
jiayuasu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sedona.git
The following commit(s) were added to refs/heads/master by this push:
new 8356b79da19 [GH-3370] GeoPandas: add distributed coverage simplification (#3371)
8356b79da19 is described below
commit 8356b79da19a0f8816794cf7a24210794a96f53a
Author: Jia Yu <ji...@apache.org>
AuthorDate: Mon Sep 14 23:01:16 2026 -0700
[GH-3370] GeoPandas: add distributed coverage simplification (#3371)
---
docs/setup/release-notes.md | 1 +
docs/tutorial/geopandas-api.md | 42 ++
docs/tutorial/geopandas-api.zh.md | 31 ++
python/sedona/spark/geopandas/_coverage.py | 510 +++++++++++++++++++++++
python/sedona/spark/geopandas/base.py | 87 ++++
python/sedona/spark/geopandas/geoseries.py | 47 +++
python/tests/geopandas/test_coverage.py | 358 ++++++++++++++++
python/tests/geopandas/test_simplify_coverage.py | 268 ++++++++++++
8 files changed, 1344 insertions(+)
diff --git a/docs/setup/release-notes.md b/docs/setup/release-notes.md
index 18bba8a0a95..e41d9084517 100644
--- a/docs/setup/release-notes.md
+++ b/docs/setup/release-notes.md
@@ -67,6 +67,7 @@
* [<a href='https://github.com/apache/sedona/issues/3288'>GH-3288</a>] - Implement `GeoDataFrame.from_dict` for in-memory dictionaries
* [<a href='https://github.com/apache/sedona/issues/3344'>GH-3344</a>] - Expose `SpatialIndex.valid_query_predicates`
* [<a href='https://github.com/apache/sedona/issues/3357'>GH-3357</a>] - Implement `list_layers` for GeoPackage using the native Spark reader
+* [<a href='https://github.com/apache/sedona/issues/3370'>GH-3370</a>] - Add distributed `simplify_coverage` for GeoSeries and GeoDataFrame, using reliable Spark checkpoints
### Bug Fixes
diff --git a/docs/tutorial/geopandas-api.md b/docs/tutorial/geopandas-api.md
index cb16b69a0b0..d3d8996e873 100644
--- a/docs/tutorial/geopandas-api.md
+++ b/docs/tutorial/geopandas-api.md
@@ -348,6 +348,8 @@ The GeoPandas API for Apache Sedona implements the most commonly used GeoSeries
coverages
- `invalid_coverage_edges()` - Return per-row invalid coverage edges,
optionally detecting narrow gaps
+- `simplify_coverage()` - Simplify matching polygon boundaries together using
+ distributed spatial joins and reliable checkpoints
- `sample_points()` - Sample polygons by area and lines by length with native
distributed expressions
- `GeoSeries.explode()` and `GeoDataFrame.explode()` - Expand multipart
@@ -380,6 +382,46 @@ reduction and returns one Python `bool`. Dense or highly overlapping coverages,
and larger `gap_width` values, can increase each target's candidate array and
executor memory use. `gap_width` must be finite and non-negative.
+`simplify_coverage(tolerance, simplify_boundary=True)` is available since
+v2.0.0. It removes shared vertices consistently across adjacent polygons.
+The input must be a valid, finite, edge-matched 2D Polygon/MultiPolygon
+coverage. Nulls and empty polygons are preserved; non-polygonal geometries,
+Z/M coordinates, invalid polygons and repeated nonclosing ring vertices are
+rejected. Empty interior rings are rejected, while empty polygons and empty
+MultiPolygon members are preserved. Full coverage validity is a precondition,
+not an automatic check.
+The result is an unnamed GeoSeries preserving every index level and CRS.
+
+Unlike most geometry methods, this operation runs Spark jobs eagerly until
+its conservative simplification rules accept no more edits. It requires
+Spark Classic and a checkpoint directory accessible to every executor:
+
+```python
+# Use a writable shared filesystem on a cluster; a local directory works
+# only in local Spark mode.
+spark.sparkContext.setCheckpointDir("hdfs:///user/me/coverage-checkpoints")
+simplified = coverage.simplify_coverage(0.1, simplify_boundary=False)
+```
+
+Intermediate checkpoints are cleaned after their successors are materialized.
+The final checkpoint must remain available while the result or its derived
+DataFrames are used. Its files follow Spark's checkpoint cleanup policy; the
+method does not delete the configured directory or require a `close()` call.
+
+Tolerance is a finite, non-negative scalar: a vertex's local triangle area
+must not exceed `tolerance ** 2`. It is not a maximum displacement bound.
+Zero can remove collinear vertices. Setting `simplify_boundary=False` locks
+the exterior coverage boundary. The algorithm can retain more vertices than
+GeoPandas/GEOS and never deletes rings, holes or parts; exact vertex-selection
+parity is not promised.
+
+Geometry stays distributed, but long rings, dense spatial matches and many
+synchronization rounds can be expensive. Reconstruction uses arrays per ring
+and original geometry. The 100,000-coordinate admission limit per geometry
+is not a memory guarantee: long rings can exhaust executor memory below that
+limit. No geometry arrays for the full coverage or whole neighborhoods are
+collected.
+
`hilbert_distance()` keeps its per-row ordering keys distributed and uses only
native Spark expressions. When `total_bounds` is omitted, one distributed
aggregation derives the extent of all envelope midpoints; only that bounded
diff --git a/docs/tutorial/geopandas-api.zh.md b/docs/tutorial/geopandas-api.zh.md
index 3751ba81473..9007652c8aa 100644
--- a/docs/tutorial/geopandas-api.zh.md
+++ b/docs/tutorial/geopandas-api.zh.md
@@ -344,6 +344,7 @@ Apache Sedona 的 GeoPandas API 已实现最常用的 GeoSeries 与 GeoDataFrame
- `make_valid()` —— 几何校验与修复
- `is_valid_coverage()` —— 校验多边形覆盖的内部是否互不重叠、共享边界是否完全匹配
- `invalid_coverage_edges()` —— 按输入行返回导致覆盖无效的边,并可选择检测狭窄间隙
+- `simplify_coverage()` —— 使用分布式空间连接和可靠检查点,一致地简化多边形共享边界
- `sample_points()` —— 使用原生分布式表达式按面积对多边形采样、按长度对线采样
- `GeoSeries.explode()` 与 `GeoDataFrame.explode()` —— 将多部件几何展开为多行,
其中 GeoDataFrame 方法会保留对应的属性列
@@ -371,6 +372,36 @@ invalid_edges = with_gap.invalid_coverage_edges(gap_width=0.2)
在高密度或大量重叠的覆盖中,或 `gap_width` 较大时,每个目标的候选数组和
executor 内存开销都会增加。`gap_width` 必须是有限的非负数。
+自 v2.0.0 起,`simplify_coverage(tolerance, simplify_boundary=True)` 可以
+一致地删除相邻多边形的共享顶点。输入必须是有效、坐标有限、边界完全匹配的
+二维 Polygon/MultiPolygon 覆盖。缺失值和空多边形会保留;非多边形、Z/M
+坐标、无效多边形以及环内非闭合位置的重复顶点会被拒绝。空的内环也会被拒绝,
+但空多边形和 MultiPolygon 中的空部件会被保留。完整覆盖的有效性是
+使用前提,并不会自动检查。结果是无名称的 GeoSeries,保留所有索引级别和 CRS。
+
+与多数几何方法不同,该操作会立即执行 Spark 作业,直到保守简化规则不再接受
+任何修改。它需要 Spark Classic,以及所有 executor 都能访问的检查点目录:
+
+```python
+# 集群上使用可写的共享文件系统;本地目录仅适用于 Spark 本地模式。
+spark.sparkContext.setCheckpointDir("hdfs:///user/me/coverage-checkpoints")
+simplified = coverage.simplify_coverage(0.1, simplify_boundary=False)
+```
+
+后续检查点物化完成后,中间检查点会被清理。在使用结果或其派生 DataFrame
+期间,最终检查点必须保持可用。其文件遵循 Spark 的检查点清理策略;该方法
+不会删除配置的根目录,也不要求用户调用 `close()`。
+
+容差必须是有限的非负标量:候选顶点的局部三角形面积不得超过
+`tolerance ** 2`。这不是最大位移上限。零容差仍可删除共线顶点;
+`simplify_boundary=False` 会固定覆盖的外部边界。该算法可能比 GeoPandas/GEOS
+保留更多顶点,且不会删除环、孔洞或多边形部件;不保证选择完全相同的顶点。
+
+几何数据保持分布式执行,但长环、密集空间匹配和大量同步轮次的开销可能很高。
+重建过程按环和原始几何构造数组。每个几何最多 100,000 个坐标的准入限制不是
+内存安全保证:低于此限制的长环仍可能耗尽 executor 内存。实现不会把完整覆盖
+或整个邻域收集成几何数组。
+
`hilbert_distance()` 使用原生 Spark 表达式,并让逐行排序键保持分布式执行。
未提供 `total_bounds` 时,该方法会通过一次分布式聚合计算所有包围盒中点的
范围,只有这个有界摘要会返回 driver。由于 Spark 没有无符号整数类型,
diff --git a/python/sedona/spark/geopandas/_coverage.py b/python/sedona/spark/geopandas/_coverage.py
new file mode 100644
index 00000000000..16caddf9760
--- /dev/null
+++ b/python/sedona/spark/geopandas/_coverage.py
@@ -0,0 +1,510 @@
+# 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.
+
+"""Conservative distributed coverage simplification using spatial joins.
+
+Coordinates and current/proposed segments stay in Spark. Reconstruction collects
+only each admitted ring/polygon, never a whole coverage or neighborhood. Inputs
+must form a valid edge-matched coverage; that cross-row precondition is not
+validated here. Ring/part deletion and JTS-equivalent output are not promised.
+"""
+
+import logging
+import math
+
+from pyspark.sql import DataFrame, Window
+from pyspark.sql import functions as F
+from pyspark.sql.types import LongType
+from pyspark.sql.utils import is_remote
+
+from sedona.spark.sql.types import GeometryType
+
+
+class _Checkpoints:
+ """Own only the reliable checkpoint files made by one invocation.
+
+ Spark allocates a unique rdd-N path for each raw checkpoint DataFrame. Never
+ list or delete the configured root: other operations can use it concurrently.
+ The returned output is detached from this owner and follows Spark/user
+ checkpoint retention. As with any reliable Spark checkpoint, its files must
+ remain available for as long as callers use the output.
+ """
+
+ def __init__(self, context):
+ self._context = context
+ self._paths = {}
+
+ def save(self, frame):
+ saved = frame.checkpoint(eager=True)
+ # Use the raw LogicalRDD, not DataFrame.rdd (which adds a Python RDD).
+ path = saved._jdf.queryExecution().analyzed().rdd().getCheckpointFile().get()
+ self._paths[id(saved)] = path
+ return saved
+
+ def keep(self, frame):
+ self._paths.pop(id(frame))
+ return frame
+
+ def release(self, frame):
+ path = self._paths.pop(id(frame))
+ self._delete(path)
+
+ def _delete(self, path):
+ # Paths originate only from successfully completed checkpoints above.
+ # Do not mask a validation or Spark failure if storage cleanup fails.
+ try:
+ jpath = self._context._jvm.org.apache.hadoop.fs.Path(path)
+ fs = jpath.getFileSystem(self._context._jsc.hadoopConfiguration())
+ if not fs.delete(jpath, True) and fs.exists(jpath):
+ logging.getLogger(__name__).warning(
+ "Could not remove intermediate coverage checkpoint %s", path
+ )
+ except Exception:
+ logging.getLogger(__name__).warning(
+ "Could not remove intermediate coverage checkpoint %s",
+ path,
+ exc_info=True,
+ )
+
+ def close(self):
+ for path in self._paths.values():
+ self._delete(path)
+ self._paths.clear()
+
+
+def _extract(frame: DataFrame) -> DataFrame:
+ """Expand rings without closing duplicates; normalize signed-zero XY IDs."""
+ parts = frame.select(
+ "id",
+ F.posexplode(F.expr("ST_Dump(geom)")).alias("part", "_polygon"),
+ ).where("NOT ST_IsEmpty(_polygon)")
+ rings = (
+ parts.select(
+ "id",
+ "part",
+ "_polygon",
+ F.explode(
+ F.sequence(F.lit(0), F.expr("ST_NumInteriorRings(_polygon)"))
+ ).alias("ring"),
+ )
+ .withColumn(
+ "_line",
+ F.expr(
+ "CASE WHEN ring = 0 THEN ST_ExteriorRing(_polygon) "
+ "ELSE ST_InteriorRingN(_polygon, ring - 1) END"
+ ),
+ )
+ .withColumn("_points", F.expr("ST_DumpPoints(_line)"))
+ )
+ # Trim before expansion so Generate does not carry and copy the full ring
+ # array for every vertex when Spark inlines a post-expansion size filter.
+ points = rings.select(
+ "id",
+ "part",
+ "ring",
+ F.posexplode(F.slice("_points", 1, F.size("_points") - 1)).alias(
+ "pos", "_point"
+ ),
+ )
+ points = points.withColumn("_x", F.expr("ST_X(_point)")).withColumn(
+ "_y", F.expr("ST_Y(_point)")
+ )
+ points = points.select(
+ "id",
+ "part",
+ "ring",
+ "pos",
+ F.when(F.col("_x") == 0.0, F.lit(0.0)).otherwise(F.col("_x")).alias("x"),
+ F.when(F.col("_y") == 0.0, F.lit(0.0)).otherwise(F.col("_y")).alias("y"),
+ )
+ return points.select(
+ "id",
+ "part",
+ "ring",
+ "pos",
+ F.to_json(F.array("x", "y")).alias("vid"),
+ "x",
+ "y",
+ )
+
+
+def _segments(occ: DataFrame) -> DataFrame:
+ """Canonical undirected segments with distinct owning-ring counts."""
+ order = Window.partitionBy("id", "part", "ring").orderBy("pos")
+ first = order.rowsBetween(Window.unboundedPreceding, Window.unboundedFollowing)
+ edges = occ
+ for value in ("vid", "x", "y"):
+ edges = edges.withColumn(
+ "_next_" + value,
+ F.coalesce(F.lead(value).over(order), F.first(value).over(first)),
+ )
+ forward = F.col("vid") < F.col("_next_vid")
+ edges = edges.where(F.col("vid") != F.col("_next_vid")).select(
+ "id",
+ "part",
+ "ring",
+ F.when(forward, F.col("vid")).otherwise(F.col("_next_vid")).alias("a"),
+ F.when(forward, F.col("_next_vid")).otherwise(F.col("vid")).alias("b"),
+ F.when(forward, F.col("x")).otherwise(F.col("_next_x")).alias("ax"),
+ F.when(forward, F.col("y")).otherwise(F.col("_next_y")).alias("ay"),
+ F.when(forward, F.col("_next_x")).otherwise(F.col("x")).alias("bx"),
+ F.when(forward, F.col("_next_y")).otherwise(F.col("y")).alias("by"),
+ )
+ edges = edges.groupBy("a", "b").agg(
+ *[F.first(name).alias(name) for name in ("ax", "ay", "bx", "by")],
+ F.countDistinct(F.struct("id", "part", "ring")).alias("owners"),
+ )
+ return edges.select(
+ "a",
+ "b",
+ "ax",
+ "ay",
+ "bx",
+ "by",
+ F.expr("ST_MakeLine(array(ST_Point(ax, ay), ST_Point(bx, by)))").alias("geom"),
+ "owners",
+ )
+
+
+def _candidates(occ, edges, tolerance, simplify_boundary):
+ adjacency = edges.selectExpr(
+ "a AS vid", "b AS nid", "bx AS nx", "by AS ny", "owners"
+ ).unionByName(
+ edges.selectExpr("b AS vid", "a AS nid", "ax AS nx", "ay AS ny", "owners")
+ )
+ pair = (
+ adjacency.groupBy("vid")
+ .agg(
+ F.count("*").alias("degree"),
+ F.min(F.struct("nid", "nx", "ny")).alias("u"),
+ F.max(F.struct("nid", "nx", "ny")).alias("w"),
+ F.min("owners").alias("min_owners"),
+ )
+ .where("degree = 2 AND u.nid <> w.nid")
+ )
+ if not simplify_boundary:
+ pair = pair.where("min_owners = 2")
+ sizes = (
+ occ.groupBy("id", "part", "ring")
+ .count()
+ .withColumnRenamed("count", "ring_size")
+ )
+ minimum = (
+ occ.join(sizes, ["id", "part", "ring"])
+ .groupBy("vid")
+ .agg(F.min("ring_size").alias("min_ring_size"))
+ )
+ points = occ.select("vid", "x", "y").distinct()
+ return (
+ pair.join(points, "vid")
+ .join(minimum, "vid")
+ .where("min_ring_size >= 4")
+ .selectExpr(
+ "vid",
+ "x",
+ "y",
+ "u.nid uid",
+ "w.nid wid",
+ "u.nx ux",
+ "u.ny uy",
+ "w.nx wx",
+ "w.ny wy",
+ )
+ .withColumn(
+ "_triangle",
+ F.expr(
+ "ST_MakePolygon(ST_MakeLine(array("
+ "ST_Point(ux,uy),ST_Point(x,y),ST_Point(wx,wy),ST_Point(ux,uy))))"
+ ),
+ )
+ .withColumn("area", F.expr("ST_Area(_triangle)"))
+ .where(F.col("area") <= tolerance * tolerance)
+ .withColumn("priority", F.struct("area", "vid"))
+ .withColumn(
+ "ends", F.expr("ST_Collect(array(ST_Point(ux,uy), ST_Point(wx,wy)))")
+ )
+ # Robust orientation, not a rounded area, determines the dimension.
+ # Keep the original triangle's area: hull ordering can change floating-
+ # point cancellation for very thin triangles.
+ .withColumn("footprint", F.expr("ST_ConvexHull(_triangle)"))
+ # Skip non-collinear edits whose area rounds to zero.
+ .where("area > 0 OR ST_GeometryType(footprint) = 'ST_LineString'")
+ .drop("_triangle")
+ )
+
+
+def _rebuild(occ: DataFrame, original: DataFrame) -> DataFrame:
+ """Rebuild original types, rings, parts, SRIDs, and all extra columns."""
+ rings = (
+ occ.groupBy("id", "part", "ring")
+ .agg(F.sort_array(F.collect_list(F.struct("pos", "x", "y"))).alias("_coords"))
+ .withColumn("_points", F.expr("transform(_coords, p -> ST_Point(p.x, p.y))"))
+ .withColumn(
+ "_line",
+ F.expr("ST_MakeLine(concat(_points, array(element_at(_points, 1))))"),
+ )
+ )
+ # Compare integer IDs, not GeometryUDT values.
+ ring_arrays = rings.groupBy("id", "part").agg(
+ F.array_sort(
+ F.collect_list(F.struct("ring", "_line")),
+ lambda left, right: left["ring"] - right["ring"],
+ ).alias("_rings")
+ )
+ parts = ring_arrays.select(
+ "id",
+ "part",
+ F.expr(
+ "ST_MakePolygon("
+ "element_at(filter(_rings, r -> r.ring = 0), 1)._line, "
+ "transform(filter(_rings, r -> r.ring > 0), r -> r._line))"
+ ).alias("_polygon"),
+ )
+ # Empty members have no coordinate occurrences. Restore them at their
+ # original positions rather than dropping them while assembling the parts.
+ original_parts = original.select(
+ "id",
+ F.expr("ST_SRID(geom)").alias("_srid"),
+ F.posexplode(F.expr("ST_Dump(geom)")).alias("part", "_original_polygon"),
+ )
+ parts = original_parts.join(parts, ["id", "part"], "left").select(
+ "id",
+ "part",
+ # ST_SetSRID copies geometry through GeometryEditor, which removes
+ # empty collection members. Set each polygon's SRID before collecting.
+ F.expr(
+ "ST_SetSRID(CASE WHEN ST_IsEmpty(_original_polygon) "
+ "THEN _original_polygon ELSE _polygon END, _srid)"
+ ).alias("_polygon"),
+ )
+ polygons = parts.groupBy("id").agg(
+ F.array_sort(
+ F.collect_list(F.struct("part", "_polygon")),
+ lambda left, right: left["part"] - right["part"],
+ ).alias("_parts")
+ )
+ assembled = original.select("id", F.col("geom").alias("_original")).join(
+ polygons, "id", "left"
+ )
+ result = F.expr(
+ "CASE WHEN _original IS NULL OR ST_IsEmpty(_original) THEN _original "
+ "ELSE CASE WHEN ST_GeometryType(_original) = 'ST_Polygon' "
+ "THEN element_at(_parts, 1)._polygon "
+ "ELSE ST_Collect(transform(_parts, p -> p._polygon)) END END"
+ )
+ rebuilt = assembled.select("id", result.alias("geom"))
+ joined = original.alias("original").join(rebuilt.alias("rebuilt"), "id", "left")
+ return joined.select(
+ *[
+ F.col(
+ f"{'rebuilt' if field.name == 'geom' else 'original'}.`{field.name.replace('`', '``')}`"
+ ).alias(field.name, metadata=field.metadata)
+ for field in original.schema
+ ]
+ )
+
+
+def simplify_coverage(
+ frame: DataFrame, tolerance: float, simplify_boundary: bool
+) -> DataFrame:
+ """Simplify until the conservative selection has no further removals.
+
+ ``frame`` has unique nonnull LongType ``id``, GeometryType ``geom``, and
+ arbitrary additional columns. A configured shared Spark checkpoint directory
+ is required. Execution is eager; the returned reliable checkpoint remains
+ reusable without an explicit close operation. Its storage is retained under
+ Spark/user lifecycle, not deleted by subsequent calls to this function.
+
+ Each input geometry is limited to 100000 coordinates. The baseline can
+ still be costly on long rings, dense spatial matches, or many rounds.
+ Empty interior rings are rejected because the polygon constructor removes
+ them. Empty polygon rows and empty multipart members are preserved.
+ """
+ if is_remote():
+ raise NotImplementedError("coverage simplification requires Spark Classic")
+ if (
+ not isinstance(tolerance, (float, int))
+ or not math.isfinite(tolerance)
+ or tolerance < 0
+ ):
+ raise ValueError("tolerance must be a finite nonnegative scalar")
+ if not isinstance(frame.schema["id"].dataType, LongType):
+ raise ValueError("coverage simplification requires LongType row IDs")
+ if not isinstance(frame.schema["geom"].dataType, GeometryType):
+ raise ValueError("coverage simplification requires a GeometryType geom column")
+ context = frame.sparkSession.sparkContext
+ if not context.getCheckpointDir():
+ raise ValueError(
+ "coverage simplification requires a shared Spark checkpoint directory; "
+ "configure spark.sparkContext.setCheckpointDir(...)"
+ )
+ checkpoints = _Checkpoints(context)
+ try:
+ # Snapshot before validation or any branches: physical IDs (and user
+ # columns) may originate from nondeterministic Spark expressions.
+ original = checkpoints.save(frame)
+ stats = (
+ original.selectExpr(
+ "id",
+ "ST_NPoints(geom) n",
+ "CASE WHEN geom IS NULL THEN false ELSE "
+ "ST_GeometryType(geom) NOT IN ('ST_Polygon','ST_MultiPolygon') OR "
+ "NOT ST_IsValid(geom) OR ST_HasZ(geom) OR ST_HasM(geom) END invalid",
+ )
+ .agg(
+ F.count("*").alias("rows"),
+ F.countDistinct("id").alias("ids"),
+ F.sum("n").alias("vertices"),
+ F.max("n").alias("max_vertices"),
+ F.max(F.col("invalid").cast("int")).alias("invalid"),
+ )
+ .first()
+ )
+ if stats.rows != stats.ids:
+ raise ValueError("coverage simplification requires unique nonnull IDs")
+ if stats.invalid:
+ raise ValueError(
+ "coverage simplification requires valid 2D Polygon/MultiPolygon rows"
+ )
+ if (stats.max_vertices or 0) > 100000:
+ raise ValueError(
+ "input exceeds the per-geometry limit of 100000 coordinates"
+ )
+ # Geometry-level dimension predicates inspect only the first
+ # coordinate. A NaN first ordinate can hide later Z/M coordinates.
+ # Inspect individual points only after the per-geometry size check.
+ if (
+ original.where("exists(ST_DumpPoints(geom), p -> ST_HasZ(p) OR ST_HasM(p))")
+ .limit(1)
+ .count()
+ ):
+ raise ValueError(
+ "coverage simplification requires valid 2D Polygon/MultiPolygon rows"
+ )
+ if (
+ original.where(
+ "exists(ST_Dump(geom), p -> CASE WHEN ST_NumInteriorRings(p) = 0 "
+ "THEN false ELSE exists(sequence(0, ST_NumInteriorRings(p) - 1), "
+ "i -> ST_IsEmpty(ST_InteriorRingN(p, i))) END)"
+ )
+ .limit(1)
+ .count()
+ ):
+ raise ValueError(
+ "coverage simplification does not support empty interior rings"
+ )
+ if not stats.vertices:
+ return checkpoints.keep(original)
+
+ occ = checkpoints.save(_extract(original))
+ bad = occ.where(
+ "isnan(x) OR isnan(y) OR abs(x) = cast('Infinity' AS double) "
+ "OR abs(y) = cast('Infinity' AS double)"
+ )
+ if bad.limit(1).count():
+ raise ValueError("coverage simplification requires finite XY coordinates")
+ if (
+ occ.groupBy("id", "part", "ring", "vid")
+ .count()
+ .where("count > 1")
+ .limit(1)
+ .count()
+ ):
+ raise ValueError(
+ "coverage simplification does not support repeated vertices within a ring"
+ )
+
+ while True:
+ resources = []
+
+ def materialize(value):
+ saved = checkpoints.save(value)
+ resources.append(saved)
+ return saved
+
+ try:
+ edge = materialize(_segments(occ))
+ candidates = materialize(
+ _candidates(occ, edge, tolerance, simplify_boundary)
+ )
+ if not candidates.limit(1).count():
+ break
+ # Aggregate scalar flags, never arrays of neighboring geometry.
+ hits = (
+ candidates.alias("c")
+ .join(
+ edge.alias("s"),
+ F.expr(
+ "ST_Intersects(c.footprint,s.geom) AND s.a <> c.vid AND s.b <> c.vid"
+ ),
+ )
+ .selectExpr(
+ "c.vid", "c.ends", "ST_Intersection(c.footprint,s.geom) hit"
+ )
+ )
+ flags = hits.groupBy("vid").agg(
+ F.max((~F.expr("ST_CoveredBy(hit,ends)")).cast("int")).alias(
+ "blocked"
+ )
+ )
+ safe = materialize(
+ candidates.join(flags, "vid", "left").where(
+ "coalesce(blocked,0) = 0"
+ )
+ )
+ # At most one coordinate per ring per round; all owners agree.
+ memberships = occ.select("id", "part", "ring", "vid").join(
+ safe.select("vid", "priority"), "vid"
+ )
+ ring_min = memberships.groupBy("id", "part", "ring").agg(
+ F.min("priority").alias("winner")
+ )
+ ring_losers = (
+ memberships.join(ring_min, ["id", "part", "ring"])
+ .where("priority <> winner")
+ .select("vid")
+ .distinct()
+ )
+ winners = materialize(safe.join(ring_losers, "vid", "left_anti"))
+ # Proposed affected regions must be pairwise disjoint.
+ conflicts = (
+ winners.alias("a")
+ .join(
+ winners.alias("b"),
+ F.expr(
+ "ST_Intersects(a.footprint,b.footprint) AND a.priority > b.priority"
+ ),
+ )
+ .selectExpr("a.vid")
+ .distinct()
+ )
+ selected = materialize(
+ winners.join(conflicts, "vid", "left_anti").select("vid")
+ )
+ if not selected.limit(1).count():
+ break
+ next_occ = checkpoints.save(occ.join(selected, "vid", "left_anti"))
+ checkpoints.release(occ)
+ occ = next_occ
+ finally:
+ for saved in resources:
+ checkpoints.release(saved)
+ # Reliable output must complete before original/occ dependencies go away.
+ output = checkpoints.save(_rebuild(occ, original))
+ return checkpoints.keep(output)
+ finally:
+ checkpoints.close()
diff --git a/python/sedona/spark/geopandas/base.py b/python/sedona/spark/geopandas/base.py
index 04f9013d99c..fb649220cf6 100644
--- a/python/sedona/spark/geopandas/base.py
+++ b/python/sedona/spark/geopandas/base.py
@@ -403,6 +403,93 @@ class GeoFrame(metaclass=ABCMeta):
"is_valid_coverage", self, gap_width=gap_width
)
+ def simplify_coverage(self, tolerance, *, simplify_boundary=True):
+ """Simplify an edge-matched polygonal coverage using distributed joins.
+
+ Shared boundary vertices are removed consistently from every incident
+ polygon. The operation evaluates Spark jobs eagerly until no further
+ edits are accepted, and returns a reusable, unnamed GeoSeries.
+
+ .. versionadded:: 2.0.0
+
+ Parameters
+ ----------
+ tolerance : float
+ Finite, non-negative scalar. A vertex is eligible when the area
+ of its triangle with its two neighbours is at most
+ ``tolerance ** 2``. Tolerance has the units of the coordinates;
+ it is not a bound on displacement. Zero can remove collinear
+ vertices. Per-row tolerances are not supported.
+ simplify_boundary : bool, default True
+ Whether the exterior boundary of the coverage can change. If
+ False, simplify only edges shared by two rings.
+
+ Returns
+ -------
+ GeoSeries
+ Simplified polygons with the original index levels, CRS and
+ embedded SRIDs. Missing and empty polygon rows are preserved.
+
+ Notes
+ -----
+ Requires Spark Classic and a checkpoint directory configured with
+ ``spark.sparkContext.setCheckpointDir(path)``. On a cluster, the path
+ must use storage accessible to all executors, such as HDFS. Local
+ filesystem paths are appropriate only for local Spark execution.
+ Intermediate checkpoints are released after their successors are
+ materialized. The final checkpoint must remain available while the
+ result or any derived DataFrame is in use. Its files follow Spark's
+ checkpoint cleanup policy; this method does not delete the configured
+ directory or require a public ``close()`` call.
+
+ Input must be a valid, finite, edge-matched 2D Polygon/MultiPolygon
+ coverage. Non-polygonal values, Z/M coordinates, invalid polygons and
+ repeated vertices within a ring (apart from closure) are rejected.
+ Empty interior rings are also rejected; empty polygons and empty
+ MultiPolygon members are preserved.
+ Full coverage validity is a precondition, not checked by this method;
+ use :meth:`is_valid_coverage` separately when needed.
+
+ The conservative algorithm uses current-segment safety checks and
+ disjoint edit regions, with at most one vertex removed per ring per
+ round. It can retain more vertices than GeoPandas/GEOS and never
+ deletes rings, holes or polygon parts. Results are not guaranteed to
+ match GeoPandas/GEOS vertex selection.
+
+ Geometry rows stay distributed, but reconstruction builds arrays per
+ ring and input geometry. Inputs above 100,000 coordinates per geometry
+ are rejected. This is an admission limit, not a memory guarantee:
+ long rings can exhaust executor memory even below that limit. Dense
+ spatial matches and many synchronization rounds can also be costly.
+
+ Examples
+ --------
+ >>> from sedona.spark import SedonaContext
+ >>> from sedona.spark.geopandas import GeoSeries
+ >>> from shapely.geometry import Polygon
+ >>> import tempfile
+ >>> spark = SedonaContext.create(
+ ... SedonaContext.builder().master("local[2]").getOrCreate()
+ ... )
+ >>> spark.sparkContext.setCheckpointDir(tempfile.mkdtemp())
+ >>> polygons = GeoSeries([
+ ... Polygon([(0, 0), (0.5, 0), (1, 0), (1, 1), (0, 1)])
+ ... ])
+ >>> polygons.simplify_coverage(0).count_coordinates().to_list()
+ [5]
+
+ See Also
+ --------
+ simplify : simplify each geometry independently
+ is_valid_coverage : check edge matching and coverage validity
+ """
+ return _delegate_to_geometry_column(
+ "simplify_coverage",
+ self,
+ tolerance=tolerance,
+ simplify_boundary=simplify_boundary,
+ )
+
def invalid_coverage_edges(self, *, gap_width=0.0):
"""Return edges causing invalid polygonal coverage for each geometry.
diff --git a/python/sedona/spark/geopandas/geoseries.py b/python/sedona/spark/geopandas/geoseries.py
index 4cd4a5289df..33667a0f617 100644
--- a/python/sedona/spark/geopandas/geoseries.py
+++ b/python/sedona/spark/geopandas/geoseries.py
@@ -1406,6 +1406,53 @@ class GeoSeries(GeoFrame, pspd.Series):
source_internal,
)
+ def simplify_coverage(self, tolerance, *, simplify_boundary=True) -> "GeoSeries":
+ from sedona.spark.geopandas._coverage import simplify_coverage
+
+ tolerance = _normalize_numeric_scalar(
+ tolerance, "'tolerance' must be a numeric scalar"
+ )
+ if tolerance < 0 or not np.isfinite(tolerance):
+ raise ValueError("'tolerance' must be finite and non-negative")
+ if not isinstance(simplify_boundary, (bool, np.bool_)):
+ raise TypeError("'simplify_boundary' must be a boolean")
+
+ source_internal = self._internal.resolved_copy
+ source_frame = source_internal.spark_frame
+ index_names = [
+ f"__coverage_index_{level}__"
+ for level in range(len(source_internal.index_spark_columns))
+ ]
+ source = source_frame.select(
+ source_internal.data_spark_columns[0].alias(
+ "geom", metadata=source_internal.data_fields[0].metadata
+ ),
+ *[
+ column.alias(name)
+ for column, name in zip(
+ source_internal.index_spark_columns, index_names
+ )
+ ],
+ scol_for(source_frame, NATURAL_ORDER_COLUMN_NAME),
+ # Index labels and natural-order values can both be duplicated or
+ # null after alignment. The helper snapshots this physical ID
+ # before branching, so every original row has a stable identity.
+ F.monotonically_increasing_id().alias("id"),
+ )
+ result = simplify_coverage(source, tolerance, bool(simplify_boundary))
+ result = result.orderBy(
+ scol_for(result, NATURAL_ORDER_COLUMN_NAME).asc_nulls_last(),
+ scol_for(result, "id"),
+ )
+ return self._result_preserving_index(
+ scol_for(result, "geom"),
+ result,
+ [scol_for(result, name) for name in index_names],
+ source_internal.index_fields,
+ source_internal.index_names,
+ returns_geom=True,
+ )
+
def invalid_coverage_edges(self, *, gap_width=0.0) -> "GeoSeries":
gap_width = _normalize_numeric_scalar(
gap_width, "'gap_width' must be a numeric scalar"
diff --git a/python/tests/geopandas/test_coverage.py b/python/tests/geopandas/test_coverage.py
new file mode 100644
index 00000000000..4c03005166c
--- /dev/null
+++ b/python/tests/geopandas/test_coverage.py
@@ -0,0 +1,358 @@
+# 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.
+
+import os
+
+import pytest
+from pyspark.sql import functions as F
+
+from sedona.spark import SedonaContext
+
+pytestmark = pytest.mark.skipif(
+ bool(os.getenv("SPARK_REMOTE")),
+ reason="Coverage simplification requires Spark Classic",
+)
+
+
+@pytest.fixture(scope="module")
+def spark():
+ if "SPARK_HOME" in os.environ and not os.environ["SPARK_HOME"]:
+ del os.environ["SPARK_HOME"]
+ builder = (
+ SedonaContext.builder()
+ .master("local[2]")
+ .appName("CoverageSimplificationTest")
+ .config("spark.sql.shuffle.partitions", "2")
+ .config("spark.sql.ansi.enabled", "false")
+ )
+ if os.getenv("SEDONA_PYTHON_EXTRA_JARS"):
+ builder = builder.config("spark.jars", os.environ["SEDONA_PYTHON_EXTRA_JARS"])
+ session = SedonaContext.create(builder.getOrCreate())
+ previous = session.sparkContext._jsc.sc().checkpointDir()
+ yield session
+ getattr(session.sparkContext._jsc.sc(), "checkpointDir_$eq")(previous)
+
+
+def _source(spark):
+ return spark.createDataFrame(
+ [
+ (0, "POLYGON ((0 0, 1 0, 1.05 1, 1 2, 0 2, 0 0))", "left"),
+ (1, "POLYGON ((1 0, 2 0, 2 2, 1 2, 1.05 1, 1 0))", "right"),
+ ],
+ "id long, wkt string, label string",
+ ).selectExpr("label", "ST_GeomFromWKT(wkt) geom", "id")
+
+
+def test_extraction_does_not_repeat_ring_arrays(spark):
+ from sedona.spark.geopandas._coverage import _extract
+
+ extracted = _extract(_source(spark))
+ nodes = [extracted._jdf.queryExecution().optimizedPlan()]
+ generators = 0
+ while nodes:
+ node = nodes.pop()
+ if node.nodeName() == "Generate":
+ generators += 1
+ carried = node.requiredChildOutput()
+ # Carrying the full array through Generate copies it once per
+ # vertex at a codegen boundary, even if a later projection drops it.
+ assert all(
+ carried.apply(i).dataType().typeName() != "array"
+ for i in range(carried.size())
+ ), node.toString()
+ children = node.children()
+ nodes.extend(children.apply(i) for i in range(children.size()))
+ assert generators > 0
+
+
+def test_extraction_preserves_parts_rings_positions_and_signed_zero(spark):
+ from sedona.spark.geopandas._coverage import _extract
+
+ source = spark.createDataFrame(
+ [
+ (
+ 7,
+ "MULTIPOLYGON (EMPTY, ((-0 0, 4 0, 4 4, 0 4, -0 0), (1 1, 1 2, 2 1, 1 1)), ((8 0, 9 0, 8 1, 8 0)))",
+ ),
+ (8, "POLYGON EMPTY"),
+ (9, None),
+ ],
+ "id long, wkt string",
+ ).selectExpr("id", "ST_GeomFromWKT(wkt) geom")
+
+ rows = _extract(source).orderBy("id", "part", "ring", "pos").collect()
+
+ expected = [
+ (7, 1, 0, 0, 0.0, 0.0),
+ (7, 1, 0, 1, 4.0, 0.0),
+ (7, 1, 0, 2, 4.0, 4.0),
+ (7, 1, 0, 3, 0.0, 4.0),
+ (7, 1, 1, 0, 1.0, 1.0),
+ (7, 1, 1, 1, 1.0, 2.0),
+ (7, 1, 1, 2, 2.0, 1.0),
+ (7, 2, 0, 0, 8.0, 0.0),
+ (7, 2, 0, 1, 9.0, 0.0),
+ (7, 2, 0, 2, 8.0, 1.0),
+ ]
+ assert [
+ (row.id, row.part, row.ring, row.pos, row.x, row.y) for row in rows
+ ] == expected
+ assert rows[0].vid == "[0.0,0.0]"
+
+
+def test_shared_boundary_output_survives_intermediate_cleanup(spark, tmp_path):
+ from sedona.spark.geopandas._coverage import simplify_coverage
+
+ spark.sparkContext.setCheckpointDir(str(tmp_path))
+ source = _source(spark)
+ result = simplify_coverage(source, 0.3, False)
+
+ assert result.columns == source.columns
+ assert result.count() == 2
+ assert result.selectExpr("sum(ST_NPoints(geom)) n").first().n == 10
+ assert result.selectExpr("min(cast(ST_IsValid(geom) as int)) ok").first().ok == 1
+ spark.catalog.clearCache()
+ assert result.orderBy("id").collect() == result.orderBy("id").collect()
+ assert [r.label for r in result.orderBy("id").collect()] == ["left", "right"]
+ assert len(list(tmp_path.glob("*/rdd-*"))) == 1
+
+
+def test_requires_checkpoint_directory(spark):
+ from sedona.spark.geopandas._coverage import simplify_coverage
+
+ context = spark.sparkContext
+ previous = context._jsc.sc().checkpointDir()
+ getattr(context._jsc.sc(), "checkpointDir_$eq")(context._jvm.scala.Option.empty())
+ try:
+ with pytest.raises(ValueError, match="checkpoint"):
+ simplify_coverage(_source(spark), 0.3, False)
+ finally:
+ getattr(context._jsc.sc(), "checkpointDir_$eq")(previous)
+
+
+def test_preserves_null_empty_srid_metadata_and_unrelated_files(spark, tmp_path):
+ from sedona.spark.geopandas._coverage import simplify_coverage
+
+ spark.sparkContext.setCheckpointDir(str(tmp_path))
+ sentinel = tmp_path / "caller-data"
+ sentinel.write_text("keep")
+ source = spark.createDataFrame(
+ [
+ (0, None),
+ (1, "POLYGON EMPTY"),
+ (2, "MULTIPOLYGON EMPTY"),
+ (3, "POLYGON ((0 0, 1 0, 2 0, 2 2, 0 2, 0 0))"),
+ ],
+ "id long, wkt string",
+ ).selectExpr("id", "ST_SetSRID(ST_GeomFromWKT(wkt), 4326) geom")
+ source = source.select(
+ F.col("id").alias("id", metadata={"description": "physical identifier"}),
+ F.col("geom").alias("geom", metadata={"crs": "EPSG:4326"}),
+ F.lit("unchanged").alias("extra.column`name", metadata={"note": "keep"}),
+ )
+ caller_checkpoint = source.checkpoint(eager=True)
+ result = simplify_coverage(source, 0.0, True)
+
+ assert result.schema == source.schema
+ rows = (
+ result.selectExpr("id", "ST_AsText(geom) wkt", "ST_SRID(geom) srid")
+ .orderBy("id")
+ .collect()
+ )
+ assert [r.wkt for r in rows[:3]] == [None, "POLYGON EMPTY", "MULTIPOLYGON EMPTY"]
+ assert rows[3].srid == 4326
+ assert result.where("id = 3").selectExpr("ST_NPoints(geom) n").first().n == 5
+ assert sentinel.read_text() == "keep"
+ assert len(list(tmp_path.glob("*/rdd-*"))) == 2
+ assert caller_checkpoint.count() == 4
+
+
+@pytest.mark.parametrize(
+ "wkt, message",
+ [
+ ("POINT (0 0)", "valid 2D"),
+ ("POLYGON Z ((0 0 1, 2 0 1, 2 2 1, 0 0 1))", "valid 2D"),
+ ("POLYGON M ((0 0 1, 2 0 1, 2 2 1, 0 0 1))", "valid 2D"),
+ ("POLYGON ((0 0, 2 2, 0 2, 2 0, 0 0))", "valid 2D"),
+ ("POLYGON ((0 0, 2 0, 2 0, 2 2, 0 2, 0 0))", "repeated"),
+ ("POLYGON ((0 0, Infinity 0, 2 2, 0 2, 0 0))", "finite|valid 2D"),
+ ],
+)
+def test_validation_failure_cleans_owned_checkpoints(spark, tmp_path, wkt, message):
+ from sedona.spark.geopandas._coverage import simplify_coverage
+
+ spark.sparkContext.setCheckpointDir(str(tmp_path))
+ sentinel = tmp_path / "caller-data"
+ sentinel.write_text("keep")
+ source = spark.createDataFrame([(0, wkt)], "id long, wkt string").selectExpr(
+ "id", "ST_GeomFromWKT(wkt) geom"
+ )
+ with pytest.raises(ValueError, match=message):
+ simplify_coverage(source, 0.3, False)
+ assert not list(tmp_path.glob("*/rdd-*"))
+ assert sentinel.read_text() == "keep"
+
+
+@pytest.mark.parametrize("ids", [[0, 0], [0, None]])
+def test_requires_unique_nonnull_physical_ids(spark, tmp_path, ids):
+ from sedona.spark.geopandas._coverage import simplify_coverage
+
+ spark.sparkContext.setCheckpointDir(str(tmp_path))
+ source = spark.createDataFrame([(i,) for i in ids], "id long").selectExpr(
+ "id", "ST_GeomFromWKT('POLYGON EMPTY') geom"
+ )
+ with pytest.raises(ValueError, match="unique nonnull"):
+ simplify_coverage(source, 0.0, False)
+ assert not list(tmp_path.glob("*/rdd-*"))
+
+
+def test_rejects_connect_with_clear_error(spark, monkeypatch):
+ from sedona.spark.geopandas._coverage import simplify_coverage
+
+ source = _source(spark)
+ monkeypatch.setenv("SPARK_CONNECT_MODE_ENABLED", "1")
+ with pytest.raises(NotImplementedError, match="Spark Classic"):
+ simplify_coverage(source, 0.3, False)
+
+
+@pytest.mark.parametrize("id_type", ["double", "string"])
+def test_rejects_non_long_ids_before_checkpoint(spark, tmp_path, id_type):
+ from sedona.spark.geopandas._coverage import simplify_coverage
+
+ spark.sparkContext.setCheckpointDir(str(tmp_path))
+ source = _source(spark).withColumn("id", F.col("id").cast(id_type))
+ with pytest.raises(ValueError, match="LongType"):
+ simplify_coverage(source, 0.0, False)
+ assert not list(tmp_path.glob("*/rdd-*"))
+
+
+def test_rejects_oversized_geometry_before_ring_expansion(spark, tmp_path):
+ from sedona.spark.geopandas._coverage import simplify_coverage
+
+ spark.sparkContext.setCheckpointDir(str(tmp_path))
+ source = spark.range(1).selectExpr(
+ "id",
+ "ST_MakePolygon(ST_MakeLine(transform(sequence(0, 100000), i -> "
+ "CASE WHEN i = 100000 THEN ST_Point(1D, 0D) ELSE "
+ "ST_Point(cos(2*pi()*i/100000), sin(2*pi()*i/100000)) END))) geom",
+ )
+ with pytest.raises(ValueError, match="100000"):
+ simplify_coverage(source, 0.0, False)
+ assert not list(tmp_path.glob("*/rdd-*"))
+
+
+@pytest.mark.parametrize(
+ "wkt, x, y",
+ [
+ (
+ "POLYGON ((0 0,100000000 100000001,100000000 100000003,100000001 100000002,0 0))",
+ 0,
+ 0,
+ ),
+ (
+ "POLYGON ((0 0,100000000 100000001,100000001 100000002,0 10,0 0))",
+ 100000000,
+ 100000001,
+ ),
+ ],
+)
+def test_rounded_area_never_admits_noncollinear_edit(spark, wkt, x, y):
+ from sedona.spark.geopandas._coverage import _candidates, _extract, _segments
+
+ source = spark.createDataFrame([(0, wkt)], "id long, wkt string").selectExpr(
+ "id", "ST_GeomFromWKT(wkt) geom"
+ )
+ occurrences = _extract(source)
+ candidates = _candidates(occurrences, _segments(occurrences), 0.5, True)
+ # The exact triangle area is 0.5, greater than tolerance squared (0.25).
+ # A rounded determinant can incorrectly make that area zero.
+ assert candidates.where((F.col("x") == x) & (F.col("y") == y)).count() == 0
+
+
+@pytest.mark.parametrize("dimension", ["Z", "M"])
+@pytest.mark.parametrize("multipart", [False, True])
+def test_rejects_dimensions_hidden_by_first_nan_ordinate(
+ spark, tmp_path, dimension, multipart
+):
+ from sedona.spark.geopandas._coverage import simplify_coverage
+
+ spark.sparkContext.setCheckpointDir(str(tmp_path))
+ wkt = f"POLYGON {dimension} ((0 0 NaN, 2 0 1, 2 2 1, 0 2 1, 0 0 NaN))"
+ if multipart:
+ wkt = (
+ f"MULTIPOLYGON {dimension} (((0 0 NaN, 2 0 NaN, 2 2 NaN, 0 2 NaN, 0 0 NaN)), "
+ "((4 0 1, 6 0 1, 6 2 1, 4 2 1, 4 0 1)))"
+ )
+ source = spark.createDataFrame(
+ [(0, wkt)],
+ "id long, wkt string",
+ ).selectExpr("id", "ST_GeomFromWKT(wkt) geom")
+ assert source.selectExpr("ST_IsValid(geom) valid").first().valid
+ with pytest.raises(ValueError, match="valid 2D"):
+ simplify_coverage(source, 0.0, False)
+ assert not list(tmp_path.glob("*/rdd-*"))
+
+
+@pytest.mark.parametrize(
+ "wkt",
+ [
+ "MULTIPOLYGON (EMPTY, ((0 0, 1 0, 2 0, 2 2, 0 2, 0 0)))",
+ "MULTIPOLYGON (((0 0, 1 0, 2 0, 2 2, 0 2, 0 0)), EMPTY)",
+ "MULTIPOLYGON (EMPTY, ((0 0, 1 0, 2 0, 2 2, 0 2, 0 0)), EMPTY)",
+ ],
+)
+@pytest.mark.parametrize("srid", [0, 4326])
+def test_preserves_empty_parts_when_other_rings_change(spark, tmp_path, wkt, srid):
+ from sedona.spark.geopandas._coverage import simplify_coverage
+
+ spark.sparkContext.setCheckpointDir(str(tmp_path))
+ source = spark.createDataFrame([(0, wkt)], "id long, wkt string").selectExpr(
+ "id", f"ST_GeomFromEWKT(concat('SRID={srid};', wkt)) geom"
+ )
+ assert source.selectExpr("ST_IsValid(geom) valid").first().valid
+ result = simplify_coverage(source, 0.0, True)
+ # Each fixture has exactly one eligible collinear shell coordinate (1, 0).
+ expected = spark.createDataFrame(
+ [(wkt.replace("0 0, 1 0, ", "0 0, "),)], "wkt string"
+ )
+ expected_text = (
+ expected.selectExpr("ST_AsText(ST_GeomFromWKT(wkt)) wkt").first().wkt
+ )
+ assert result.selectExpr("ST_AsText(geom) wkt").first().wkt == expected_text
+ assert result.selectExpr("ST_SRID(geom) srid").first().srid == srid
+ assert len(list(tmp_path.glob("*/rdd-*"))) == 1
+
+
+@pytest.mark.parametrize(
+ "wkt",
+ [
+ "POLYGON ((0 0, 1 0, 4 0, 4 4, 0 4, 0 0), EMPTY)",
+ "POLYGON ((0 0, 1 0, 4 0, 4 4, 0 4, 0 0), EMPTY, (1 1, 1 2, 2 2, 2 1, 1 1), EMPTY)",
+ "MULTIPOLYGON (EMPTY, ((0 0, 1 0, 4 0, 4 4, 0 4, 0 0), EMPTY))",
+ ],
+)
+def test_rejects_empty_interior_rings(spark, tmp_path, wkt):
+ from sedona.spark.geopandas._coverage import simplify_coverage
+
+ spark.sparkContext.setCheckpointDir(str(tmp_path))
+ source = spark.createDataFrame([(0, wkt)], "id long, wkt string").selectExpr(
+ "id", "ST_GeomFromWKT(wkt) geom"
+ )
+ assert source.selectExpr("ST_IsValid(geom) valid").first().valid
+ with pytest.raises(ValueError, match="empty interior rings"):
+ simplify_coverage(source, 0.0, True)
+ assert not list(tmp_path.glob("*/rdd-*"))
diff --git a/python/tests/geopandas/test_simplify_coverage.py b/python/tests/geopandas/test_simplify_coverage.py
new file mode 100644
index 00000000000..06ea073e2b1
--- /dev/null
+++ b/python/tests/geopandas/test_simplify_coverage.py
@@ -0,0 +1,268 @@
+# 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.
+
+from decimal import Decimal
+
+import geopandas as gpd
+import numpy as np
+import pandas as pd
+import pyspark.pandas as ps
+import pytest
+from geopandas.testing import assert_geoseries_equal
+from pyspark.pandas.internal import NATURAL_ORDER_COLUMN_NAME
+from pyspark.pandas.series import first_series
+from pyspark.pandas.utils import scol_for
+from pyspark.sql import functions as F
+from shapely.geometry import MultiPolygon, Polygon, box
+from shapely.ops import unary_union
+
+from sedona.spark.geopandas import GeoDataFrame, GeoSeries
+from tests.geopandas.test_geopandas_base import TestGeopandasBase
+
+
+class TestSimplifyCoverage(TestGeopandasBase):
+ def test_long_ring_with_locked_boundary(self):
+ rows = self.spark.range(1).selectExpr(
+ "id",
+ "ST_MakePolygon(ST_MakeLine(transform(sequence(0, 10000), i -> "
+ "CASE WHEN i = 10000 THEN ST_Point(1D, 0D) ELSE "
+ "ST_Point(cos(2*pi()*i/10000), sin(2*pi()*i/10000)) END))) geometry",
+ )
+ original = rows.selectExpr("ST_AsBinary(geometry) wkb").first().wkb
+ source = GeoSeries(rows.pandas_api(index_col="id")["geometry"])
+
+ result = source.simplify_coverage(0, simplify_boundary=False)
+ internal = result._internal.resolved_copy
+ output = (
+ internal.spark_frame.select(
+ internal.data_spark_columns[0].alias("geometry")
+ )
+ .selectExpr("ST_NPoints(geometry) points", "ST_AsBinary(geometry) wkb")
+ .collect()
+ )
+
+ assert len(output) == 1
+ assert output[0].points == 10001
+ assert output[0].wkb == original
+
+ @pytest.mark.parametrize("tolerance", [0, np.float64(0), Decimal("0")])
+ def test_zero_tolerance_removes_collinear_vertices(self, tolerance):
+ _ = self.spark
+ source = GeoSeries([Polygon([(0, 0), (0.5, 0), (1, 0), (1, 1), (0, 1)])])
+
+ result = source.simplify_coverage(tolerance).to_geopandas()
+
+ assert result.iloc[0].equals(box(0, 0, 1, 1))
+ assert len(result.iloc[0].exterior.coords) == 5
+
+ def test_shared_boundary_and_multilevel_index(self):
+ _ = self.spark
+ left = Polygon([(0, 0), (1, 0), (1.1, 0.5), (1, 1), (0, 1)])
+ right = Polygon([(1, 0), (2, 0), (2, 1), (1, 1), (1.1, 0.5)])
+ index = pd.MultiIndex.from_tuples(
+ [("same", 2), ("same", 2), ("missing", 0)],
+ names=["group", "feature"],
+ )
+ source = GeoSeries([left, right, None], index=index, name="shape", crs=3857)
+
+ result = source.simplify_coverage(0.3, simplify_boundary=False)
+ first = result.to_geopandas()
+ second = result.to_geopandas()
+
+ expected = gpd.GeoSeries(
+ [box(0, 0, 1, 1), box(1, 0, 2, 1), None],
+ index=index,
+ crs=3857,
+ )
+ assert_geoseries_equal(first, expected, normalize=True)
+ assert_geoseries_equal(second, first)
+ assert unary_union(first.dropna()).equals(unary_union([left, right]))
+ assert first.iloc[0].intersection(first.iloc[1]).area == 0
+ assert source.name == "shape"
+
+ def test_geodataframe_uses_active_geometry(self):
+ _ = self.spark
+ geometry = Polygon([(0, 0), (0.5, 0), (1, 0), (1, 1), (0, 1)])
+ frame = GeoDataFrame({"shape": [geometry], "value": [17]}, geometry="shape")
+
+ result = frame.simplify_coverage(0).to_geopandas()
+
+ assert result.name is None
+ assert len(result.iloc[0].exterior.coords) == 5
+ assert frame["value"].to_pandas().tolist() == [17]
+
+ def test_empty_and_null_only_input(self):
+ rows = self.spark.createDataFrame(
+ [(0, "POLYGON EMPTY"), (1, None)], "id long, wkt string"
+ ).selectExpr("id", "ST_GeomFromWKT(wkt) geometry")
+ source = GeoSeries(rows.pandas_api(index_col="id")["geometry"])
+
+ result = source.simplify_coverage(0.1).to_geopandas()
+
+ assert result.index.tolist() == [0, 1]
+ assert result.iloc[0].is_empty
+ assert result.iloc[1] is None
+
+ def test_boundary_option_requires_boolean(self):
+ _ = self.spark
+ with pytest.raises(TypeError, match="boolean"):
+ GeoSeries([box(0, 0, 1, 1)]).simplify_coverage(
+ 0.1, simplify_boundary="False"
+ )
+
+ def test_empty_multipart_members_and_srid_survive_public_wrapper(self):
+ rows = self.spark.createDataFrame(
+ [
+ (
+ 7,
+ "SRID=3857;MULTIPOLYGON (EMPTY, ((0 0, 1 0, 2 0, 2 2, 0 2, 0 0)), EMPTY)",
+ )
+ ],
+ "id long, ewkt string",
+ ).selectExpr("id", "ST_GeomFromEWKT(ewkt) geometry")
+ assert (
+ rows.selectExpr("ST_NumGeometries(geometry) members").first().members == 3
+ )
+ source = GeoSeries(rows.pandas_api(index_col="id")["geometry"])
+
+ result = source.simplify_coverage(0)
+ internal = result._internal.resolved_copy
+ geometry = (
+ internal.spark_frame.select(
+ internal.data_spark_columns[0].alias("geometry")
+ )
+ .selectExpr(
+ "ST_NumGeometries(geometry) members",
+ "ST_SRID(geometry) srid",
+ "ST_NPoints(geometry) points",
+ )
+ .first()
+ )
+
+ assert geometry.members == 3
+ assert geometry.srid == 3857
+ assert geometry.points == 5
+ assert result.crs.to_epsg() == 3857
+
+ @pytest.mark.parametrize("tolerance", [-1, float("inf"), float("nan")])
+ def test_rejects_invalid_tolerance(self, tolerance):
+ _ = self.spark
+ with pytest.raises(ValueError, match="finite.*non-negative"):
+ GeoSeries([box(0, 0, 1, 1)]).simplify_coverage(tolerance)
+
+ @pytest.mark.parametrize("tolerance", [[1], np.array([1]), "1", None])
+ def test_rejects_non_scalar_tolerance(self, tolerance):
+ _ = self.spark
+ with pytest.raises(TypeError, match="numeric scalar"):
+ GeoSeries([box(0, 0, 1, 1)]).simplify_coverage(tolerance)
+
+ def test_boundary_lock_preserves_a_single_polygon(self):
+ _ = self.spark
+ geometry = Polygon([(0, 0), (0.5, 0), (1, 0), (1, 1), (0, 1)])
+
+ result = (
+ GeoSeries([geometry])
+ .simplify_coverage(10, simplify_boundary=False)
+ .to_geopandas()
+ )
+
+ assert result.iloc[0].equals_exact(geometry, 0)
+
+ def test_duplicate_and_null_natural_order_do_not_merge_rows(self):
+ _ = self.spark
+ source = GeoSeries(
+ [box(0, 0, 1, 1), box(2, 0, 3, 1), None],
+ index=pd.Index(["duplicate", "duplicate", "missing"], name="feature"),
+ )
+ internal = source._internal.resolved_copy
+ frame = internal.spark_frame.withColumn(
+ NATURAL_ORDER_COLUMN_NAME,
+ F.when(internal.data_spark_columns[0].isNotNull(), F.lit(7)).cast("long"),
+ )
+ internal = internal.copy(
+ spark_frame=frame,
+ index_spark_columns=[
+ scol_for(frame, name) for name in internal.index_spark_column_names
+ ],
+ data_spark_columns=[
+ scol_for(frame, name) for name in internal.data_spark_column_names
+ ],
+ )
+ source = GeoSeries(first_series(ps.DataFrame(internal)))
+
+ result = source.simplify_coverage(0, simplify_boundary=False).to_geopandas()
+
+ assert len(result) == 3
+ assert result.loc["missing"] is None
+ assert sorted(geometry.bounds for geometry in result.loc["duplicate"]) == [
+ (0.0, 0.0, 1.0, 1.0),
+ (2.0, 0.0, 3.0, 1.0),
+ ]
+
+ def test_conflicting_edits_do_not_erase_a_lens(self):
+ _ = self.spark
+ geometries = [
+ Polygon([(0, 0), (5, 1), (10, 0), (10, 5), (0, 5)]),
+ Polygon([(0, 0), (5, -1), (10, 0), (5, 1)]),
+ Polygon([(0, 0), (0, -5), (10, -5), (10, 0), (5, -1)]),
+ ]
+
+ result = (
+ GeoSeries(geometries)
+ .simplify_coverage(3, simplify_boundary=False)
+ .to_geopandas()
+ )
+
+ assert all(geometry.is_valid for geometry in result)
+ assert result.iloc[1].area > 0
+ assert sum(len(geometry.exterior.coords) for geometry in result) < 17
+ assert unary_union(result).equals(unary_union(geometries))
+ assert sum(geometry.area for geometry in result) == unary_union(result).area
+
+ def test_disconnected_obstacle_blocks_boundary_shortcut(self):
+ _ = self.spark
+ polygon = Polygon([(0, 0), (5, 1), (10, 0), (10, 5), (0, 5)])
+ obstacle = box(4.9, 0.2, 5.1, 0.4)
+
+ result = GeoSeries([polygon, obstacle]).simplify_coverage(3).to_geopandas()
+
+ assert result.iloc[0].equals(polygon)
+ assert result.iloc[1].is_valid and not result.iloc[1].is_empty
+ assert result.iloc[0].intersection(result.iloc[1]).area == 0
+
+ def test_shared_hole_boundary_and_multipart_are_preserved(self):
+ _ = self.spark
+ ring = [(1, 1), (2, 1), (2.1, 1.5), (2, 2), (1, 2)]
+ geometries = [
+ Polygon([(0, 0), (3, 0), (3, 3), (0, 3)], [ring]),
+ MultiPolygon([Polygon(ring), box(5, 0, 6, 1)]),
+ ]
+
+ result = (
+ GeoSeries(geometries)
+ .simplify_coverage(0.3, simplify_boundary=False)
+ .to_geopandas()
+ )
+
+ assert result.iloc[0].geom_type == "Polygon"
+ assert len(result.iloc[0].interiors) == 1
+ assert len(result.iloc[0].interiors[0].coords) == 5
+ assert result.iloc[1].geom_type == "MultiPolygon"
+ assert len(result.iloc[1].geoms) == 2
+ assert all(geometry.is_valid for geometry in result)
+ assert result.iloc[0].intersection(result.iloc[1]).area == 0
+ assert unary_union(result).equals(unary_union(geometries))