1use geo::Intersects;
7use vortex_array::ArrayRef;
8use vortex_array::ExecutionCtx;
9use vortex_array::arrays::ScalarFnArray;
10use vortex_array::dtype::DType;
11use vortex_array::dtype::Nullability;
12use vortex_array::expr::Expression;
13use vortex_array::expr::union_child_validities;
14use vortex_array::scalar_fn::Arity;
15use vortex_array::scalar_fn::ChildName;
16use vortex_array::scalar_fn::EmptyOptions;
17use vortex_array::scalar_fn::ExecutionArgs;
18use vortex_array::scalar_fn::ScalarFnId;
19use vortex_array::scalar_fn::ScalarFnVTable;
20use vortex_array::scalar_fn::TypedScalarFnInstance;
21use vortex_error::VortexResult;
22use vortex_error::vortex_ensure;
23use vortex_session::VortexSession;
24use vortex_session::registry::CachedId;
25
26use crate::extension::is_native_geometry;
27use crate::scalar_fn::execute::execute_binary_geo_types;
28
29fn validate_intersects_operands(dtypes: &[DType]) -> VortexResult<()> {
31 vortex_ensure!(
32 dtypes.len() == 2,
33 "spatial: intersects requires exactly two geometry operands, got {}",
34 dtypes.len()
35 );
36 for dtype in dtypes {
37 vortex_ensure!(
38 is_native_geometry(dtype),
39 "spatial: intersects operand {dtype} is not a native geometry type"
40 );
41 }
42 Ok(())
43}
44
45#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
48pub struct SpatialIntersects;
49
50impl SpatialIntersects {
51 pub fn try_new(a: ArrayRef, b: ArrayRef) -> VortexResult<ScalarFnArray> {
54 ScalarFnArray::try_new(
55 TypedScalarFnInstance::new(SpatialIntersects, EmptyOptions).erased(),
56 vec![a, b],
57 )
58 }
59}
60
61impl ScalarFnVTable for SpatialIntersects {
62 type Options = EmptyOptions;
63
64 fn id(&self) -> ScalarFnId {
65 static ID: CachedId = CachedId::new("vortex.st.intersects");
66 *ID
67 }
68
69 fn serialize(&self, _: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
70 Ok(Some(vec![]))
71 }
72
73 fn deserialize(&self, _: &[u8], _: &VortexSession) -> VortexResult<Self::Options> {
74 Ok(EmptyOptions)
75 }
76
77 fn arity(&self, _: &Self::Options) -> Arity {
78 Arity::Exact(2)
79 }
80
81 fn child_name(&self, _: &Self::Options, child_idx: usize) -> ChildName {
82 match child_idx {
83 0 => ChildName::from("a"),
84 1 => ChildName::from("b"),
85 _ => unreachable!("intersects has exactly two children"),
86 }
87 }
88
89 fn return_dtype(&self, _: &Self::Options, dtypes: &[DType]) -> VortexResult<DType> {
90 validate_intersects_operands(dtypes)?;
91 let nullability = Nullability::from(dtypes.iter().any(DType::is_nullable));
92 Ok(DType::Bool(nullability))
93 }
94
95 fn execute(
96 &self,
97 _: &Self::Options,
98 args: &dyn ExecutionArgs,
99 ctx: &mut ExecutionCtx,
100 ) -> VortexResult<ArrayRef> {
101 let a = args.get(0)?;
102 let b = args.get(1)?;
103 execute_binary_geo_types(
106 &a,
107 &b,
108 |x, y| x.intersects(y),
109 Some(|ra, rb| (!ra.intersects(rb)).then_some(false)),
110 ctx,
111 )
112 }
113
114 fn validity(
115 &self,
116 _: &Self::Options,
117 expression: &Expression,
118 ) -> VortexResult<Option<Expression>> {
119 union_child_validities(expression)
120 }
121
122 fn is_strict(&self, _: &Self::Options) -> bool {
123 true
124 }
125
126 fn is_infallible(&self, _: &Self::Options) -> bool {
127 true
128 }
129}
130
131#[cfg(test)]
132mod tests {
133 use geo_types::Coord;
134 use geo_types::Geometry;
135 use geo_types::LineString;
136 use geo_types::MultiPolygon;
137 use geo_types::Polygon;
138 use rstest::rstest;
139 use vortex_array::ArrayRef;
140 use vortex_array::Canonical;
141 use vortex_array::ExecutionCtx;
142 use vortex_array::IntoArray;
143 use vortex_array::VortexSessionExecute;
144 use vortex_array::arrays::BoolArray;
145 use vortex_array::arrays::ConstantArray;
146 use vortex_array::assert_arrays_eq;
147 use vortex_array::dtype::DType;
148 use vortex_array::dtype::Nullability;
149 use vortex_array::dtype::PType;
150 use vortex_array::scalar::Scalar;
151 use vortex_array::scalar_fn::EmptyOptions;
152 use vortex_array::scalar_fn::ScalarFnVTable;
153 use vortex_array::validity::Validity;
154 use vortex_arrow::ArrowSessionExt;
155 use vortex_buffer::BitBuffer;
156 use vortex_error::VortexResult;
157 use vortex_error::vortex_err;
158 use wkb::writer::WriteOptions;
159
160 use super::SpatialIntersects;
161 use crate::test_harness::nullable_point_column;
162 use crate::test_harness::point_column;
163
164 fn rect_polygon(x0: f64, y0: f64, x1: f64, y1: f64) -> Polygon {
166 Polygon::new(
167 LineString::from(vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)]),
168 vec![],
169 )
170 }
171
172 fn donut() -> Geometry {
174 Geometry::Polygon(Polygon::new(
175 LineString::from(vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]),
176 vec![LineString::from(vec![
177 (4.0, 4.0),
178 (6.0, 4.0),
179 (6.0, 6.0),
180 (4.0, 6.0),
181 ])],
182 ))
183 }
184
185 fn donut_probes() -> VortexResult<ArrayRef> {
188 point_column(vec![2.0, 20.0, 0.0, 5.0], vec![2.0, 20.0, 5.0, 5.0])
189 }
190
191 const DONUT_EXPECTED: [bool; 4] = [true, false, true, false];
194
195 fn geometry_constant(geometry: &Geometry, len: usize) -> VortexResult<ArrayRef> {
197 let mut buf = Vec::new();
198 wkb::writer::write_geometry(&mut buf, geometry, &WriteOptions::default())
199 .map_err(|e| vortex_err!("writing WKB failed: {e}"))?;
200 let session = vortex_array::array_session();
201 let scalar = crate::extension::native_geometry_scalar_from_wkb(&buf, &session.arrow())?
202 .ok_or_else(|| vortex_err!("unsupported geometry type"))?;
203 Ok(ConstantArray::new(scalar, len).into_array())
204 }
205
206 fn materialize(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
208 Ok(array.execute::<Canonical>(ctx)?.into_array())
209 }
210
211 fn assert_intersects(
213 a: ArrayRef,
214 b: ArrayRef,
215 expected: impl IntoIterator<Item = bool>,
216 ) -> VortexResult<()> {
217 let session = vortex_array::array_session();
218 let mut ctx = session.create_execution_ctx();
219 let intersects = SpatialIntersects::try_new(a, b)?.into_array();
220 assert_arrays_eq!(intersects, BoolArray::from_iter(expected), &mut ctx);
221 Ok(())
222 }
223
224 #[rstest]
229 #[case::overlapping(rect_polygon(2.0, 2.0, 6.0, 6.0), true)]
230 #[case::touching_edge(rect_polygon(4.0, 0.0, 8.0, 4.0), true)]
231 #[case::touching_corner(rect_polygon(4.0, 4.0, 8.0, 8.0), true)]
232 #[case::disjoint(rect_polygon(20.0, 20.0, 24.0, 24.0), false)]
233 fn constant_vs_constant_polygons(
234 #[case] other: Polygon,
235 #[case] expected: bool,
236 ) -> VortexResult<()> {
237 let a = geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 3)?;
238 let b = geometry_constant(&Geometry::Polygon(other), 3)?;
239 assert_intersects(a, b, [expected; 3])
240 }
241
242 #[test]
245 fn point_column_vs_constant_polygon() -> VortexResult<()> {
246 assert_intersects(
247 donut_probes()?,
248 geometry_constant(&donut(), 4)?,
249 DONUT_EXPECTED,
250 )?;
251 assert_intersects(
252 geometry_constant(&donut(), 4)?,
253 donut_probes()?,
254 DONUT_EXPECTED,
255 )
256 }
257
258 #[test]
261 fn point_column_vs_constant_multipolygon() -> VortexResult<()> {
262 let query = Geometry::MultiPolygon(MultiPolygon::new(vec![
263 rect_polygon(0.0, 0.0, 2.0, 2.0),
264 rect_polygon(10.0, 10.0, 12.0, 12.0),
265 ]));
266 let points = point_column(vec![1.0, 11.0, 5.0], vec![1.0, 11.0, 5.0])?;
267 assert_intersects(points, geometry_constant(&query, 3)?, [true, true, false])
268 }
269
270 #[rstest]
273 #[case::overlapping(rect_polygon(2.0, 2.0, 6.0, 6.0), true)]
274 #[case::touching_edge(rect_polygon(4.0, 0.0, 8.0, 4.0), true)]
275 #[case::disjoint(rect_polygon(20.0, 20.0, 24.0, 24.0), false)]
276 fn polygon_column_vs_constant(
277 #[case] other: Polygon,
278 #[case] expected: bool,
279 ) -> VortexResult<()> {
280 let session = vortex_array::array_session();
281 let mut ctx = session.create_execution_ctx();
282 let column = materialize(geometry_constant(&Geometry::Polygon(other), 2)?, &mut ctx)?;
283 let query = geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 2)?;
284 assert_intersects(column, query, [expected; 2])
285 }
286
287 #[test]
289 fn point_column_vs_point_column() -> VortexResult<()> {
290 let a = point_column(vec![0.0, 1.0], vec![0.0, 1.0])?;
291 let b = point_column(vec![0.0, 2.0], vec![0.0, 1.0])?;
292 assert_intersects(a, b, [true, false])
293 }
294
295 #[test]
298 fn columns_agree_with_constant() -> VortexResult<()> {
299 let session = vortex_array::array_session();
300 let mut ctx = session.create_execution_ctx();
301
302 let constant = geometry_constant(&donut(), 4)?;
303 let column = materialize(constant.clone(), &mut ctx)?;
304
305 let against_constant = SpatialIntersects::try_new(donut_probes()?, constant)?.into_array();
306 let pairwise = SpatialIntersects::try_new(donut_probes()?, column)?.into_array();
307
308 assert_arrays_eq!(against_constant, pairwise, &mut ctx);
309 Ok(())
310 }
311
312 #[test]
314 fn empty_constant_intersects_nothing() -> VortexResult<()> {
315 let empty = Geometry::LineString(LineString::new(Vec::<Coord>::new()));
316 let points = point_column(vec![0.0, 1.0], vec![0.0, 1.0])?;
317 assert_intersects(points, geometry_constant(&empty, 2)?, [false, false])
318 }
319
320 #[test]
323 fn output_nullability_mirrors_operands() -> VortexResult<()> {
324 let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
325 let non_nullable =
326 SpatialIntersects.return_dtype(&EmptyOptions, &[dtype.clone(), dtype.clone()])?;
327 assert!(!non_nullable.is_nullable());
328 let nullable =
329 SpatialIntersects.return_dtype(&EmptyOptions, &[dtype.as_nullable(), dtype])?;
330 assert!(nullable.is_nullable());
331 Ok(())
332 }
333
334 #[test]
337 fn intersects_propagates_null_rows() -> VortexResult<()> {
338 let session = vortex_array::array_session();
339 let mut ctx = session.create_execution_ctx();
340
341 let points = nullable_point_column(vec![Some((2.0, 2.0)), None, Some((20.0, 20.0))])?;
342 let query = geometry_constant(&donut(), 3)?;
343 let intersects = SpatialIntersects::try_new(points, query)?.into_array();
344
345 let expected = BoolArray::new(
346 BitBuffer::from_iter([true, false, false]),
347 Validity::from_iter([true, false, true]),
348 )
349 .into_array();
350 assert_arrays_eq!(intersects, expected, &mut ctx);
351 Ok(())
352 }
353
354 #[test]
356 fn intersects_constant_null_is_all_null() -> VortexResult<()> {
357 let session = vortex_array::array_session();
358 let mut ctx = session.create_execution_ctx();
359
360 let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().as_nullable();
361 let null_const = ConstantArray::new(Scalar::null(point_dtype), 2).into_array();
362 let points = point_column(vec![2.0, 20.0], vec![2.0, 20.0])?;
363 let intersects = SpatialIntersects::try_new(null_const, points)?.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 #[test]
374 fn intersects_propagates_column_pair_nulls() -> VortexResult<()> {
375 let session = vortex_array::array_session();
376 let mut ctx = session.create_execution_ctx();
377
378 let a = nullable_point_column(vec![
379 Some((0.0, 0.0)),
380 None,
381 Some((2.0, 2.0)),
382 Some((3.0, 3.0)),
383 ])?;
384 let b = nullable_point_column(vec![
385 Some((0.0, 0.0)),
386 Some((5.0, 5.0)),
387 None,
388 Some((9.0, 9.0)),
389 ])?;
390 let intersects = SpatialIntersects::try_new(a, b)?.into_array();
391
392 let expected = BoolArray::new(
393 BitBuffer::from_iter([true, false, false, false]),
394 Validity::from_iter([true, false, false, true]),
395 )
396 .into_array();
397 assert_arrays_eq!(intersects, expected, &mut ctx);
398 Ok(())
399 }
400
401 #[test]
403 fn intersects_all_null_column_is_all_null() -> VortexResult<()> {
404 let session = vortex_array::array_session();
405 let mut ctx = session.create_execution_ctx();
406
407 let points = nullable_point_column(vec![None, None])?;
408 let query = geometry_constant(&donut(), 2)?;
409 let intersects = SpatialIntersects::try_new(points, query)?.into_array();
410
411 let expected =
412 BoolArray::new(BitBuffer::from_iter([false, false]), Validity::AllInvalid).into_array();
413 assert_arrays_eq!(intersects, expected, &mut ctx);
414 Ok(())
415 }
416
417 #[test]
420 fn intersects_column_pair_all_null() -> VortexResult<()> {
421 let session = vortex_array::array_session();
422 let mut ctx = session.create_execution_ctx();
423
424 let a = nullable_point_column(vec![Some((0.0, 0.0)), None])?;
425 let b = nullable_point_column(vec![None, Some((1.0, 1.0))])?;
426 let intersects = SpatialIntersects::try_new(a, b)?.into_array();
427
428 let expected =
429 BoolArray::new(BitBuffer::from_iter([false, false]), Validity::AllInvalid).into_array();
430 assert_arrays_eq!(intersects, expected, &mut ctx);
431 Ok(())
432 }
433
434 #[test]
436 fn non_geometry_operand_is_rejected() -> VortexResult<()> {
437 let spatial_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
438 let numeric = DType::Primitive(PType::I32, Nullability::NonNullable);
439 let result = SpatialIntersects.return_dtype(&EmptyOptions, &[spatial_dtype, numeric]);
440 assert!(result.is_err());
441 Ok(())
442 }
443}