Skip to main content

vortex_spatial/scalar_fn/
intersects.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! `ST_Intersects`: OGC intersection test between two native geometries.
5
6use geo::Intersects;
7use vortex_array::ArrayRef;
8use vortex_array::arrays::ScalarFnArray;
9use vortex_array::dtype::DType;
10use vortex_array::scalar_fn::EmptyOptions;
11use vortex_array::scalar_fn::ScalarFnId;
12use vortex_array::scalar_fn::TypedScalarFnInstance;
13use vortex_array::scalar_fn::unstable::row::RowFn;
14use vortex_array::scalar_fn::unstable::row::RowVisitor;
15use vortex_error::VortexResult;
16use vortex_session::VortexSession;
17use vortex_session::registry::CachedId;
18
19use crate::scalar_fn::row::visit_binary_geo_predicate;
20
21/// OGC `ST_Intersects` (not disjoint; boundary contact counts) between two native geometry
22/// operands, each a column or a constant literal.
23#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
24pub struct SpatialIntersects;
25
26impl SpatialIntersects {
27    /// A lazy `ScalarFnArray` computing per-row whether operands `a` and `b` intersect; either may
28    /// be constant. The output length is taken from `a`.
29    pub fn try_new(a: ArrayRef, b: ArrayRef) -> VortexResult<ScalarFnArray> {
30        ScalarFnArray::try_new(
31            TypedScalarFnInstance::new(SpatialIntersects, EmptyOptions).erased(),
32            vec![a, b],
33        )
34    }
35}
36
37impl RowFn for SpatialIntersects {
38    type Options = EmptyOptions;
39
40    const ARG_NAMES: &'static [&'static str] = &["a", "b"];
41    const INFALLIBLE: bool = true;
42
43    fn id(&self) -> ScalarFnId {
44        static ID: CachedId = CachedId::new("vortex.st.intersects");
45        *ID
46    }
47
48    fn serialize(&self, _: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
49        Ok(Some(vec![]))
50    }
51
52    fn deserialize(&self, _: &[u8], _: &VortexSession) -> VortexResult<Self::Options> {
53        Ok(EmptyOptions)
54    }
55
56    fn dispatch<V: RowVisitor>(
57        &self,
58        _options: &Self::Options,
59        _args: &[DType],
60        visitor: V,
61    ) -> VortexResult<V::VisitResult> {
62        // Disjoint bounding rects prove the geometries disjoint; rect contact (closed test)
63        // falls through to the exact test.
64        visit_binary_geo_predicate(
65            visitor,
66            |x, y| x.intersects(y),
67            |a, b| (!a.intersects(b)).then_some(false),
68        )
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use std::sync::LazyLock;
75
76    use geo_types::Coord;
77    use geo_types::Geometry;
78    use geo_types::LineString;
79    use geo_types::MultiPolygon;
80    use geo_types::Polygon;
81    use rstest::rstest;
82    use vortex_array::ArrayRef;
83    use vortex_array::Canonical;
84    use vortex_array::ExecutionCtx;
85    use vortex_array::IntoArray;
86    use vortex_array::VortexSessionExecute;
87    use vortex_array::arrays::BoolArray;
88    use vortex_array::arrays::ConstantArray;
89    use vortex_array::assert_arrays_eq;
90    use vortex_array::dtype::DType;
91    use vortex_array::dtype::Nullability;
92    use vortex_array::dtype::PType;
93    use vortex_array::scalar::Scalar;
94    use vortex_array::scalar_fn::EmptyOptions;
95    use vortex_array::scalar_fn::ScalarFnVTable;
96    use vortex_array::validity::Validity;
97    use vortex_buffer::BitBuffer;
98    use vortex_error::VortexResult;
99    use vortex_error::vortex_err;
100    use vortex_session::VortexSession;
101    use wkb::writer::WriteOptions;
102
103    use super::SpatialIntersects;
104    use crate::test_harness::nullable_point_column;
105    use crate::test_harness::point_column;
106
107    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
108
109    /// A rectangle polygon with corners `(x0, y0)` and `(x1, y1)`, no holes.
110    fn rect_polygon(x0: f64, y0: f64, x1: f64, y1: f64) -> Polygon {
111        Polygon::new(
112            LineString::from(vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)]),
113            vec![],
114        )
115    }
116
117    /// The query region shared by the point tests: a `10x10` square with a `4..6` square hole.
118    fn donut() -> Geometry {
119        Geometry::Polygon(Polygon::new(
120            LineString::from(vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]),
121            vec![LineString::from(vec![
122                (4.0, 4.0),
123                (6.0, 4.0),
124                (6.0, 6.0),
125                (4.0, 6.0),
126            ])],
127        ))
128    }
129
130    /// Probes for [`donut`], one per verdict class: interior, exterior, on the outer boundary,
131    /// and inside the hole.
132    fn donut_probes() -> VortexResult<ArrayRef> {
133        point_column(vec![2.0, 20.0, 0.0, 5.0], vec![2.0, 20.0, 5.0, 5.0])
134    }
135
136    /// [`donut_probes`]'s verdicts: interior and boundary contact intersect; exterior and
137    /// in-hole do not.
138    const DONUT_EXPECTED: [bool; 4] = [true, false, true, false];
139
140    /// A constant column of length `len`, every row the native form of `geometry`.
141    fn geometry_constant(geometry: &Geometry, len: usize) -> VortexResult<ArrayRef> {
142        let mut buf = Vec::new();
143        wkb::writer::write_geometry(&mut buf, geometry, &WriteOptions::default())
144            .map_err(|e| vortex_err!("writing WKB failed: {e}"))?;
145        let session = VortexSession::empty();
146        let scalar = crate::extension::native_geometry_scalar_from_wkb(&buf, &session)?
147            .ok_or_else(|| vortex_err!("unsupported geometry type"))?;
148        Ok(ConstantArray::new(scalar, len).into_array())
149    }
150
151    /// Materialize `array` so it is no longer a `Constant`, forcing the non-constant kernel paths.
152    fn materialize(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
153        Ok(array.execute::<Canonical>(ctx)?.into_array())
154    }
155
156    /// Execute `SpatialIntersects(a, b)` and assert the per-row verdicts equal `expected`.
157    fn assert_intersects(
158        a: ArrayRef,
159        b: ArrayRef,
160        expected: impl IntoIterator<Item = bool>,
161    ) -> VortexResult<()> {
162        let mut ctx = SESSION.create_execution_ctx();
163        let intersects = SpatialIntersects::try_new(a, b)?.into_array();
164        assert_arrays_eq!(intersects, BoolArray::from_iter(expected), &mut ctx);
165        Ok(())
166    }
167
168    /// Constant vs constant: overlapping and touching (edge or corner) polygons intersect,
169    /// disjoint ones do not; every output row carries the same verdict.
170    #[rstest]
171    #[case::overlapping(rect_polygon(2.0, 2.0, 6.0, 6.0), true)]
172    #[case::touching_edge(rect_polygon(4.0, 0.0, 8.0, 4.0), true)]
173    #[case::touching_corner(rect_polygon(4.0, 4.0, 8.0, 8.0), true)]
174    #[case::disjoint(rect_polygon(20.0, 20.0, 24.0, 24.0), false)]
175    fn constant_vs_constant_polygons(
176        #[case] other: Polygon,
177        #[case] expected: bool,
178    ) -> VortexResult<()> {
179        let a = geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 3)?;
180        let b = geometry_constant(&Geometry::Polygon(other), 3)?;
181        assert_intersects(a, b, [expected; 3])
182    }
183
184    /// Point column vs constant polygon, with the constant on either side since intersection
185    /// is symmetric: the [`DONUT_EXPECTED`] verdicts.
186    #[test]
187    fn point_column_vs_constant_polygon() -> VortexResult<()> {
188        assert_intersects(
189            donut_probes()?,
190            geometry_constant(&donut(), 4)?,
191            DONUT_EXPECTED,
192        )?;
193        assert_intersects(
194            geometry_constant(&donut(), 4)?,
195            donut_probes()?,
196            DONUT_EXPECTED,
197        )
198    }
199
200    /// Point column vs constant multipolygon: a point in either part intersects, a point in
201    /// neither does not.
202    #[test]
203    fn point_column_vs_constant_multipolygon() -> VortexResult<()> {
204        let query = Geometry::MultiPolygon(MultiPolygon::new(vec![
205            rect_polygon(0.0, 0.0, 2.0, 2.0),
206            rect_polygon(10.0, 10.0, 12.0, 12.0),
207        ]));
208        let points = point_column(vec![1.0, 11.0, 5.0], vec![1.0, 11.0, 5.0])?;
209        assert_intersects(points, geometry_constant(&query, 3)?, [true, true, false])
210    }
211
212    /// Polygon column vs constant: the same pairs and verdicts as
213    /// [`constant_vs_constant_polygons`].
214    #[rstest]
215    #[case::overlapping(rect_polygon(2.0, 2.0, 6.0, 6.0), true)]
216    #[case::touching_edge(rect_polygon(4.0, 0.0, 8.0, 4.0), true)]
217    #[case::disjoint(rect_polygon(20.0, 20.0, 24.0, 24.0), false)]
218    fn polygon_column_vs_constant(
219        #[case] other: Polygon,
220        #[case] expected: bool,
221    ) -> VortexResult<()> {
222        let mut ctx = SESSION.create_execution_ctx();
223        let column = materialize(geometry_constant(&Geometry::Polygon(other), 2)?, &mut ctx)?;
224        let query = geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 2)?;
225        assert_intersects(column, query, [expected; 2])
226    }
227
228    /// Point column vs point column: rows intersect exactly at equal coordinates.
229    #[test]
230    fn point_column_vs_point_column() -> VortexResult<()> {
231        let a = point_column(vec![0.0, 1.0], vec![0.0, 1.0])?;
232        let b = point_column(vec![0.0, 2.0], vec![0.0, 1.0])?;
233        assert_intersects(a, b, [true, false])
234    }
235
236    /// Point column vs polygon column pairwise: agrees with point column vs constant on the
237    /// same data.
238    #[test]
239    fn columns_agree_with_constant() -> VortexResult<()> {
240        let mut ctx = SESSION.create_execution_ctx();
241
242        let constant = geometry_constant(&donut(), 4)?;
243        let column = materialize(constant.clone(), &mut ctx)?;
244
245        let against_constant = SpatialIntersects::try_new(donut_probes()?, constant)?.into_array();
246        let pairwise = SpatialIntersects::try_new(donut_probes()?, column)?.into_array();
247
248        let expected = BoolArray::from_iter(DONUT_EXPECTED);
249        assert_arrays_eq!(against_constant, expected, &mut ctx);
250        assert_arrays_eq!(pairwise, expected, &mut ctx);
251        Ok(())
252    }
253
254    /// An empty constant geometry intersects nothing.
255    #[test]
256    fn empty_constant_intersects_nothing() -> VortexResult<()> {
257        let empty = Geometry::LineString(LineString::new(Vec::<Coord>::new()));
258        let points = point_column(vec![0.0, 1.0], vec![0.0, 1.0])?;
259        assert_intersects(points, geometry_constant(&empty, 2)?, [false, false])
260    }
261
262    /// Output nullability mirrors the operands: nullable if any operand is nullable, otherwise
263    /// non-nullable.
264    #[test]
265    fn output_nullability_mirrors_operands() -> VortexResult<()> {
266        let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
267        let non_nullable =
268            SpatialIntersects.return_dtype(&EmptyOptions, &[dtype.clone(), dtype.clone()])?;
269        assert_eq!(non_nullable, DType::Bool(Nullability::NonNullable));
270        let nullable =
271            SpatialIntersects.return_dtype(&EmptyOptions, &[dtype.as_nullable(), dtype])?;
272        assert_eq!(nullable, DType::Bool(Nullability::Nullable));
273        Ok(())
274    }
275
276    /// A null row in a geometry operand yields a null verdict; valid rows keep their verdict
277    /// (interior intersects, exterior does not).
278    #[test]
279    fn intersects_propagates_null_rows() -> VortexResult<()> {
280        let mut ctx = SESSION.create_execution_ctx();
281
282        let points = nullable_point_column(vec![Some((2.0, 2.0)), None, Some((20.0, 20.0))])?;
283        let query = geometry_constant(&donut(), 3)?;
284        let intersects = SpatialIntersects::try_new(points, query)?.into_array();
285
286        let expected = BoolArray::new(
287            BitBuffer::from_iter([true, false, false]),
288            Validity::from_iter([true, false, true]),
289        )
290        .into_array();
291        assert_arrays_eq!(intersects, expected, &mut ctx);
292        Ok(())
293    }
294
295    /// A constant-null operand produces an all-null output.
296    #[test]
297    fn intersects_constant_null_is_all_null() -> VortexResult<()> {
298        let mut ctx = SESSION.create_execution_ctx();
299
300        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().as_nullable();
301        let null_const = ConstantArray::new(Scalar::null(point_dtype), 2).into_array();
302        let points = point_column(vec![2.0, 20.0], vec![2.0, 20.0])?;
303        let intersects = SpatialIntersects::try_new(null_const, points)?.into_array();
304
305        let expected =
306            BoolArray::new(BitBuffer::from_iter([false, false]), Validity::AllInvalid).into_array();
307        assert_arrays_eq!(intersects, expected, &mut ctx);
308        Ok(())
309    }
310
311    /// Both operands nullable columns: the verdict is null wherever either row is null, and
312    /// computed on the rows valid in both (points intersect exactly when equal).
313    #[test]
314    fn intersects_propagates_column_pair_nulls() -> VortexResult<()> {
315        let mut ctx = SESSION.create_execution_ctx();
316
317        let a = nullable_point_column(vec![
318            Some((0.0, 0.0)),
319            None,
320            Some((2.0, 2.0)),
321            Some((3.0, 3.0)),
322        ])?;
323        let b = nullable_point_column(vec![
324            Some((0.0, 0.0)),
325            Some((5.0, 5.0)),
326            None,
327            Some((9.0, 9.0)),
328        ])?;
329        let intersects = SpatialIntersects::try_new(a, b)?.into_array();
330
331        let expected = BoolArray::new(
332            BitBuffer::from_iter([true, false, false, false]),
333            Validity::from_iter([true, false, false, true]),
334        )
335        .into_array();
336        assert_arrays_eq!(intersects, expected, &mut ctx);
337        Ok(())
338    }
339
340    /// An entirely-null geometry column yields an all-null output.
341    #[test]
342    fn intersects_all_null_column_is_all_null() -> VortexResult<()> {
343        let mut ctx = SESSION.create_execution_ctx();
344
345        let points = nullable_point_column(vec![None, None])?;
346        let query = geometry_constant(&donut(), 2)?;
347        let intersects = SpatialIntersects::try_new(points, query)?.into_array();
348
349        let expected =
350            BoolArray::new(BitBuffer::from_iter([false, false]), Validity::AllInvalid).into_array();
351        assert_arrays_eq!(intersects, expected, &mut ctx);
352        Ok(())
353    }
354
355    /// Two nullable columns whose nulls never line up: the combined mask is empty, so the output
356    /// is all null.
357    #[test]
358    fn intersects_column_pair_all_null() -> VortexResult<()> {
359        let mut ctx = SESSION.create_execution_ctx();
360
361        let a = nullable_point_column(vec![Some((0.0, 0.0)), None])?;
362        let b = nullable_point_column(vec![None, Some((1.0, 1.0))])?;
363        let intersects = SpatialIntersects::try_new(a, b)?.into_array();
364
365        let expected =
366            BoolArray::new(BitBuffer::from_iter([false, false]), Validity::AllInvalid).into_array();
367        assert_arrays_eq!(intersects, expected, &mut ctx);
368        Ok(())
369    }
370
371    /// A non-geometry operand dtype is rejected up front, before execution.
372    #[test]
373    fn non_geometry_operand_is_rejected() -> VortexResult<()> {
374        let spatial_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
375        let numeric = DType::Primitive(PType::I32, Nullability::NonNullable);
376        let result = SpatialIntersects.return_dtype(&EmptyOptions, &[spatial_dtype, numeric]);
377        assert!(result.is_err());
378        Ok(())
379    }
380}