1use geo::Rect as SpatialRect;
7use vortex_array::ArrayRef;
8use vortex_array::Columnar;
9use vortex_array::ExecutionCtx;
10use vortex_array::IntoArray;
11use vortex_array::aggregate_fn::AggregateArgs;
12use vortex_array::aggregate_fn::AggregateFnId;
13use vortex_array::aggregate_fn::AggregateFnRef;
14use vortex_array::aggregate_fn::AggregateFnVTable;
15use vortex_array::aggregate_fn::AggregateFnVTableExt;
16use vortex_array::aggregate_fn::EmptyOptions;
17use vortex_array::dtype::DType;
18use vortex_array::dtype::Nullability;
19use vortex_array::dtype::extension::ExtDType;
20use vortex_array::scalar::Scalar;
21use vortex_error::VortexExpect;
22use vortex_error::VortexResult;
23use vortex_error::vortex_err;
24use vortex_session::VortexSession;
25use vortex_session::registry::CachedId;
26
27use crate::extension::Rect;
28use crate::extension::SpatialMetadata;
29use crate::extension::box_storage_dtype;
30use crate::extension::coordinate::Dimension;
31use crate::extension::coordinate::box_corners;
32use crate::extension::coordinate::ordinates;
33use crate::extension::flatten_coordinates;
34use crate::extension::is_native_geometry;
35
36#[derive(Clone, Debug)]
40pub struct GeometryAabb;
41
42pub struct AabbPartial {
45 rect: Option<SpatialRect<f64>>,
46}
47
48impl AabbPartial {
49 fn merge(&mut self, other: SpatialRect<f64>) {
51 self.rect = Some(self.rect.map_or(other, |cur| {
52 SpatialRect::new(
53 (
54 cur.min().x.min(other.min().x),
55 cur.min().y.min(other.min().y),
56 ),
57 (
58 cur.max().x.max(other.max().x),
59 cur.max().y.max(other.max().y),
60 ),
61 )
62 }));
63 }
64}
65
66fn aabb_dtype() -> DType {
68 DType::Extension(
69 ExtDType::<Rect>::try_new(SpatialMetadata::default(), aabb_storage_dtype())
70 .vortex_expect("2D box storage is a valid Rect")
71 .erased(),
72 )
73}
74
75fn aabb_storage_dtype() -> DType {
77 box_storage_dtype(Dimension::Xy, Nullability::Nullable)
78}
79
80fn aabb_of(xs: &[f64], ys: &[f64]) -> Option<SpatialRect<f64>> {
82 (!xs.is_empty()).then(|| {
83 let [xmin, ymin, xmax, ymax] = box_corners(xs, ys);
84 SpatialRect::new((xmin, ymin), (xmax, ymax))
85 })
86}
87
88fn rect_from_storage(scalar: &Scalar) -> VortexResult<Option<SpatialRect<f64>>> {
91 if scalar.is_null() {
92 return Ok(None);
93 }
94 let storage = scalar.as_extension().to_storage_scalar();
95 let fields = storage.as_struct();
96 let read = |name: &str| -> VortexResult<f64> {
97 f64::try_from(
98 &fields
99 .field(name)
100 .ok_or_else(|| vortex_err!("AABB missing {name}"))?,
101 )
102 };
103 Ok(Some(SpatialRect::new(
104 (read("xmin")?, read("ymin")?),
105 (read("xmax")?, read("ymax")?),
106 )))
107}
108
109fn rect_to_storage(rect: SpatialRect<f64>) -> Scalar {
111 let storage = Scalar::struct_(
112 aabb_storage_dtype(),
113 vec![
114 Scalar::primitive(rect.min().x, Nullability::NonNullable),
115 Scalar::primitive(rect.min().y, Nullability::NonNullable),
116 Scalar::primitive(rect.max().x, Nullability::NonNullable),
117 Scalar::primitive(rect.max().y, Nullability::NonNullable),
118 ],
119 );
120 Scalar::extension::<Rect>(SpatialMetadata::default(), storage)
121}
122
123impl AggregateFnVTable for GeometryAabb {
124 type Options = EmptyOptions;
125 type Partial = AabbPartial;
126
127 fn id(&self) -> AggregateFnId {
128 static ID: CachedId = CachedId::new("vortex.st.aabb");
129 *ID
130 }
131
132 fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
134 Ok(Some(vec![]))
135 }
136
137 fn deserialize(
138 &self,
139 _metadata: &[u8],
140 _session: &VortexSession,
141 ) -> VortexResult<Self::Options> {
142 Ok(EmptyOptions)
143 }
144
145 fn return_dtype(&self, _options: &Self::Options, input_dtype: &DType) -> Option<DType> {
146 is_native_geometry(input_dtype).then(aabb_dtype)
147 }
148
149 fn zone_stat_default(&self, input_dtype: &DType) -> Option<AggregateFnRef> {
150 is_native_geometry(input_dtype).then(|| self.bind(EmptyOptions))
151 }
152
153 fn partial_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option<DType> {
154 self.return_dtype(options, input_dtype)
155 }
156
157 fn empty_partial(
158 &self,
159 _args: AggregateArgs<'_, Self::Options>,
160 ) -> VortexResult<Self::Partial> {
161 Ok(AabbPartial { rect: None })
162 }
163
164 fn partial_from_scalar(
165 &self,
166 _args: AggregateArgs<'_, Self::Options>,
167 scalar: &Scalar,
168 ) -> VortexResult<Self::Partial> {
169 Ok(AabbPartial {
171 rect: rect_from_storage(scalar)?,
172 })
173 }
174
175 fn merge_partials(
176 &self,
177 _args: AggregateArgs<'_, Self::Options>,
178 mut first: Self::Partial,
179 second: Self::Partial,
180 ) -> VortexResult<Self::Partial> {
181 if let Some(rect) = second.rect {
182 first.merge(rect);
183 }
184 Ok(first)
185 }
186
187 fn to_scalar(
188 &self,
189 args: AggregateArgs<'_, Self::Options>,
190 partial: &Self::Partial,
191 ) -> VortexResult<Scalar> {
192 Ok(match partial.rect {
193 Some(rect) => rect_to_storage(rect),
194 None => Scalar::null(args.partial_dtype.clone()),
195 })
196 }
197
198 fn is_saturated(
199 &self,
200 _args: AggregateArgs<'_, Self::Options>,
201 _partial: &Self::Partial,
202 ) -> bool {
203 false
205 }
206
207 fn accumulate(
208 &self,
209 _args: AggregateArgs<'_, Self::Options>,
210 partial: &mut Self::Partial,
211 batch: &Columnar,
212 ctx: &mut ExecutionCtx,
213 ) -> VortexResult<()> {
214 let array = match batch {
215 Columnar::Canonical(canonical) => canonical.clone().into_array(),
216 Columnar::Constant(constant) => constant.clone().into_array(),
217 };
218 let valid = array.validity()?.execute_mask(array.len(), ctx)?;
228 let array = array.filter(valid)?;
229 let coords = flatten_coordinates(&array, ctx)?;
233 let xs = ordinates(&coords, "x", ctx)?;
234 let ys = ordinates(&coords, "y", ctx)?;
235 if let Some(rect) = aabb_of(&xs, &ys) {
236 partial.merge(rect);
237 }
238 Ok(())
239 }
240
241 fn finalize(
242 &self,
243 _args: AggregateArgs<'_, Self::Options>,
244 partials: ArrayRef,
245 ) -> VortexResult<ArrayRef> {
246 Ok(partials)
248 }
249
250 fn finalize_scalar(
251 &self,
252 args: AggregateArgs<'_, Self::Options>,
253 partial: &Self::Partial,
254 ) -> VortexResult<Scalar> {
255 self.to_scalar(args, partial)
256 }
257}
258
259#[cfg(test)]
260mod tests {
261 use geo::Rect as SpatialRect;
262 use vortex_array::ArrayRef;
263 use vortex_array::VortexSessionExecute;
264 use vortex_array::aggregate_fn::Accumulator;
265 use vortex_array::aggregate_fn::AggregateDTypes;
266 use vortex_array::aggregate_fn::AggregateFnVTable;
267 use vortex_array::aggregate_fn::DynAccumulator;
268 use vortex_array::aggregate_fn::EmptyOptions;
269 use vortex_array::aggregate_fn::session::AggregateFnSessionExt;
270 use vortex_array::dtype::DType;
271 use vortex_array::dtype::Nullability;
272 use vortex_array::dtype::PType;
273 use vortex_array::scalar::Scalar;
274 use vortex_error::VortexResult;
275
276 use super::AabbPartial;
277 use super::GeometryAabb;
278 use super::rect_from_storage;
279 use crate::test_harness::linestring_column;
280 use crate::test_harness::multilinestring_column;
281 use crate::test_harness::multipoint_column;
282 use crate::test_harness::multipolygon_column;
283 use crate::test_harness::nullable_point_column;
284 use crate::test_harness::point_column;
285 use crate::test_harness::polygon_column;
286 use crate::test_harness::spatial_session;
287
288 fn every_native_column(vertices: &[(f64, f64)]) -> VortexResult<Vec<ArrayRef>> {
290 let (xs, ys): (Vec<f64>, Vec<f64>) = vertices.iter().copied().unzip();
291 let flat = vertices.to_vec();
292 Ok(vec![
293 point_column(xs, ys)?,
294 linestring_column(vec![flat.clone()])?,
295 multipoint_column(vec![flat.clone()])?,
296 polygon_column(vec![vec![flat.clone()]])?,
297 multilinestring_column(vec![vec![flat.clone()]])?,
298 multipolygon_column(vec![vec![vec![flat]]])?,
299 ])
300 }
301
302 #[test]
304 fn serializes_for_zone_storage() -> VortexResult<()> {
305 let session = vortex_array::array_session();
306 let metadata = GeometryAabb
307 .serialize(&EmptyOptions)?
308 .expect("GeometryAabb must be serializable to be stored as a zone statistic");
309 GeometryAabb.deserialize(&metadata, &session)?;
310 Ok(())
311 }
312
313 fn aabb(result: &Scalar) -> VortexResult<(f64, f64, f64, f64)> {
315 let rect = rect_from_storage(result)?.expect("non-null AABB");
316 Ok((rect.min().x, rect.min().y, rect.max().x, rect.max().y))
317 }
318
319 #[test]
321 fn point_aabb_across_batches() -> VortexResult<()> {
322 let session = vortex_array::array_session();
323 let mut ctx = session.create_execution_ctx();
324
325 let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
326 let mut acc = Accumulator::try_new(GeometryAabb, EmptyOptions, dtype)?;
327
328 acc.accumulate(&point_column(vec![1.0, 3.0], vec![2.0, 4.0])?, &mut ctx)?;
329 acc.accumulate(&point_column(vec![-1.0], vec![5.0])?, &mut ctx)?;
330
331 assert_eq!(aabb(&acc.finish()?)?, (-1.0, 2.0, 3.0, 5.0));
332 Ok(())
333 }
334
335 #[test]
338 fn null_rows_do_not_widen_aabb() -> VortexResult<()> {
339 let session = vortex_array::array_session();
340 let mut ctx = session.create_execution_ctx();
341
342 let column = nullable_point_column(vec![Some((5.0, 6.0)), None, Some((7.0, 8.0))])?;
344 let mut acc = Accumulator::try_new(GeometryAabb, EmptyOptions, column.dtype().clone())?;
345 acc.accumulate(&column, &mut ctx)?;
346
347 assert_eq!(aabb(&acc.finish()?)?, (5.0, 6.0, 7.0, 8.0));
349 Ok(())
350 }
351
352 #[test]
355 fn polygon_aabb_union_all_vertices() -> VortexResult<()> {
356 let session = vortex_array::array_session();
357 let mut ctx = session.create_execution_ctx();
358
359 let polygons = polygon_column(vec![
361 vec![vec![(0.0, 0.0), (2.0, 0.0), (2.0, 3.0), (0.0, 3.0)]],
362 vec![vec![(5.0, 5.0), (7.0, 5.0), (7.0, 8.0), (5.0, 8.0)]],
363 ])?;
364 let dtype = polygons.dtype().clone();
365 let mut acc = Accumulator::try_new(GeometryAabb, EmptyOptions, dtype)?;
366 acc.accumulate(&polygons, &mut ctx)?;
367
368 assert_eq!(aabb(&acc.finish()?)?, (0.0, 0.0, 7.0, 8.0));
369 Ok(())
370 }
371
372 #[test]
375 fn aabb_covers_every_native_geometry_type() -> VortexResult<()> {
376 let session = vortex_array::array_session();
377 let mut ctx = session.create_execution_ctx();
378
379 for column in every_native_column(&[(1.0, 2.0), (-1.0, 5.0), (3.0, 4.0)])? {
380 let mut acc = Accumulator::try_new(GeometryAabb, EmptyOptions, column.dtype().clone())?;
381 acc.accumulate(&column, &mut ctx)?;
382 assert_eq!(
383 aabb(&acc.finish()?)?,
384 (-1.0, 2.0, 3.0, 5.0),
385 "AABB mismatch for {}",
386 column.dtype()
387 );
388 }
389 Ok(())
390 }
391
392 #[test]
395 fn multipolygon_aabb_union_all_vertices() -> VortexResult<()> {
396 let session = vortex_array::array_session();
397 let mut ctx = session.create_execution_ctx();
398
399 let multipolygons = multipolygon_column(vec![
401 vec![
402 vec![vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]],
403 vec![vec![(4.0, 4.0), (5.0, 4.0), (5.0, 5.0), (4.0, 5.0)]],
404 ],
405 vec![vec![vec![
406 (-3.0, 7.0),
407 (-2.0, 7.0),
408 (-2.0, 9.0),
409 (-3.0, 9.0),
410 ]]],
411 ])?;
412 let dtype = multipolygons.dtype().clone();
413 let mut acc = Accumulator::try_new(GeometryAabb, EmptyOptions, dtype)?;
414 acc.accumulate(&multipolygons, &mut ctx)?;
415
416 assert_eq!(aabb(&acc.finish()?)?, (-3.0, 0.0, 5.0, 9.0));
417 Ok(())
418 }
419
420 #[test]
423 fn merge_partials_unions_boxes() -> VortexResult<()> {
424 let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
425 let dtypes = AggregateDTypes::try_new(&GeometryAabb, &EmptyOptions, dtype)?;
426 let bbox = |xmin, ymin, xmax, ymax| AabbPartial {
427 rect: Some(SpatialRect::new((xmin, ymin), (xmax, ymax))),
428 };
429 let reduced = GeometryAabb.merge_partials(
430 dtypes.args(&EmptyOptions),
431 bbox(0.0, 0.0, 1.0, 1.0),
432 bbox(5.0, -2.0, 7.0, 3.0),
433 )?;
434 assert_eq!(
435 aabb(&GeometryAabb.to_scalar(dtypes.args(&EmptyOptions), &reduced)?)?,
436 (0.0, -2.0, 7.0, 3.0)
437 );
438 Ok(())
439 }
440
441 #[test]
443 fn merge_partials_ignores_empty() -> VortexResult<()> {
444 let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
445 let dtypes = AggregateDTypes::try_new(&GeometryAabb, &EmptyOptions, dtype)?;
446 let empty = GeometryAabb.empty_partial(dtypes.args(&EmptyOptions))?;
447 let value = AabbPartial {
448 rect: Some(SpatialRect::new((0.0, 0.0), (1.0, 1.0))),
449 };
450 let reduced = GeometryAabb.merge_partials(dtypes.args(&EmptyOptions), value, empty)?;
451 assert_eq!(
452 aabb(&GeometryAabb.to_scalar(dtypes.args(&EmptyOptions), &reduced)?)?,
453 (0.0, 0.0, 1.0, 1.0)
454 );
455 Ok(())
456 }
457
458 #[test]
462 fn all_nan_coordinates_kept() -> VortexResult<()> {
463 let session = vortex_array::array_session();
464 let mut ctx = session.create_execution_ctx();
465
466 let column = point_column(vec![f64::NAN, f64::NAN], vec![f64::NAN, f64::NAN])?;
467 let mut acc = Accumulator::try_new(GeometryAabb, EmptyOptions, column.dtype().clone())?;
468 acc.accumulate(&column, &mut ctx)?;
469
470 let (xmin, ymin, xmax, ymax) = aabb(&acc.finish()?)?;
471 assert!(xmin <= xmax && ymin <= ymax);
472 Ok(())
473 }
474
475 #[test]
477 fn empty_group_is_null() -> VortexResult<()> {
478 let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
479 let mut acc = Accumulator::try_new(GeometryAabb, EmptyOptions, dtype)?;
480 assert!(acc.finish()?.is_null());
481 Ok(())
482 }
483
484 #[test]
487 fn registered_as_geometry_zone_default() -> VortexResult<()> {
488 let session = spatial_session();
489
490 for column in every_native_column(&[(0.0, 0.0), (1.0, 1.0)])? {
491 assert!(
492 !session
493 .aggregate_fns()
494 .zone_stat_defaults(column.dtype())
495 .is_empty(),
496 "a geometry zone-stat default should be discovered for {}",
497 column.dtype()
498 );
499 }
500 let i32_dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
501 assert!(
502 session
503 .aggregate_fns()
504 .zone_stat_defaults(&i32_dtype)
505 .is_empty(),
506 "no geometry zone-stat default should apply to numeric columns"
507 );
508 Ok(())
509 }
510}