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/10/02 06:34:17 UTC

(sedona-db) branch main updated: feat(python/sedonadb-geopandas): add GeoSeries binary predicates, distance, and set operations (#1355)

This is an automated email from the ASF dual-hosted git repository.

jiayuasu pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/sedona-db.git


The following commit(s) were added to refs/heads/main by this push:
     new a6128ab54 feat(python/sedonadb-geopandas): add GeoSeries binary predicates, distance, and set operations (#1355)
a6128ab54 is described below

commit a6128ab54a0733828736a732ad5b7c75cf8c452f
Author: Jia Yu <ji...@wherobots.com>
AuthorDate: Thu Oct 1 23:34:11 2026 -0700

    feat(python/sedonadb-geopandas): add GeoSeries binary predicates, distance, and set operations (#1355)
---
 python/sedonadb-geopandas/README.md                |   7 +
 .../python/sedonadb_geopandas/_series.py           | 195 +++++++++++++++
 python/sedonadb-geopandas/tests/test_geoseries.py  | 276 +++++++++++++++++++++
 3 files changed, 478 insertions(+)

diff --git a/python/sedonadb-geopandas/README.md b/python/sedonadb-geopandas/README.md
index 778ea0766..bc987e2f3 100644
--- a/python/sedonadb-geopandas/README.md
+++ b/python/sedonadb-geopandas/README.md
@@ -85,6 +85,13 @@ in form: `to_wkt()` writes equivalent but differently spaced WKT
 them undefined, and `x`/`y`/`z` on a non-point raise when the result is
 computed rather than when the property is read.
 
+Binary geometry operations (`intersects`, `within`, `distance`,
+`intersection`, ...) take either a single Shapely geometry, which takes the
+column's CRS, or a `GeoSeries` from the same frame, matched row by row as with
+GeoPandas' `align=False`; there is no index to align on. `touches` inherits
+an engine issue with geometry collections that mix dimensions
+(apache/sedona-db#1383).
+
 `dissolve()` aggregates non-geometry columns with `"first"`, which is an
 unordered aggregate: it returns *some* value from the group rather than the one
 from the first row, and unlike GeoPandas it does not skip missing values, so a
diff --git a/python/sedonadb-geopandas/python/sedonadb_geopandas/_series.py b/python/sedonadb-geopandas/python/sedonadb_geopandas/_series.py
index 65959c83a..d3f91052b 100644
--- a/python/sedonadb-geopandas/python/sedonadb_geopandas/_series.py
+++ b/python/sedonadb-geopandas/python/sedonadb_geopandas/_series.py
@@ -16,6 +16,7 @@
 # under the License.
 """pandas/GeoPandas-style Series backed by a SedonaDB expression."""
 
+import math
 import numbers
 
 import pyarrow as pa
@@ -500,6 +501,21 @@ def _normalize_crs(crs):
         raise ValueError(f"Invalid CRS {crs!r}: {err}") from err
 
 
+def _check_align(align):
+    """GeoPandas' `align` argument.
+
+    There is no index to align on: operands are always columns of the same
+    frame, matched row by row, which is what GeoPandas does with
+    `align=False`. Asking for index alignment is an error rather than being
+    silently ignored.
+    """
+    if align:
+        raise ValueError(
+            "align=True is not supported: there is no index; columns of the "
+            "same frame are always matched row by row"
+        )
+
+
 class GeoSeries(Series):
     """A geometry column, in the shape of a `geopandas.GeoSeries`.
 
@@ -757,6 +773,185 @@ class GeoSeries(Series):
         """A point guaranteed to lie on each geometry (`ST_PointOnSurface`)."""
         return self._geo(self._expr.geo.point_on_surface())
 
+    # -- binary operations -----------------------------------------------
+
+    def _other(self, other):
+        """The right-hand side of a binary geometry operation, as an expression.
+
+        A `GeoSeries` must come from this same frame (there is no row
+        alignment), as for arithmetic. A geometry scalar, bare Shapely or
+        wrapped in `lit()`, takes this column's spatial kind, since the engine
+        has no kernel pairing geography with geometry. It takes this column's
+        CRS when it has none of its own, as it would in GeoPandas and as an
+        assigned geometry does (the engine refuses mismatched CRS); a literal
+        that carries its own CRS keeps it.
+        """
+        from sedonadb.expr import Literal
+        from shapely.geometry.base import BaseGeometry
+
+        ctx = self._df._ctx
+        value = _operand(self._df, other)
+        if isinstance(value, BaseGeometry):
+            return self._as_column_kind(ctx.lit(value), own_crs=None)
+        if not isinstance(value, Literal):
+            return value
+        # Rebound to this frame's context, so functions can be applied to it
+        # (a bare lit() has none).
+        expr = ctx.lit(value)
+        projected = self._df.select(expr.alias("x")).schema
+        if not projected.geometry_column_indices:
+            return expr
+        return self._as_column_kind(expr, own_crs=projected.field("x").type.crs)
+
+    def _as_column_kind(self, expr, own_crs):
+        """A geometry scalar with this column's spatial kind and a CRS.
+
+        `own_crs` is the CRS the scalar carries itself, if any; otherwise this
+        column's applies (or none, if the column has none).
+        """
+        ctx = self._df._ctx
+        geography = self._is_geography()
+        scalar = self._df.select(expr.alias("x")).schema.field("x").type
+        scalar_geography = "SPHERICAL" in str(getattr(scalar, "edge_type", "")).upper()
+        if geography and not scalar_geography:
+            # Re-entered through WKB as geography. The geography constructor
+            # synthesizes CRS84, so the CRS is always applied explicitly below.
+            expr = expr.geo.as_binary().funcs.st_geogfromwkb()
+        crs = own_crs if own_crs is not None else self.crs
+        if crs is not None:
+            return expr.funcs.st_setcrs(ctx.lit(crs.to_json()))
+        if geography:
+            # SRID 0 clears the synthesized CRS without touching the value.
+            return expr.funcs.st_setsrid(ctx.lit(0))
+        return expr
+
+    def _predicate(self, name, other, align=None):
+        """A GeoPandas binary predicate: False where either side is missing."""
+        from sedonadb.expr import lit
+
+        _check_align(align)
+        expr = getattr(self._expr.geo, name)(self._other(other))
+        return Series(self._df, expr.funcs.coalesce(lit(False)), name)
+
+    def intersects(self, other, align=None):
+        """Whether each geometry intersects `other` (`ST_Intersects`)."""
+        return self._predicate("intersects", other, align)
+
+    def contains(self, other, align=None):
+        """Whether each geometry contains `other` (`ST_Contains`)."""
+        return self._predicate("contains", other, align)
+
+    def within(self, other, align=None):
+        """Whether each geometry is within `other` (`ST_Within`)."""
+        return self._predicate("within", other, align)
+
+    def touches(self, other, align=None):
+        """Whether each geometry touches `other` (`ST_Touches`).
+
+        Known engine issue: a geometry collection mixing dimensions can be
+        misclassified (apache/sedona-db#1383).
+        """
+        return self._predicate("touches", other, align)
+
+    def crosses(self, other, align=None):
+        """Whether each geometry crosses `other` (`ST_Crosses`)."""
+        return self._predicate("crosses", other, align)
+
+    def overlaps(self, other, align=None):
+        """Whether each geometry overlaps `other` (`ST_Overlaps`)."""
+        return self._predicate("overlaps", other, align)
+
+    def covers(self, other, align=None):
+        """Whether each geometry covers `other` (`ST_Covers`)."""
+        return self._predicate("covers", other, align)
+
+    def covered_by(self, other, align=None):
+        """Whether each geometry is covered by `other` (`ST_CoveredBy`)."""
+        return self._predicate("covered_by", other, align)
+
+    def disjoint(self, other, align=None):
+        """Whether each geometry is disjoint from `other` (`ST_Disjoint`)."""
+        return self._predicate("disjoint", other, align)
+
+    def geom_equals(self, other, align=None):
+        """Whether each geometry equals `other` topologically (`ST_Equals`)."""
+        from sedonadb.expr import lit
+
+        _check_align(align)
+        other_expr = self._other(other)
+        # Two empty geometries are equal, whatever their types, as in
+        # GeoPandas; the engine says they are not.
+        both_empty = self._expr.geo.is_empty() & other_expr.geo.is_empty()
+        expr = self._expr.geo.equals(other_expr) | both_empty
+        return Series(self._df, expr.funcs.coalesce(lit(False)), "geom_equals")
+
+    def dwithin(self, other, distance, align=None):
+        """Whether each geometry is within `distance` of `other` (`ST_DWithin`).
+
+        False where either side is missing or empty.
+        """
+        from sedonadb.expr import lit
+
+        _check_align(align)
+        other_expr = self._other(other)
+        # `distance` may be one number or a numeric Series of this frame,
+        # applied row by row as in GeoPandas.
+        row_wise = isinstance(distance, Series)
+        if row_wise:
+            threshold = _operand(self._df, distance).cast(pa.float64())
+        else:
+            # Validated like any other operand (arrays are rejected), then
+            # resolved to a plain number through the same path division uses,
+            # so NumPy, Arrow, and lit() scalars are accepted like floats.
+            _operand(self._df, distance)
+            value = _numeric_value(distance)
+            if not isinstance(value, numbers.Real) or isinstance(value, bool):
+                raise TypeError(
+                    f"dwithin() distance must be a number or a numeric Series of "
+                    f"this frame, got {type(distance).__name__}"
+                )
+            if math.isnan(value):
+                # Nothing is within NaN; the engine orders NaN above every
+                # number, so the comparison alone would say True.
+                return Series(self._df, lit(False), "dwithin")
+            threshold = lit(float(value))
+        # Measured through ST_Distance, so a row-wise threshold works and an
+        # empty operand (a missing distance) is never within.
+        within = self._expr.geo.distance(other_expr) <= threshold
+        if row_wise:
+            # The same NaN rule, per row.
+            within = within & ~threshold.funcs.isnan()
+        return Series(self._df, within.funcs.coalesce(lit(False)), "dwithin")
+
+    def distance(self, other, align=None):
+        """The distance from each geometry to `other` (`ST_Distance`).
+
+        Missing where either side is missing or empty, as in GeoPandas.
+        """
+        _check_align(align)
+        other_expr = self._other(other)
+        return Series(self._df, self._expr.geo.distance(other_expr), "distance")
+
+    def intersection(self, other, align=None):
+        """The intersection of each geometry with `other` (`ST_Intersection`)."""
+        _check_align(align)
+        return self._geo(self._expr.geo.intersection(self._other(other)))
+
+    def union(self, other, align=None):
+        """The union of each geometry with `other` (`ST_Union`)."""
+        _check_align(align)
+        return self._geo(self._expr.geo.union(self._other(other)))
+
+    def difference(self, other, align=None):
+        """Each geometry minus `other` (`ST_Difference`)."""
+        _check_align(align)
+        return self._geo(self._expr.geo.difference(self._other(other)))
+
+    def symmetric_difference(self, other, align=None):
+        """The symmetric difference of each geometry and `other` (`ST_SymDifference`)."""
+        _check_align(align)
+        return self._geo(self._expr.geo.sym_difference(self._other(other)))
+
     # -- serialization and CRS --------------------------------------------
 
     def to_wkt(self):
diff --git a/python/sedonadb-geopandas/tests/test_geoseries.py b/python/sedonadb-geopandas/tests/test_geoseries.py
index 5b33ec198..ad2113597 100644
--- a/python/sedonadb-geopandas/tests/test_geoseries.py
+++ b/python/sedonadb-geopandas/tests/test_geoseries.py
@@ -29,10 +29,18 @@ import numpy as np
 import pandas as pd
 import pyproj
 import pytest
+import sedonadb
 import shapely
+from packaging.version import Version
+from sedonadb.expr import lit
 
 import sedonadb_geopandas as sgpd
 
+# Released sedonadb 0.4.1 still has engine bugs fixed on main (boundary-only
+# predicates, distances to empty geometries); tests that need the fix skip
+# there.
+_OLD_ENGINE = Version(sedonadb.__version__) < Version("0.5.0a0")
+
 CORPUS = [
     "POINT (1 2)",
     "POINT Z (1 2 3)",
@@ -60,12 +68,35 @@ def _same_z(got, expected):
     )
 
 
+def _without_empty_parts(geometry):
+    """A multi-part geometry with its empty parts removed.
+
+    GEOS 3.12 keeps an empty operand as an empty part of a union or
+    symmetric difference (MULTIPOINT (EMPTY, (0 0))) where GEOS 3.13 drops
+    it (POINT (0 0)); the engine's GEOS version depends on the build. A
+    single remaining part stands on its own, as GEOS 3.13 returns it.
+    """
+    parts = shapely.get_parts(geometry)
+    if len(parts) <= 1 and geometry.geom_type in ("Point", "LineString", "Polygon"):
+        return geometry
+    non_empty = [part for part in parts if not part.is_empty]
+    if len(non_empty) == len(parts):
+        return geometry
+    if len(non_empty) == 1:
+        return non_empty[0]
+    if not non_empty:
+        return geometry
+    return type(geometry)(non_empty)
+
+
 def _same(got, expected):
     if expected is None or (isinstance(expected, float) and math.isnan(expected)):
         return got is None or (isinstance(got, float) and math.isnan(got))
     if isinstance(expected, shapely.Geometry):
         if not isinstance(got, shapely.Geometry):
             return False
+        got = _without_empty_parts(got)
+        expected = _without_empty_parts(expected)
         # The geometry type must match exactly, empties included: a POLYGON
         # EMPTY is not a POINT EMPTY, and a line is not its multipoint boundary.
         # The one allowance is a ring: WKB has no ring type, so a LinearRing
@@ -494,3 +525,248 @@ def test_set_crs_has_the_geopandas_signature():
     g = sgpd.from_geopandas(gpd.GeoDataFrame(geometry=gs)).geometry
     relabeled = g.set_crs("EPSG:32633", None, False, True)
     assert relabeled.to_geopandas().crs == "EPSG:32633"
+
+
+LEFT = [
+    "POINT (1 1)",
+    "POINT (2 0)",
+    "LINESTRING (0 0, 2 2)",
+    "POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))",
+    "POLYGON ((1 1, 3 1, 3 3, 1 3, 1 1))",
+    "POLYGON ((5 5, 6 5, 6 6, 5 6, 5 5))",
+    "MULTIPOINT ((0 0), (3 3))",
+    "POINT EMPTY",
+    None,
+    "POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))",
+]
+RIGHT = [
+    "POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))",
+    "POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))",
+    "LINESTRING (0 2, 2 0)",
+    "POLYGON ((1 1, 3 1, 3 3, 1 3, 1 1))",
+    "POINT (2 2)",
+    "POINT (0 0)",
+    "LINESTRING (0 0, 1 1)",
+    "POINT (0 0)",
+    "POINT (0 0)",
+    None,
+]
+PREDICATES = [
+    "intersects",
+    "contains",
+    "within",
+    "touches",
+    "crosses",
+    "overlaps",
+    "covers",
+    "covered_by",
+    "disjoint",
+    "geom_equals",
+]
+SET_OPERATIONS = ["intersection", "union", "difference", "symmetric_difference"]
+
+
+def _binary_case():
+    left = gpd.GeoSeries.from_wkt(LEFT, crs="EPSG:3857")
+    right = gpd.GeoSeries.from_wkt(RIGHT, crs="EPSG:3857")
+    frame = gpd.GeoDataFrame({"b": right}, geometry=left)
+    gdf = sgpd.from_geopandas(frame)
+    return left, right, gdf.geometry, gdf["b"]
+
+
+@pytest.mark.parametrize("name", PREDICATES + ["distance"] + SET_OPERATIONS)
+@pytest.mark.parametrize("operand", ["column", "scalar"])
+def test_binary_operations_match_geopandas(name, operand):
+    if _OLD_ENGINE and name == "distance":
+        pytest.skip("sedonadb < 0.5 measures empty geometries as distance 0 (#1356)")
+    # Against a column of the same frame (row by row) and against a single
+    # Shapely geometry, including empty and missing operands: GeoPandas
+    # answers False for a predicate and NaN for a distance there.
+    left, right, g, b = _binary_case()
+    scalar = shapely.from_wkt("POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))")
+    other, reference_other = (b, right) if operand == "column" else (scalar, scalar)
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore")
+        got = getattr(g, name)(other).to_pandas().tolist()
+        expected = getattr(left, name)(reference_other).tolist()
+    for value, reference in zip(got, expected):
+        assert _same(value, reference), (name, value, reference)
+
+
+@pytest.mark.parametrize("operand", ["column", "scalar"])
+@pytest.mark.skipif(
+    _OLD_ENGINE, reason="sedonadb < 0.5 measures empty geometries as distance 0 (#1356)"
+)
+def test_dwithin_matches_geopandas(operand):
+    left, right, g, b = _binary_case()
+    scalar = shapely.from_wkt("POINT (3 3)")
+    other, reference_other = (b, right) if operand == "column" else (scalar, scalar)
+    for distance in (0.0, 1.0, 5.0):
+        got = g.dwithin(other, distance).to_pandas().tolist()
+        assert got == left.dwithin(reference_other, distance).tolist()
+
+
+@pytest.mark.skipif(
+    _OLD_ENGINE, reason="sedonadb < 0.5 measures empty geometries as distance 0 (#1356)"
+)
+def test_empty_operands_have_no_distance():
+    # The distance to an empty geometry is undefined, as in GeoPandas (and
+    # PostGIS), so dwithin is False there.
+    gs = gpd.GeoSeries.from_wkt(["POINT EMPTY", "POINT (0 0)"], crs="EPSG:3857")
+    g = sgpd.from_geopandas(gpd.GeoDataFrame(geometry=gs)).geometry
+    distances = g.distance(shapely.Point(0, 0)).to_pandas().tolist()
+    assert math.isnan(distances[0]) and distances[1] == 0.0
+    assert g.dwithin(shapely.Point(0, 0), 1.0).to_pandas().tolist() == [False, True]
+    assert g.distance(shapely.Point()).to_pandas().isna().all()
+
+
+def test_scalar_geometry_takes_the_column_crs():
+    # A Shapely geometry carries no CRS; comparing it with a column that has
+    # one made the engine refuse the mismatched CRS.
+    gs = gpd.GeoSeries.from_wkt(["POINT (1 1)"], crs="EPSG:3857")
+    g = sgpd.from_geopandas(gpd.GeoDataFrame(geometry=gs)).geometry
+    square = shapely.from_wkt("POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))")
+    assert g.within(square).to_pandas().tolist() == [True]
+    assert g.intersection(square).to_geopandas().crs == "EPSG:3857"
+
+
+def test_binary_operations_reject_other_frames_and_alignment():
+    gs = gpd.GeoSeries.from_wkt(["POINT (1 1)"], crs="EPSG:3857")
+    g = sgpd.from_geopandas(gpd.GeoDataFrame(geometry=gs)).geometry
+    other = sgpd.from_geopandas(gpd.GeoDataFrame(geometry=gs)).geometry
+    with pytest.raises(ValueError, match="different DataFrames"):
+        g.intersects(other)
+    with pytest.raises(ValueError, match="align"):
+        g.intersects(shapely.Point(1, 1), align=True)
+    with pytest.raises(TypeError):
+        g.intersects([shapely.Point(1, 1)])
+
+
+@pytest.mark.skipif(
+    _OLD_ENGINE,
+    reason="sedonadb < 0.5 misclassifies these boundary-only cases (#1165)",
+)
+@pytest.mark.parametrize(
+    "name,left,right",
+    [
+        # A line through a polygon corner touches it.
+        ("touches", "LINESTRING (1 3, 3 1)", "POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))"),
+        # A multipoint with one point inside and one on the boundary is within.
+        ("within", "MULTIPOINT ((0 0), (1 1))", "POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))"),
+    ],
+    ids=["touches-corner", "within-boundary-point"],
+)
+def test_boundary_only_predicates_match_geopandas(name, left, right):
+    gs = gpd.GeoSeries.from_wkt([left], crs="EPSG:3857")
+    g = sgpd.from_geopandas(gpd.GeoDataFrame(geometry=gs)).geometry
+    expected = getattr(gs, name)(shapely.from_wkt(right)).tolist()
+    assert expected == [True]
+    assert getattr(g, name)(shapely.from_wkt(right)).to_pandas().tolist() == expected
+
+
+def test_shapely_operand_takes_a_geography_columns_kind():
+    # A Shapely operand was built as planar geometry, and the engine has no
+    # kernel pairing geography with geometry.
+    gdf = sgpd.GeoDataFrame(
+        sgpd.default_context().sql("SELECT ST_GeogFromWKT('POINT (0 0)') AS g"),
+        geometry="g",
+    )
+    assert gdf.geometry.intersects(shapely.Point(0, 0)).to_pandas().tolist() == [True]
+    # Spherical distance, in meters: one degree of latitude.
+    distance = gdf.geometry.distance(shapely.Point(0, 1)).to_pandas().tolist()[0]
+    assert 111_000 < distance < 111_400
+
+
+def test_literal_operands_are_bound_and_take_the_column_crs():
+    # A bare lit() has no context, so functions could not be applied to it;
+    # once bound, a CRS-less geometry literal takes the column's CRS, while
+    # one carrying a different CRS of its own is still refused.
+    gs = gpd.GeoSeries.from_wkt(["POINT (0 0)"], crs="EPSG:3857")
+    g = sgpd.from_geopandas(gpd.GeoDataFrame(geometry=gs)).geometry
+    assert g.distance(lit(shapely.Point(3, 4))).to_pandas().tolist() == [5.0]
+    assert g.dwithin(lit(shapely.Point(3, 4)), 10).to_pandas().tolist() == [True]
+    other_crs = lit(gpd.GeoSeries([shapely.Point(3, 4)], crs="EPSG:4326"))
+    with pytest.raises(Exception, match="CRS"):
+        g.distance(other_crs).to_pandas()
+
+
+def test_two_empty_geometries_are_equal():
+    # GeoPandas treats any two empty geometries as equal; the engine does not.
+    gs = gpd.GeoSeries.from_wkt(["POINT EMPTY", "POLYGON EMPTY", None], crs="EPSG:3857")
+    g = sgpd.from_geopandas(gpd.GeoDataFrame(geometry=gs)).geometry
+    empty = shapely.from_wkt("POINT EMPTY")
+    assert g.geom_equals(empty).to_pandas().tolist() == gs.geom_equals(empty).tolist()
+
+
+def test_dwithin_nan_threshold_is_never_within():
+    # The engine orders NaN above every number, so `distance <= NaN` was True.
+    gs = gpd.GeoSeries.from_wkt(["POINT (0 0)", "POINT (1 1)"], crs="EPSG:3857")
+    g = sgpd.from_geopandas(gpd.GeoDataFrame(geometry=gs)).geometry
+    got = g.dwithin(shapely.Point(0, 0), float("nan")).to_pandas().tolist()
+    assert (
+        got == gs.dwithin(shapely.Point(0, 0), float("nan")).tolist() == [False, False]
+    )
+
+
+def test_dwithin_accepts_a_row_wise_threshold():
+    # GeoPandas applies a Series of thresholds row by row; the same NaN rule
+    # holds per row.
+    gs = gpd.GeoSeries.from_wkt(
+        ["POINT (0 0)", "POINT (3 4)", "POINT (1 0)", "POINT (0 0)"], crs="EPSG:3857"
+    )
+    thresholds = [1.0, 5.0, 0.5, float("nan")]
+    gdf = sgpd.from_geopandas(gpd.GeoDataFrame({"d": thresholds}, geometry=gs))
+    got = gdf.geometry.dwithin(shapely.Point(0, 0), gdf["d"]).to_pandas().tolist()
+    expected = gs.dwithin(shapely.Point(0, 0), pd.Series(thresholds)).tolist()
+    assert got == expected == [True, True, False, False]
+    with pytest.raises(TypeError, match="distance"):
+        gdf.geometry.dwithin(shapely.Point(0, 0), "far")
+
+
+def test_literal_operand_takes_a_geography_columns_kind():
+    # A bare Shapely operand was already built as geography; one wrapped in
+    # lit() still arrived as planar geometry, which no kernel pairs with
+    # geography.
+    gdf = sgpd.GeoDataFrame(
+        sgpd.default_context().sql("SELECT ST_GeogFromWKT('POINT (0 0)') AS g"),
+        geometry="g",
+    )
+    g = gdf.geometry
+    assert g.intersects(lit(shapely.Point(0, 0))).to_pandas().tolist() == [True]
+    wrapped = g.distance(lit(shapely.Point(0, 1))).to_pandas().tolist()
+    bare = g.distance(shapely.Point(0, 1)).to_pandas().tolist()
+    assert wrapped == bare
+
+
+@pytest.mark.parametrize(
+    "threshold",
+    [np.float64(5.0), np.float32(4.9), np.int64(5), np.float64("nan")],
+    ids=["float64", "float32", "int64", "nan"],
+)
+def test_dwithin_accepts_numpy_thresholds(threshold):
+    # NumPy scalars were normalized into Arrow scalars before the numeric
+    # check and rejected, where GeoPandas accepts them.
+    gs = gpd.GeoSeries.from_wkt(["POINT (0 0)", "POINT (3 4)"], crs="EPSG:3857")
+    g = sgpd.from_geopandas(gpd.GeoDataFrame(geometry=gs)).geometry
+    got = g.dwithin(shapely.Point(0, 0), threshold).to_pandas().tolist()
+    assert got == gs.dwithin(shapely.Point(0, 0), threshold).tolist()
+
+
+@pytest.mark.xfail(
+    not _OLD_ENGINE,
+    strict=True,
+    reason="engine misclassifies collections mixing dimensions (apache/sedona-db#1383)",
+)
+def test_touches_with_a_mixed_dimension_collection():
+    # The line lies on the polygon's boundary but the point is inside it, so
+    # the interiors intersect and the two do not touch. Released 0.4.1 gets
+    # this right; the tg update after it regressed it.
+    gs = gpd.GeoSeries.from_wkt(
+        ["POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))"], crs="EPSG:3857"
+    )
+    g = sgpd.from_geopandas(gpd.GeoDataFrame(geometry=gs)).geometry
+    collection = shapely.from_wkt(
+        "GEOMETRYCOLLECTION (POINT (1 1), LINESTRING (0 0, 1 0))"
+    )
+    assert gs.touches(collection).tolist() == [False]
+    assert g.touches(collection).to_pandas().tolist() == [False]