1use 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#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
24pub struct SpatialIntersects;
25
26impl SpatialIntersects {
27 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 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 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 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 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 const DONUT_EXPECTED: [bool; 4] = [true, false, true, false];
135
136 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 fn materialize(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
149 Ok(array.execute::<Canonical>(ctx)?.into_array())
150 }
151
152 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 #[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 #[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 #[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 #[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 #[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 #[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 let expected = BoolArray::from_iter(DONUT_EXPECTED);
248 assert_arrays_eq!(against_constant, expected, &mut ctx);
249 assert_arrays_eq!(pairwise, expected, &mut ctx);
250 Ok(())
251 }
252
253 #[test]
255 fn empty_constant_intersects_nothing() -> VortexResult<()> {
256 let empty = Geometry::LineString(LineString::new(Vec::<Coord>::new()));
257 let points = point_column(vec![0.0, 1.0], vec![0.0, 1.0])?;
258 assert_intersects(points, geometry_constant(&empty, 2)?, [false, false])
259 }
260
261 #[test]
264 fn output_nullability_mirrors_operands() -> VortexResult<()> {
265 let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
266 let non_nullable =
267 SpatialIntersects.return_dtype(&EmptyOptions, &[dtype.clone(), dtype.clone()])?;
268 assert_eq!(non_nullable, DType::Bool(Nullability::NonNullable));
269 let nullable =
270 SpatialIntersects.return_dtype(&EmptyOptions, &[dtype.as_nullable(), dtype])?;
271 assert_eq!(nullable, DType::Bool(Nullability::Nullable));
272 Ok(())
273 }
274
275 #[test]
278 fn intersects_propagates_null_rows() -> VortexResult<()> {
279 let session = vortex_array::array_session();
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 #[test]
297 fn intersects_constant_null_is_all_null() -> VortexResult<()> {
298 let session = vortex_array::array_session();
299 let mut ctx = session.create_execution_ctx();
300
301 let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().as_nullable();
302 let null_const = ConstantArray::new(Scalar::null(point_dtype), 2).into_array();
303 let points = point_column(vec![2.0, 20.0], vec![2.0, 20.0])?;
304 let intersects = SpatialIntersects::try_new(null_const, points)?.into_array();
305
306 let expected =
307 BoolArray::new(BitBuffer::from_iter([false, false]), Validity::AllInvalid).into_array();
308 assert_arrays_eq!(intersects, expected, &mut ctx);
309 Ok(())
310 }
311
312 #[test]
315 fn intersects_propagates_column_pair_nulls() -> VortexResult<()> {
316 let session = vortex_array::array_session();
317 let mut ctx = session.create_execution_ctx();
318
319 let a = nullable_point_column(vec![
320 Some((0.0, 0.0)),
321 None,
322 Some((2.0, 2.0)),
323 Some((3.0, 3.0)),
324 ])?;
325 let b = nullable_point_column(vec![
326 Some((0.0, 0.0)),
327 Some((5.0, 5.0)),
328 None,
329 Some((9.0, 9.0)),
330 ])?;
331 let intersects = SpatialIntersects::try_new(a, b)?.into_array();
332
333 let expected = BoolArray::new(
334 BitBuffer::from_iter([true, false, false, false]),
335 Validity::from_iter([true, false, false, true]),
336 )
337 .into_array();
338 assert_arrays_eq!(intersects, expected, &mut ctx);
339 Ok(())
340 }
341
342 #[test]
344 fn intersects_all_null_column_is_all_null() -> VortexResult<()> {
345 let session = vortex_array::array_session();
346 let mut ctx = session.create_execution_ctx();
347
348 let points = nullable_point_column(vec![None, None])?;
349 let query = geometry_constant(&donut(), 2)?;
350 let intersects = SpatialIntersects::try_new(points, query)?.into_array();
351
352 let expected =
353 BoolArray::new(BitBuffer::from_iter([false, false]), Validity::AllInvalid).into_array();
354 assert_arrays_eq!(intersects, expected, &mut ctx);
355 Ok(())
356 }
357
358 #[test]
361 fn intersects_column_pair_all_null() -> VortexResult<()> {
362 let session = vortex_array::array_session();
363 let mut ctx = session.create_execution_ctx();
364
365 let a = nullable_point_column(vec![Some((0.0, 0.0)), None])?;
366 let b = nullable_point_column(vec![None, Some((1.0, 1.0))])?;
367 let intersects = SpatialIntersects::try_new(a, b)?.into_array();
368
369 let expected =
370 BoolArray::new(BitBuffer::from_iter([false, false]), Validity::AllInvalid).into_array();
371 assert_arrays_eq!(intersects, expected, &mut ctx);
372 Ok(())
373 }
374
375 #[test]
377 fn non_geometry_operand_is_rejected() -> VortexResult<()> {
378 let spatial_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
379 let numeric = DType::Primitive(PType::I32, Nullability::NonNullable);
380 let result = SpatialIntersects.return_dtype(&EmptyOptions, &[spatial_dtype, numeric]);
381 assert!(result.is_err());
382 Ok(())
383 }
384}