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 assert_arrays_eq!(against_constant, pairwise, &mut ctx);
248 Ok(())
249 }
250
251 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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}