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_buffer::BitBuffer;
96 use vortex_error::VortexResult;
97 use vortex_error::vortex_err;
98 use wkb::writer::WriteOptions;
99
100 use super::SpatialIntersects;
101 use crate::test_harness::nullable_point_column;
102 use crate::test_harness::point_column;
103
104 fn rect_polygon(x0: f64, y0: f64, x1: f64, y1: f64) -> Polygon {
106 Polygon::new(
107 LineString::from(vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)]),
108 vec![],
109 )
110 }
111
112 fn donut() -> Geometry {
114 Geometry::Polygon(Polygon::new(
115 LineString::from(vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]),
116 vec![LineString::from(vec![
117 (4.0, 4.0),
118 (6.0, 4.0),
119 (6.0, 6.0),
120 (4.0, 6.0),
121 ])],
122 ))
123 }
124
125 fn donut_probes() -> VortexResult<ArrayRef> {
128 point_column(vec![2.0, 20.0, 0.0, 5.0], vec![2.0, 20.0, 5.0, 5.0])
129 }
130
131 const DONUT_EXPECTED: [bool; 4] = [true, false, true, false];
134
135 fn geometry_constant(geometry: &Geometry, len: usize) -> VortexResult<ArrayRef> {
137 let mut buf = Vec::new();
138 wkb::writer::write_geometry(&mut buf, geometry, &WriteOptions::default())
139 .map_err(|e| vortex_err!("writing WKB failed: {e}"))?;
140 let session = vortex_array::array_session();
141 let scalar = crate::extension::native_geometry_scalar_from_wkb(&buf, &session)?
142 .ok_or_else(|| vortex_err!("unsupported geometry type"))?;
143 Ok(ConstantArray::new(scalar, len).into_array())
144 }
145
146 fn materialize(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
148 Ok(array.execute::<Canonical>(ctx)?.into_array())
149 }
150
151 fn assert_intersects(
153 a: ArrayRef,
154 b: ArrayRef,
155 expected: impl IntoIterator<Item = bool>,
156 ) -> VortexResult<()> {
157 let session = vortex_array::array_session();
158 let mut ctx = session.create_execution_ctx();
159 let intersects = SpatialIntersects::try_new(a, b)?.into_array();
160 assert_arrays_eq!(intersects, BoolArray::from_iter(expected), &mut ctx);
161 Ok(())
162 }
163
164 #[rstest]
167 #[case::overlapping(rect_polygon(2.0, 2.0, 6.0, 6.0), true)]
168 #[case::touching_edge(rect_polygon(4.0, 0.0, 8.0, 4.0), true)]
169 #[case::touching_corner(rect_polygon(4.0, 4.0, 8.0, 8.0), true)]
170 #[case::disjoint(rect_polygon(20.0, 20.0, 24.0, 24.0), false)]
171 fn constant_vs_constant_polygons(
172 #[case] other: Polygon,
173 #[case] expected: bool,
174 ) -> VortexResult<()> {
175 let a = geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 3)?;
176 let b = geometry_constant(&Geometry::Polygon(other), 3)?;
177 assert_intersects(a, b, [expected; 3])
178 }
179
180 #[test]
183 fn point_column_vs_constant_polygon() -> VortexResult<()> {
184 assert_intersects(
185 donut_probes()?,
186 geometry_constant(&donut(), 4)?,
187 DONUT_EXPECTED,
188 )?;
189 assert_intersects(
190 geometry_constant(&donut(), 4)?,
191 donut_probes()?,
192 DONUT_EXPECTED,
193 )
194 }
195
196 #[test]
199 fn point_column_vs_constant_multipolygon() -> VortexResult<()> {
200 let query = Geometry::MultiPolygon(MultiPolygon::new(vec![
201 rect_polygon(0.0, 0.0, 2.0, 2.0),
202 rect_polygon(10.0, 10.0, 12.0, 12.0),
203 ]));
204 let points = point_column(vec![1.0, 11.0, 5.0], vec![1.0, 11.0, 5.0])?;
205 assert_intersects(points, geometry_constant(&query, 3)?, [true, true, false])
206 }
207
208 #[rstest]
211 #[case::overlapping(rect_polygon(2.0, 2.0, 6.0, 6.0), true)]
212 #[case::touching_edge(rect_polygon(4.0, 0.0, 8.0, 4.0), true)]
213 #[case::disjoint(rect_polygon(20.0, 20.0, 24.0, 24.0), false)]
214 fn polygon_column_vs_constant(
215 #[case] other: Polygon,
216 #[case] expected: bool,
217 ) -> VortexResult<()> {
218 let session = vortex_array::array_session();
219 let mut ctx = session.create_execution_ctx();
220 let column = materialize(geometry_constant(&Geometry::Polygon(other), 2)?, &mut ctx)?;
221 let query = geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 2)?;
222 assert_intersects(column, query, [expected; 2])
223 }
224
225 #[test]
227 fn point_column_vs_point_column() -> VortexResult<()> {
228 let a = point_column(vec![0.0, 1.0], vec![0.0, 1.0])?;
229 let b = point_column(vec![0.0, 2.0], vec![0.0, 1.0])?;
230 assert_intersects(a, b, [true, false])
231 }
232
233 #[test]
236 fn columns_agree_with_constant() -> VortexResult<()> {
237 let session = vortex_array::array_session();
238 let mut ctx = session.create_execution_ctx();
239
240 let constant = geometry_constant(&donut(), 4)?;
241 let column = materialize(constant.clone(), &mut ctx)?;
242
243 let against_constant = SpatialIntersects::try_new(donut_probes()?, constant)?.into_array();
244 let pairwise = SpatialIntersects::try_new(donut_probes()?, column)?.into_array();
245
246 let expected = BoolArray::from_iter(DONUT_EXPECTED);
247 assert_arrays_eq!(against_constant, expected, &mut ctx);
248 assert_arrays_eq!(pairwise, expected, &mut ctx);
249 Ok(())
250 }
251
252 #[test]
254 fn empty_constant_intersects_nothing() -> VortexResult<()> {
255 let empty = Geometry::LineString(LineString::new(Vec::<Coord>::new()));
256 let points = point_column(vec![0.0, 1.0], vec![0.0, 1.0])?;
257 assert_intersects(points, geometry_constant(&empty, 2)?, [false, false])
258 }
259
260 #[test]
263 fn output_nullability_mirrors_operands() -> VortexResult<()> {
264 let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
265 let non_nullable =
266 SpatialIntersects.return_dtype(&EmptyOptions, &[dtype.clone(), dtype.clone()])?;
267 assert_eq!(non_nullable, DType::Bool(Nullability::NonNullable));
268 let nullable =
269 SpatialIntersects.return_dtype(&EmptyOptions, &[dtype.as_nullable(), dtype])?;
270 assert_eq!(nullable, DType::Bool(Nullability::Nullable));
271 Ok(())
272 }
273
274 #[test]
277 fn intersects_propagates_null_rows() -> VortexResult<()> {
278 let session = vortex_array::array_session();
279 let mut ctx = session.create_execution_ctx();
280
281 let points = nullable_point_column(vec![Some((2.0, 2.0)), None, Some((20.0, 20.0))])?;
282 let query = geometry_constant(&donut(), 3)?;
283 let intersects = SpatialIntersects::try_new(points, query)?.into_array();
284
285 let expected = BoolArray::new(
286 BitBuffer::from_iter([true, false, false]),
287 Validity::from_iter([true, false, true]),
288 )
289 .into_array();
290 assert_arrays_eq!(intersects, expected, &mut ctx);
291 Ok(())
292 }
293
294 #[test]
296 fn intersects_constant_null_is_all_null() -> VortexResult<()> {
297 let session = vortex_array::array_session();
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 #[test]
314 fn intersects_propagates_column_pair_nulls() -> VortexResult<()> {
315 let session = vortex_array::array_session();
316 let mut ctx = session.create_execution_ctx();
317
318 let a = nullable_point_column(vec![
319 Some((0.0, 0.0)),
320 None,
321 Some((2.0, 2.0)),
322 Some((3.0, 3.0)),
323 ])?;
324 let b = nullable_point_column(vec![
325 Some((0.0, 0.0)),
326 Some((5.0, 5.0)),
327 None,
328 Some((9.0, 9.0)),
329 ])?;
330 let intersects = SpatialIntersects::try_new(a, b)?.into_array();
331
332 let expected = BoolArray::new(
333 BitBuffer::from_iter([true, false, false, false]),
334 Validity::from_iter([true, false, false, true]),
335 )
336 .into_array();
337 assert_arrays_eq!(intersects, expected, &mut ctx);
338 Ok(())
339 }
340
341 #[test]
343 fn intersects_all_null_column_is_all_null() -> VortexResult<()> {
344 let session = vortex_array::array_session();
345 let mut ctx = session.create_execution_ctx();
346
347 let points = nullable_point_column(vec![None, None])?;
348 let query = geometry_constant(&donut(), 2)?;
349 let intersects = SpatialIntersects::try_new(points, query)?.into_array();
350
351 let expected =
352 BoolArray::new(BitBuffer::from_iter([false, false]), Validity::AllInvalid).into_array();
353 assert_arrays_eq!(intersects, expected, &mut ctx);
354 Ok(())
355 }
356
357 #[test]
360 fn intersects_column_pair_all_null() -> VortexResult<()> {
361 let session = vortex_array::array_session();
362 let mut ctx = session.create_execution_ctx();
363
364 let a = nullable_point_column(vec![Some((0.0, 0.0)), None])?;
365 let b = nullable_point_column(vec![None, Some((1.0, 1.0))])?;
366 let intersects = SpatialIntersects::try_new(a, b)?.into_array();
367
368 let expected =
369 BoolArray::new(BitBuffer::from_iter([false, false]), Validity::AllInvalid).into_array();
370 assert_arrays_eq!(intersects, expected, &mut ctx);
371 Ok(())
372 }
373
374 #[test]
376 fn non_geometry_operand_is_rejected() -> VortexResult<()> {
377 let spatial_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
378 let numeric = DType::Primitive(PType::I32, Nullability::NonNullable);
379 let result = SpatialIntersects.return_dtype(&EmptyOptions, &[spatial_dtype, numeric]);
380 assert!(result.is_err());
381 Ok(())
382 }
383}