Skip to main content

vortex_spatial/extension/
rect.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! The [`Rect`] bounding-box extension type (`vortex.st.box`): an axis-aligned envelope stored
5//! columnarly as `Struct<xmin, ymin[, zmin][, mmin], xmax, ymax[, zmax][, mmax]>` of non-nullable
6//! `f64` — the lower corner's ordinates followed by the upper corner's — tagged with
7//! [`SpatialMetadata`] (CRS). Its GeoArrow wire type is `geoarrow.box`.
8//!
9//! Decoding to `geo_types` yields a 2D [`Geometry::Rect`]; any `z`/`m`
10//! bounds are dropped, as for the other geometry types.
11
12use std::sync::Arc;
13
14use arrow_array::ArrayRef as ArrowArrayRef;
15use arrow_schema::DataType;
16use arrow_schema::Field;
17use arrow_schema::extension::ExtensionType;
18use geo_traits::to_geo::ToGeoGeometry;
19use geo_types::Geometry;
20use geoarrow::array::GeoArrowArrayAccessor;
21use geoarrow::array::IntoArrow;
22use geoarrow::array::RectArray;
23use geoarrow::datatypes::BoxType;
24use prost::Message;
25use vortex_array::ArrayRef;
26use vortex_array::ExecutionCtx;
27use vortex_array::IntoArray;
28use vortex_array::arrays::ExtensionArray;
29use vortex_array::arrays::StructArray;
30use vortex_array::arrays::extension::ExtensionArrayExt;
31use vortex_array::dtype::DType;
32use vortex_array::dtype::FieldNames;
33use vortex_array::dtype::Nullability;
34use vortex_array::dtype::PType;
35use vortex_array::dtype::StructFields;
36use vortex_array::dtype::extension::ExtDType;
37use vortex_array::dtype::extension::ExtId;
38use vortex_array::dtype::extension::ExtVTable;
39use vortex_array::scalar::ScalarValue;
40use vortex_array::validity::Validity;
41use vortex_arrow::ArrowExport;
42use vortex_arrow::ArrowExportOptions;
43use vortex_arrow::ArrowExportVTable;
44use vortex_arrow::ArrowImport;
45use vortex_arrow::ArrowImportVTable;
46use vortex_arrow::ArrowSession;
47use vortex_arrow::ArrowSessionExt;
48use vortex_error::VortexResult;
49use vortex_error::vortex_bail;
50use vortex_error::vortex_ensure;
51use vortex_error::vortex_err;
52use vortex_session::registry::CachedId;
53use vortex_session::registry::Id;
54
55use super::SpatialMetadata;
56use super::coordinate::Dimension;
57use super::geoarrow_metadata;
58use super::spatial_metadata_from_arrow;
59
60/// An axis-aligned bounding box (`geoarrow.box`), stored as `Struct<xmin, ymin[, ..], xmax, ymax[, ..]>`.
61// Named `Rect`, not `Box`: matches `geo::Rect` / geoarrow-rs `RectArray`, and `Box` is a std name.
62#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
63pub struct Rect;
64
65impl ExtVTable for Rect {
66    type Metadata = SpatialMetadata;
67    // No cheap owned value; expose the raw storage scalar like `Polygon`.
68    type NativeValue<'a> = &'a ScalarValue;
69
70    fn id(&self) -> ExtId {
71        static ID: CachedId = CachedId::new("vortex.st.box");
72        *ID
73    }
74
75    fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
76        Ok(metadata.encode_to_vec())
77    }
78
79    fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult<Self::Metadata> {
80        Ok(SpatialMetadata::decode(metadata)?)
81    }
82
83    fn validate_dtype(ext_dtype: &ExtDType<Self>) -> VortexResult<()> {
84        box_dimension(ext_dtype.storage_dtype()).map(|_| ())
85    }
86
87    fn unpack_native<'a>(
88        _ext_dtype: &'a ExtDType<Self>,
89        storage_value: &'a ScalarValue,
90    ) -> VortexResult<&'a ScalarValue> {
91        Ok(storage_value)
92    }
93}
94
95/// The `geoarrow.box` storage field names for `dim`: the lower corner's ordinates followed by the
96/// upper corner's.
97pub(crate) fn box_field_names(dim: Dimension) -> &'static [&'static str] {
98    match dim {
99        Dimension::Xy => &["xmin", "ymin", "xmax", "ymax"],
100        Dimension::Xyz => &["xmin", "ymin", "zmin", "xmax", "ymax", "zmax"],
101        Dimension::Xym => &["xmin", "ymin", "mmin", "xmax", "ymax", "mmax"],
102        Dimension::Xyzm => &[
103            "xmin", "ymin", "zmin", "mmin", "xmax", "ymax", "zmax", "mmax",
104        ],
105    }
106}
107
108/// The dimension whose box field names match `names`, or `None` if none do.
109fn box_dimension_from_names(names: &FieldNames) -> Option<Dimension> {
110    [
111        Dimension::Xy,
112        Dimension::Xyz,
113        Dimension::Xym,
114        Dimension::Xyzm,
115    ]
116    .into_iter()
117    .find(|&dim| {
118        names
119            .iter()
120            .map(AsRef::as_ref)
121            .eq(box_field_names(dim).iter().copied())
122    })
123}
124
125/// Canonical box storage: a `Struct` of non-nullable `f64` min/max fields, with `nullability` at
126/// the struct (per-box) level.
127pub(crate) fn box_storage_dtype(dim: Dimension, nullability: Nullability) -> DType {
128    let names = box_field_names(dim);
129    let fields = std::iter::repeat_n(
130        DType::Primitive(PType::F64, Nullability::NonNullable),
131        names.len(),
132    )
133    .collect::<Vec<_>>();
134    DType::Struct(
135        StructFields::new(FieldNames::from(names), fields),
136        nullability,
137    )
138}
139
140/// Validate `dtype` is a box `Struct` of non-nullable `f64` min/max fields, returning its
141/// [`Dimension`].
142pub(crate) fn box_dimension(dtype: &DType) -> VortexResult<Dimension> {
143    let DType::Struct(fields, _) = dtype else {
144        vortex_bail!("box storage must be a Struct, was {dtype}");
145    };
146    for (name, field) in fields.names().iter().zip(fields.fields()) {
147        vortex_ensure!(
148            matches!(
149                field,
150                DType::Primitive(PType::F64, Nullability::NonNullable)
151            ),
152            "box field {name} must be non-nullable f64, was {field}"
153        );
154    }
155    box_dimension_from_names(fields.names())
156        .ok_or_else(|| vortex_err!("not a valid geoarrow.box dimension: {:?}", fields.names()))
157}
158
159/// Build a native [`Rect`] array from canonical min/max ordinate columns.
160pub(crate) fn build_rect_array(
161    ext_dtype: &ExtDType<Rect>,
162    corners: Vec<ArrayRef>,
163    len: usize,
164    validity: Validity,
165) -> VortexResult<ArrayRef> {
166    let dimension = box_dimension(ext_dtype.storage_dtype())?;
167    let storage = StructArray::try_new(
168        FieldNames::from(box_field_names(dimension)),
169        corners,
170        len,
171        validity,
172    )?
173    .into_array();
174    Ok(ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array())
175}
176
177static ARROW_BOX: CachedId = CachedId::new(BoxType::NAME);
178
179/// The `geoarrow.box` extension type for `dimension`.
180fn box_type(spatial_metadata: &SpatialMetadata, dimension: Dimension) -> BoxType {
181    BoxType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
182}
183
184/// Build a geoarrow `RectArray` from a `Rect`'s box `Struct` storage.
185fn rect_array(storage: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<RectArray> {
186    let box_type = box_type(&SpatialMetadata::default(), box_dimension(storage.dtype())?);
187    let session = ctx.session().clone();
188    let arrow = session.arrow().execute_arrow(storage.clone(), None, ctx)?;
189    RectArray::try_from((arrow.as_ref(), box_type))
190        .map_err(|e| vortex_err!("failed to construct RectArray: {e}"))
191}
192
193/// Decode `Rect` storage to `geo_types` (2D [`Geometry::Rect`]), for the spatial scalar functions.
194pub(crate) fn rect_geometries(
195    storage: &ArrayRef,
196    ctx: &mut ExecutionCtx,
197) -> VortexResult<Vec<Geometry<f64>>> {
198    rect_array(storage, ctx)?
199        .iter()
200        .map(|geometry| -> VortexResult<Geometry<f64>> {
201            Ok(geometry
202                .ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
203                .map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
204                .to_geometry())
205        })
206        .collect()
207}
208
209impl ArrowExportVTable for Rect {
210    fn arrow_ext_id(&self) -> Id {
211        *ARROW_BOX
212    }
213
214    fn vortex_id(&self) -> Id {
215        self.id()
216    }
217
218    fn to_arrow_field(
219        &self,
220        name: &str,
221        dtype: &DType,
222        session: &ArrowSession,
223    ) -> VortexResult<Option<Field>> {
224        let ext_type = dtype.as_extension();
225        let spatial_metadata = ext_type.metadata::<Rect>();
226        let dimension = box_dimension(ext_type.storage_dtype())?;
227
228        let mut field = session.to_arrow_field(name, ext_type.storage_dtype())?;
229        field.try_with_extension_type(box_type(spatial_metadata, dimension))?;
230
231        Ok(Some(field))
232    }
233
234    fn execute_arrow(
235        &self,
236        array: ArrayRef,
237        target: &Field,
238        options: &ArrowExportOptions,
239        ctx: &mut ExecutionCtx,
240    ) -> VortexResult<ArrowExport> {
241        let is_box = array
242            .dtype()
243            .as_extension_opt()
244            .map(|ext| ext.is::<Rect>())
245            .unwrap_or(false);
246        if !is_box {
247            return Ok(ArrowExport::Unsupported(array));
248        }
249
250        let Ok(box_meta) = target.try_extension_type::<BoxType>() else {
251            return Ok(ArrowExport::Unsupported(array));
252        };
253
254        let executed = array.execute::<ExtensionArray>(ctx)?;
255        let storage = executed.storage_array().clone();
256
257        let storage_field = Field::new(
258            String::new(),
259            target.data_type().clone(),
260            target.is_nullable(),
261        );
262        let session = ctx.session().clone();
263        let arrow_storage =
264            session
265                .arrow()
266                .exporter(options)
267                .execute_arrow(storage, Some(&storage_field), ctx)?;
268
269        // Round-trip through GeoArrow's rect array; `into_arrow` is concrete, so wrap in `Arc`.
270        let rects = RectArray::try_from((arrow_storage.as_ref(), box_meta))
271            .map_err(|e| vortex_err!("failed to construct RectArray: {e}"))?;
272
273        Ok(ArrowExport::Exported(Arc::new(rects.into_arrow())))
274    }
275}
276
277impl ArrowImportVTable for Rect {
278    fn arrow_ext_id(&self) -> Id {
279        *ARROW_BOX
280    }
281
282    /// Import a `geoarrow.box` field as the [`Rect`] dtype. Keyed off the standard GeoArrow name,
283    /// so any producer resolves here. Accepts the full `BoxType` extension, or — for a
284    /// metadata-less literal — the name alone, inferring the dimension from the field names.
285    fn from_arrow_field(
286        &self,
287        field: &Field,
288        session: &ArrowSession,
289    ) -> VortexResult<Option<DType>> {
290        let (dimension, metadata) = if let Ok(box_meta) = field.try_extension_type::<BoxType>() {
291            (
292                box_meta.dimension().into(),
293                spatial_metadata_from_arrow(box_meta.metadata()),
294            )
295        } else {
296            if field.extension_type_name() != Some(BoxType::NAME) {
297                return Ok(None);
298            }
299            // Infer from field names, not the strict `box_dimension` check: a literal's fields may
300            // be nullable, which that check rejects.
301            let Ok(DType::Struct(fields, _)) =
302                session.from_arrow_datatype(field.data_type(), field.is_nullable().into())
303            else {
304                return Ok(None);
305            };
306            let Some(dimension) = box_dimension_from_names(fields.names()) else {
307                return Ok(None);
308            };
309            (dimension, SpatialMetadata::default())
310        };
311
312        let storage_dtype = box_storage_dtype(dimension, field.is_nullable().into());
313        Ok(Some(DType::Extension(
314            ExtDType::try_with_vtable(Rect, metadata, storage_dtype)?.erased(),
315        )))
316    }
317
318    fn from_arrow_array(
319        &self,
320        array: ArrowArrayRef,
321        field: &Field,
322        dtype: &DType,
323        session: &ArrowSession,
324    ) -> VortexResult<ArrowImport> {
325        let Some(ext_dtype) = dtype.as_extension_opt() else {
326            return Ok(ArrowImport::Unsupported(array));
327        };
328        if !ext_dtype.is::<Rect>()
329            || field.try_extension_type::<BoxType>().is_err()
330            || !matches!(array.data_type(), DataType::Struct(_))
331        {
332            return Ok(ArrowImport::Unsupported(array));
333        }
334
335        let storage = session.from_arrow_array(array, field.is_nullable())?;
336        Ok(ArrowImport::Imported(
337            ExtensionArray::try_new(ext_dtype.clone(), storage)?.into_array(),
338        ))
339    }
340}
341
342#[cfg(test)]
343mod tests {
344    use geo_types::Geometry;
345    use rstest::rstest;
346    use vortex_array::VortexSessionExecute;
347    use vortex_array::arrays::ExtensionArray;
348    use vortex_array::arrays::extension::ExtensionArrayExt;
349    use vortex_array::dtype::DType;
350    use vortex_array::dtype::Nullability;
351    use vortex_array::dtype::PType;
352    use vortex_array::dtype::extension::ExtDType;
353    use vortex_error::VortexResult;
354
355    use super::Rect;
356    use super::box_dimension;
357    use super::box_storage_dtype;
358    use super::rect_geometries;
359    use crate::extension::SpatialMetadata;
360    use crate::extension::coordinate::Dimension;
361
362    fn spatial_meta() -> SpatialMetadata {
363        SpatialMetadata {
364            crs: Some("EPSG:4326".to_string()),
365        }
366    }
367
368    /// `Rect` accepts the canonical box storage of every GeoArrow dimension, and the storage dtype
369    /// round-trips back to that dimension.
370    #[rstest]
371    #[case::xy(Dimension::Xy)]
372    #[case::xyz(Dimension::Xyz)]
373    #[case::xym(Dimension::Xym)]
374    #[case::xyzm(Dimension::Xyzm)]
375    fn box_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
376        let storage = box_storage_dtype(dim, Nullability::NonNullable);
377        ExtDType::<Rect>::try_new(spatial_meta(), storage.clone())?;
378        assert_eq!(box_dimension(&storage)?, dim);
379        Ok(())
380    }
381
382    /// Invalid storage is rejected at dtype construction: non-struct storage, a struct with the
383    /// wrong field names, and a struct with a nullable field.
384    #[test]
385    fn box_rejects_invalid_storage() -> VortexResult<()> {
386        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
387        assert!(ExtDType::<Rect>::try_new(spatial_meta(), primitive).is_err());
388
389        let point_like = box_storage_dtype(Dimension::Xy, Nullability::NonNullable);
390        let DType::Struct(fields, _) = &point_like else {
391            unreachable!("box storage is a struct");
392        };
393        // Rename a field so it no longer matches the geoarrow.box layout.
394        let renamed = DType::Struct(
395            vortex_array::dtype::StructFields::new(
396                ["x", "ymin", "xmax", "ymax"].into(),
397                fields.fields().collect(),
398            ),
399            Nullability::NonNullable,
400        );
401        assert!(ExtDType::<Rect>::try_new(spatial_meta(), renamed).is_err());
402        Ok(())
403    }
404
405    /// A `Rect` column decodes to 2D `geo_types` rectangles.
406    #[test]
407    fn box_decodes_to_geo_types_rect() -> VortexResult<()> {
408        let session = vortex_array::array_session();
409        let mut ctx = session.create_execution_ctx();
410
411        let rects = crate::test_harness::rect_column(vec![(0.0, 0.0, 2.0, 3.0)])?;
412        let storage = rects
413            .execute::<ExtensionArray>(&mut ctx)?
414            .storage_array()
415            .clone();
416
417        let geometries = rect_geometries(&storage, &mut ctx)?;
418        assert_eq!(
419            geometries,
420            vec![Geometry::Rect(geo_types::Rect::new((0.0, 0.0), (2.0, 3.0)))]
421        );
422        Ok(())
423    }
424}