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 geo_types::Coord;
75    use geo_types::Geometry;
76    use geo_types::LineString;
77    use geo_types::MultiPolygon;
78    use geo_types::Polygon;
79    use rstest::rstest;
80    use vortex_array::ArrayRef;
81    use vortex_array::Canonical;
82    use vortex_array::ExecutionCtx;
83    use vortex_array::IntoArray;
84    use vortex_array::VortexSessionExecute;
85    use vortex_array::arrays::BoolArray;
86    use vortex_array::arrays::ConstantArray;
87    use vortex_array::assert_arrays_eq;
88    use vortex_array::dtype::DType;
89    use vortex_array::dtype::Nullability;
90    use vortex_array::dtype::PType;
91    use vortex_array::scalar::Scalar;
92    use vortex_array::scalar_fn::EmptyOptions;
93    use vortex_array::scalar_fn::ScalarFnVTable;
94    use vortex_array::validity::Validity;
95    use vortex_arrow::ArrowSessionExt;
96    use vortex_buffer::BitBuffer;
97    use vortex_error::VortexResult;
98    use vortex_error::vortex_err;
99    use wkb::writer::WriteOptions;
100
101    use super::SpatialIntersects;
102    use crate::test_harness::nullable_point_column;
103    use crate::test_harness::point_column;
104
105    /// A rectangle polygon with corners `(x0, y0)` and `(x1, y1)`, no holes.
106    fn rect_polygon(x0: f64, y0: f64, x1: f64, y1: f64) -> Polygon {
107        Polygon::new(
108            LineString::from(vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)]),
109            vec![],
110        )
111    }
112
113    /// The query region shared by the point tests: a `10x10` square with a `4..6` square hole.
114    fn donut() -> Geometry {
115        Geometry::Polygon(Polygon::new(
116            LineString::from(vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]),
117            vec![LineString::from(vec![
118                (4.0, 4.0),
119                (6.0, 4.0),
120                (6.0, 6.0),
121                (4.0, 6.0),
122            ])],
123        ))
124    }
125
126    /// Probes for [`donut`], one per verdict class: interior, exterior, on the outer boundary,
127    /// and inside the hole.
128    fn donut_probes() -> VortexResult<ArrayRef> {
129        point_column(vec![2.0, 20.0, 0.0, 5.0], vec![2.0, 20.0, 5.0, 5.0])
130    }
131
132    /// [`donut_probes`]'s verdicts: interior and boundary contact intersect; exterior and
133    /// in-hole do not.
134    const DONUT_EXPECTED: [bool; 4] = [true, false, true, false];
135
136    /// A constant column of length `len`, every row the native form of `geometry`.
137    fn geometry_constant(geometry: &Geometry, len: usize) -> VortexResult<ArrayRef> {
138        let mut buf = Vec::new();
139        wkb::writer::write_geometry(&mut buf, geometry, &WriteOptions::default())
140            .map_err(|e| vortex_err!("writing WKB failed: {e}"))?;
141        let session = vortex_array::array_session();
142        let scalar = crate::extension::native_geometry_scalar_from_wkb(&buf, &session.arrow())?
143            .ok_or_else(|| vortex_err!("unsupported geometry type"))?;
144        Ok(ConstantArray::new(scalar, len).into_array())
145    }
146
147    /// Materialize `array` so it is no longer a `Constant`, forcing the non-constant kernel paths.
148    fn materialize(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
149        Ok(array.execute::<Canonical>(ctx)?.into_array())
150    }
151
152    /// Execute `SpatialIntersects(a, b)` and assert the per-row verdicts equal `expected`.
153    fn assert_intersects(
154        a: ArrayRef,
155        b: ArrayRef,
156        expected: impl IntoIterator<Item = bool>,
157    ) -> VortexResult<()> {
158        let session = vortex_array::array_session();
159        let mut ctx = session.create_execution_ctx();
160        let intersects = SpatialIntersects::try_new(a, b)?.into_array();
161        assert_arrays_eq!(intersects, BoolArray::from_iter(expected), &mut ctx);
162        Ok(())
163    }
164
165    /// Constant vs constant: overlapping and touching (edge or corner) polygons intersect,
166    /// disjoint ones do not; every output row carries the same verdict.
167    #[rstest]
168    #[case::overlapping(rect_polygon(2.0, 2.0, 6.0, 6.0), true)]
169    #[case::touching_edge(rect_polygon(4.0, 0.0, 8.0, 4.0), true)]
170    #[case::touching_corner(rect_polygon(4.0, 4.0, 8.0, 8.0), true)]
171    #[case::disjoint(rect_polygon(20.0, 20.0, 24.0, 24.0), false)]
172    fn constant_vs_constant_polygons(
173        #[case] other: Polygon,
174        #[case] expected: bool,
175    ) -> VortexResult<()> {
176        let a = geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 3)?;
177        let b = geometry_constant(&Geometry::Polygon(other), 3)?;
178        assert_intersects(a, b, [expected; 3])
179    }
180
181    /// Point column vs constant polygon, with the constant on either side since intersection
182    /// is symmetric: the [`DONUT_EXPECTED`] verdicts.
183    #[test]
184    fn point_column_vs_constant_polygon() -> VortexResult<()> {
185        assert_intersects(
186            donut_probes()?,
187            geometry_constant(&donut(), 4)?,
188            DONUT_EXPECTED,
189        )?;
190        assert_intersects(
191            geometry_constant(&donut(), 4)?,
192            donut_probes()?,
193            DONUT_EXPECTED,
194        )
195    }
196
197    /// Point column vs constant multipolygon: a point in either part intersects, a point in
198    /// neither does not.
199    #[test]
200    fn point_column_vs_constant_multipolygon() -> VortexResult<()> {
201        let query = Geometry::MultiPolygon(MultiPolygon::new(vec![
202            rect_polygon(0.0, 0.0, 2.0, 2.0),
203            rect_polygon(10.0, 10.0, 12.0, 12.0),
204        ]));
205        let points = point_column(vec![1.0, 11.0, 5.0], vec![1.0, 11.0, 5.0])?;
206        assert_intersects(points, geometry_constant(&query, 3)?, [true, true, false])
207    }
208
209    /// Polygon column vs constant: the same pairs and verdicts as
210    /// [`constant_vs_constant_polygons`].
211    #[rstest]
212    #[case::overlapping(rect_polygon(2.0, 2.0, 6.0, 6.0), true)]
213    #[case::touching_edge(rect_polygon(4.0, 0.0, 8.0, 4.0), true)]
214    #[case::disjoint(rect_polygon(20.0, 20.0, 24.0, 24.0), false)]
215    fn polygon_column_vs_constant(
216        #[case] other: Polygon,
217        #[case] expected: bool,
218    ) -> VortexResult<()> {
219        let session = vortex_array::array_session();
220        let mut ctx = session.create_execution_ctx();
221        let column = materialize(geometry_constant(&Geometry::Polygon(other), 2)?, &mut ctx)?;
222        let query = geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 2)?;
223        assert_intersects(column, query, [expected; 2])
224    }
225
226    /// Point column vs point column: rows intersect exactly at equal coordinates.
227    #[test]
228    fn point_column_vs_point_column() -> VortexResult<()> {
229        let a = point_column(vec![0.0, 1.0], vec![0.0, 1.0])?;
230        let b = point_column(vec![0.0, 2.0], vec![0.0, 1.0])?;
231        assert_intersects(a, b, [true, false])
232    }
233
234    /// Point column vs polygon column pairwise: agrees with point column vs constant on the
235    /// same data.
236    #[test]
237    fn columns_agree_with_constant() -> VortexResult<()> {
238        let session = vortex_array::array_session();
239        let mut ctx = session.create_execution_ctx();
240
241        let constant = geometry_constant(&donut(), 4)?;
242        let column = materialize(constant.clone(), &mut ctx)?;
243
244        let against_constant = SpatialIntersects::try_new(donut_probes()?, constant)?.into_array();
245        let pairwise = SpatialIntersects::try_new(donut_probes()?, column)?.into_array();
246
247        assert_arrays_eq!(against_constant, pairwise, &mut ctx);
248        Ok(())
249    }
250
251    /// An empty constant geometry intersects nothing.
252    #[test]
253    fn empty_constant_intersects_nothing() -> VortexResult<()> {
254        let empty = Geometry::LineString(LineString::new(Vec::<Coord>::new()));
255        let points = point_column(vec![0.0, 1.0], vec![0.0, 1.0])?;
256        assert_intersects(points, geometry_constant(&empty, 2)?, [false, false])
257    }
258
259    /// Output nullability mirrors the operands: nullable if any operand is nullable, otherwise
260    /// non-nullable.
261    #[test]
262    fn output_nullability_mirrors_operands() -> VortexResult<()> {
263        let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
264        let non_nullable =
265            SpatialIntersects.return_dtype(&EmptyOptions, &[dtype.clone(), dtype.clone()])?;
266        assert!(!non_nullable.is_nullable());
267        let nullable =
268            SpatialIntersects.return_dtype(&EmptyOptions, &[dtype.as_nullable(), dtype])?;
269        assert!(nullable.is_nullable());
270        Ok(())
271    }
272
273    /// A null row in a geometry operand yields a null verdict; valid rows keep their verdict
274    /// (interior intersects, exterior does not).
275    #[test]
276    fn intersects_propagates_null_rows() -> VortexResult<()> {
277        let session = vortex_array::array_session();
278        let mut ctx = session.create_execution_ctx();
279
280        let points = nullable_point_column(vec![Some((2.0, 2.0)), None, Some((20.0, 20.0))])?;
281        let query = geometry_constant(&donut(), 3)?;
282        let intersects = SpatialIntersects::try_new(points, query)?.into_array();
283
284        let expected = BoolArray::new(
285            BitBuffer::from_iter([true, false, false]),
286            Validity::from_iter([true, false, true]),
287        )
288        .into_array();
289        assert_arrays_eq!(intersects, expected, &mut ctx);
290        Ok(())
291    }
292
293    /// A constant-null operand produces an all-null output.
294    #[test]
295    fn intersects_constant_null_is_all_null() -> VortexResult<()> {
296        let session = vortex_array::array_session();
297        let mut ctx = session.create_execution_ctx();
298
299        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().as_nullable();
300        let null_const = ConstantArray::new(Scalar::null(point_dtype), 2).into_array();
301        let points = point_column(vec![2.0, 20.0], vec![2.0, 20.0])?;
302        let intersects = SpatialIntersects::try_new(null_const, points)?.into_array();
303
304        let expected =
305            BoolArray::new(BitBuffer::from_iter([false, false]), Validity::AllInvalid).into_array();
306        assert_arrays_eq!(intersects, expected, &mut ctx);
307        Ok(())
308    }
309
310    /// Both operands nullable columns: the verdict is null wherever either row is null, and
311    /// computed on the rows valid in both (points intersect exactly when equal).
312    #[test]
313    fn intersects_propagates_column_pair_nulls() -> VortexResult<()> {
314        let session = vortex_array::array_session();
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 session = vortex_array::array_session();
344        let mut ctx = session.create_execution_ctx();
345
346        let points = nullable_point_column(vec![None, None])?;
347        let query = geometry_constant(&donut(), 2)?;
348        let intersects = SpatialIntersects::try_new(points, query)?.into_array();
349
350        let expected =
351            BoolArray::new(BitBuffer::from_iter([false, false]), Validity::AllInvalid).into_array();
352        assert_arrays_eq!(intersects, expected, &mut ctx);
353        Ok(())
354    }
355
356    /// Two nullable columns whose nulls never line up: the combined mask is empty, so the output
357    /// is all null.
358    #[test]
359    fn intersects_column_pair_all_null() -> VortexResult<()> {
360        let session = vortex_array::array_session();
361        let mut ctx = session.create_execution_ctx();
362
363        let a = nullable_point_column(vec![Some((0.0, 0.0)), None])?;
364        let b = nullable_point_column(vec![None, Some((1.0, 1.0))])?;
365        let intersects = SpatialIntersects::try_new(a, b)?.into_array();
366
367        let expected =
368            BoolArray::new(BitBuffer::from_iter([false, false]), Validity::AllInvalid).into_array();
369        assert_arrays_eq!(intersects, expected, &mut ctx);
370        Ok(())
371    }
372
373    /// A non-geometry operand dtype is rejected up front, before execution.
374    #[test]
375    fn non_geometry_operand_is_rejected() -> VortexResult<()> {
376        let spatial_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
377        let numeric = DType::Primitive(PType::I32, Nullability::NonNullable);
378        let result = SpatialIntersects.return_dtype(&EmptyOptions, &[spatial_dtype, numeric]);
379        assert!(result.is_err());
380        Ok(())
381    }
382}