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