Skip to main content

vortex_spatial/aggregate_fn/
aabb.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! The 2D axis-aligned bounding-box (AABB) aggregate for native geometry columns.
5
6use 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::coordinate::Dimension;
30use crate::extension::coordinate::box_corners;
31use crate::extension::coordinate::ordinates;
32use crate::extension::flatten_coordinates;
33use crate::extension::is_native_geometry;
34
35/// Aggregates a native geometry column's 2D axis-aligned bounding box (AABB) as a native
36/// `geoarrow.box`, the spatial analogue of min/max. Also the default zone statistic for such
37/// columns (via `zone_stat_default`).
38#[derive(Clone, Debug)]
39pub struct GeometryAabb;
40
41/// Running union of geometry AABBs, or `None` until the first row. A transient
42/// `geo::Rect` value - the persisted stat is the native box (see `to_scalar`).
43pub struct AabbPartial {
44    rect: Option<SpatialRect<f64>>,
45}
46
47impl AabbPartial {
48    /// Grow the accumulated box to also cover `other`.
49    fn merge(&mut self, other: SpatialRect<f64>) {
50        self.rect = Some(self.rect.map_or(other, |cur| {
51            SpatialRect::new(
52                (
53                    cur.min().x.min(other.min().x),
54                    cur.min().y.min(other.min().y),
55                ),
56                (
57                    cur.max().x.max(other.max().x),
58                    cur.max().y.max(other.max().y),
59                ),
60            )
61        }));
62    }
63}
64
65/// The stat's type: the native `geoarrow.box` (2D), nullable so an empty group is a null box.
66fn aabb_dtype() -> DType {
67    DType::Extension(
68        ExtDType::<Rect>::try_new(
69            SpatialMetadata::default().with_dimension(Dimension::Xy),
70            Nullability::Nullable,
71        )
72        .vortex_expect("Rect accepts metadata with a coordinate dimension")
73        .erased(),
74    )
75}
76
77/// The AABB of the raw `x`/`y` slices, or `None` when empty.
78fn aabb_of(xs: &[f64], ys: &[f64]) -> Option<SpatialRect<f64>> {
79    (!xs.is_empty()).then(|| {
80        let [xmin, ymin, xmax, ymax] = box_corners(xs, ys);
81        SpatialRect::new((xmin, ymin), (xmax, ymax))
82    })
83}
84
85/// Read an AABB stat scalar (a nullable native `geoarrow.box`) into a [`SpatialRect`], or `None` when
86/// the scalar is null (an empty group).
87fn rect_from_storage(scalar: &Scalar) -> VortexResult<Option<SpatialRect<f64>>> {
88    if scalar.is_null() {
89        return Ok(None);
90    }
91    let storage = scalar.as_extension().to_storage_scalar();
92    let fields = storage.as_struct();
93    let read = |name: &str| -> VortexResult<f64> {
94        f64::try_from(
95            &fields
96                .field(name)
97                .ok_or_else(|| vortex_err!("AABB missing {name}"))?,
98        )
99    };
100    Ok(Some(SpatialRect::new(
101        (read("xmin")?, read("ymin")?),
102        (read("xmax")?, read("ymax")?),
103    )))
104}
105
106/// Serialize a [`SpatialRect`] as a stat scalar of `dtype`, the native `geoarrow.box` that
107/// [`aabb_dtype`] builds (inverse of [`rect_from_storage`]). The caller passes the dtype that it
108/// holds, so each group reuses it instead of building it again.
109fn rect_to_storage(rect: SpatialRect<f64>, dtype: &DType) -> Scalar {
110    let ext_dtype = dtype.as_extension();
111    let storage = Scalar::struct_(
112        ext_dtype.storage_dtype().clone(),
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_ref(ext_dtype.clone(), 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    // Serializable so the zoned writer can persist this as a per-chunk stat. No options to encode.
133    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        // A null box is an empty group's AABB.
170        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, args.partial_dtype),
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        // An AABB can always grow, so it is never saturated.
204        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        // Drop null rows before reading coordinates: a null geometry's storage holds placeholder
219        // coordinates (e.g. `(0, 0)`) that would otherwise widen the zone box and drag it toward
220        // the origin. `filter` collapses an all-true mask back to the input, so a null-free batch
221        // passes through unchanged.
222        //
223        // TODO(perf): on nullable data this `filter` compacts the whole column even for a single
224        // null before we min/max it. A validity-aware min/max straight over the raw x/y buffers
225        // would skip that copy. Left as-is for now: this is a write-time zone stat, and the common
226        // non-nullable case already costs nothing (the all-true mask makes `filter` a no-op).
227        let valid = array.validity()?.execute_mask(array.len(), ctx)?;
228        let array = array.filter(valid)?;
229        // Null rows are gone, so every coordinate below belongs to a present geometry — the
230        // `unmasked_field_by_name` reads are therefore safe. Min/max the raw x/y buffers directly:
231        // cheap, and avoids `to_geometry`'s panic on empty points (which decoding would hit).
232        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        // The stored partial is already the AABB struct, so finalizing is the identity.
247        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 std::sync::LazyLock;
262
263    use geo::Rect as SpatialRect;
264    use vortex_array::ArrayRef;
265    use vortex_array::VortexSessionExecute;
266    use vortex_array::aggregate_fn::Accumulator;
267    use vortex_array::aggregate_fn::AggregateDTypes;
268    use vortex_array::aggregate_fn::AggregateFnVTable;
269    use vortex_array::aggregate_fn::DynAccumulator;
270    use vortex_array::aggregate_fn::EmptyOptions;
271    use vortex_array::aggregate_fn::session::AggregateFnSessionExt;
272    use vortex_array::dtype::DType;
273    use vortex_array::dtype::Nullability;
274    use vortex_array::dtype::PType;
275    use vortex_array::scalar::Scalar;
276    use vortex_error::VortexResult;
277    use vortex_session::VortexSession;
278
279    use super::AabbPartial;
280    use super::GeometryAabb;
281    use super::rect_from_storage;
282    use crate::test_harness::linestring_column;
283    use crate::test_harness::multilinestring_column;
284    use crate::test_harness::multipoint_column;
285    use crate::test_harness::multipolygon_column;
286    use crate::test_harness::nullable_point_column;
287    use crate::test_harness::point_column;
288    use crate::test_harness::polygon_column;
289    use crate::test_harness::spatial_session;
290
291    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
292
293    /// One column of every native geometry type over the same `(x, y)` vertex set.
294    fn every_native_column(vertices: &[(f64, f64)]) -> VortexResult<Vec<ArrayRef>> {
295        let (xs, ys): (Vec<f64>, Vec<f64>) = vertices.iter().copied().unzip();
296        let flat = vertices.to_vec();
297        Ok(vec![
298            point_column(xs, ys)?,
299            linestring_column(vec![flat.clone()])?,
300            multipoint_column(vec![flat.clone()])?,
301            polygon_column(vec![vec![flat.clone()]])?,
302            multilinestring_column(vec![vec![flat.clone()]])?,
303            multipolygon_column(vec![vec![vec![flat]]])?,
304        ])
305    }
306
307    /// The aggregate must be serializable so the zoned writer can persist its zone-stat descriptor.
308    #[test]
309    fn serializes_for_zone_storage() -> VortexResult<()> {
310        let session = VortexSession::empty();
311        let metadata = GeometryAabb
312            .serialize(&EmptyOptions)?
313            .expect("GeometryAabb must be serializable to be stored as a zone statistic");
314        GeometryAabb.deserialize(&metadata, &session)?;
315        Ok(())
316    }
317
318    /// The AABB result's corners as `(xmin, ymin, xmax, ymax)`.
319    fn aabb(result: &Scalar) -> VortexResult<(f64, f64, f64, f64)> {
320        let rect = rect_from_storage(result)?.expect("non-null AABB");
321        Ok((rect.min().x, rect.min().y, rect.max().x, rect.max().y))
322    }
323
324    /// The AABB of a Point column is the min/max of its coordinates, accumulated across batches.
325    #[test]
326    fn point_aabb_across_batches() -> VortexResult<()> {
327        let mut ctx = SESSION.create_execution_ctx();
328
329        let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
330        let mut acc = Accumulator::try_new(GeometryAabb, EmptyOptions, dtype)?;
331
332        acc.accumulate(&point_column(vec![1.0, 3.0], vec![2.0, 4.0])?, &mut ctx)?;
333        acc.accumulate(&point_column(vec![-1.0], vec![5.0])?, &mut ctx)?;
334
335        assert_eq!(aabb(&acc.finish()?)?, (-1.0, 2.0, 3.0, 5.0));
336        Ok(())
337    }
338
339    /// Null rows contribute no extent: their placeholder coordinates must not widen the box toward
340    /// the origin (matching min/max, which skip nulls).
341    #[test]
342    fn null_rows_do_not_widen_aabb() -> VortexResult<()> {
343        let mut ctx = SESSION.create_execution_ctx();
344
345        // The valid points sit far from the origin; the null row's storage placeholder is (0, 0).
346        let column = nullable_point_column(vec![Some((5.0, 6.0)), None, Some((7.0, 8.0))])?;
347        let mut acc = Accumulator::try_new(GeometryAabb, EmptyOptions, column.dtype().clone())?;
348        acc.accumulate(&column, &mut ctx)?;
349
350        // The box covers only the two valid points, never (0, 0).
351        assert_eq!(aabb(&acc.finish()?)?, (5.0, 6.0, 7.0, 8.0));
352        Ok(())
353    }
354
355    /// The AABB of a Polygon column unions every ring vertex - exercising the `List<List<Struct>>`
356    /// unwrap, not just the bare Point struct.
357    #[test]
358    fn polygon_aabb_union_all_vertices() -> VortexResult<()> {
359        let mut ctx = SESSION.create_execution_ctx();
360
361        // Two rectangles: (0,0)-(2,3) and (5,5)-(7,8). The chunk AABB is their union: (0,0)-(7,8).
362        let polygons = polygon_column(vec![
363            vec![vec![(0.0, 0.0), (2.0, 0.0), (2.0, 3.0), (0.0, 3.0)]],
364            vec![vec![(5.0, 5.0), (7.0, 5.0), (7.0, 8.0), (5.0, 8.0)]],
365        ])?;
366        let dtype = polygons.dtype().clone();
367        let mut acc = Accumulator::try_new(GeometryAabb, EmptyOptions, dtype)?;
368        acc.accumulate(&polygons, &mut ctx)?;
369
370        assert_eq!(aabb(&acc.finish()?)?, (0.0, 0.0, 7.0, 8.0));
371        Ok(())
372    }
373
374    /// Every native geometry type over the same vertex set yields the same AABB - the zone stat
375    /// covers the whole type family.
376    #[test]
377    fn aabb_covers_every_native_geometry_type() -> VortexResult<()> {
378        let mut ctx = SESSION.create_execution_ctx();
379
380        for column in every_native_column(&[(1.0, 2.0), (-1.0, 5.0), (3.0, 4.0)])? {
381            let mut acc = Accumulator::try_new(GeometryAabb, EmptyOptions, column.dtype().clone())?;
382            acc.accumulate(&column, &mut ctx)?;
383            assert_eq!(
384                aabb(&acc.finish()?)?,
385                (-1.0, 2.0, 3.0, 5.0),
386                "AABB mismatch for {}",
387                column.dtype()
388            );
389        }
390        Ok(())
391    }
392
393    /// The AABB of a MultiPolygon column unions every vertex of every polygon's rings - exercising
394    /// the triple-`List` unwrap.
395    #[test]
396    fn multipolygon_aabb_union_all_vertices() -> VortexResult<()> {
397        let mut ctx = SESSION.create_execution_ctx();
398
399        // Multipolygon 0: squares (0,0)-(1,1) and (4,4)-(5,5); multipolygon 1: square (-3,7)-(-2,9).
400        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    /// `merge_partials` unions partial boxes - the path the zoned writer takes when a zone's
421    /// array is chunked.
422    #[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    /// An empty partial (an empty group's AABB) is a no-op in `merge_partials`.
442    #[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    /// All-NaN coordinates: `f64::min`/`max` skip the NaNs and `geo::Rect` normalizes the result to
459    /// a valid (whole-plane) box, so such a chunk is always kept. Sound - NaN-coordinate rows can
460    /// never satisfy `distance <= r` anyway.
461    #[test]
462    fn all_nan_coordinates_kept() -> VortexResult<()> {
463        let mut ctx = SESSION.create_execution_ctx();
464
465        let column = point_column(vec![f64::NAN, f64::NAN], vec![f64::NAN, f64::NAN])?;
466        let mut acc = Accumulator::try_new(GeometryAabb, EmptyOptions, column.dtype().clone())?;
467        acc.accumulate(&column, &mut ctx)?;
468
469        let (xmin, ymin, xmax, ymax) = aabb(&acc.finish()?)?;
470        assert_eq!(
471            (xmin, ymin, xmax, ymax),
472            (
473                f64::NEG_INFINITY,
474                f64::NEG_INFINITY,
475                f64::INFINITY,
476                f64::INFINITY
477            )
478        );
479        Ok(())
480    }
481
482    /// An empty group yields a null AABB.
483    #[test]
484    fn empty_group_is_null() -> VortexResult<()> {
485        let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
486        let mut acc = Accumulator::try_new(GeometryAabb, EmptyOptions, dtype)?;
487        assert!(acc.finish()?.is_null());
488        Ok(())
489    }
490
491    /// After `initialize`, the registry yields a default zone statistic for every native geometry
492    /// type (so the zoned writer stores it) but none for ordinary numeric columns.
493    #[test]
494    fn registered_as_geometry_zone_default() -> VortexResult<()> {
495        let session = spatial_session();
496
497        for column in every_native_column(&[(0.0, 0.0), (1.0, 1.0)])? {
498            assert!(
499                !session
500                    .aggregate_fns()
501                    .zone_stat_defaults(column.dtype())
502                    .is_empty(),
503                "a geometry zone-stat default should be discovered for {}",
504                column.dtype()
505            );
506        }
507        let i32_dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
508        assert!(
509            session
510                .aggregate_fns()
511                .zone_stat_defaults(&i32_dtype)
512                .is_empty(),
513            "no geometry zone-stat default should apply to numeric columns"
514        );
515        Ok(())
516    }
517}