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//! Native bounding-box geometry (`vortex.st.box`).
5//!
6//! [`Rect`] stores the lower corner's ordinates followed by the upper corner's ordinates as
7//! `Struct<xmin, ymin[, zmin][, mmin], xmax, ymax[, zmax][, mmax]>` of non-nullable `f64` fields.
8//! [`SpatialMetadata`] declares the coordinate dimension and optional coordinate reference system.
9//! Its GeoArrow wire type is `geoarrow.box`.
10//!
11//! Decoding to [`Geometry::Rect`] produces a 2D rectangle and drops any `z` and `m` bounds.
12
13use std::sync::Arc;
14
15use arrow_array::ArrayRef as ArrowArrayRef;
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 vortex_array::ArrayRef;
25use vortex_array::ExecutionCtx;
26use vortex_array::IntoArray;
27use vortex_array::arrays::ExtensionArray;
28use vortex_array::arrays::StructArray;
29use vortex_array::arrays::extension::ExtensionArrayExt;
30use vortex_array::dtype::DType;
31use vortex_array::dtype::FieldNames;
32use vortex_array::dtype::Nullability;
33use vortex_array::dtype::PType;
34use vortex_array::dtype::StructFields;
35use vortex_array::dtype::extension::ExtDType;
36use vortex_array::dtype::extension::ExtId;
37use vortex_array::dtype::extension::ExtVTable;
38use vortex_array::scalar::ScalarValue;
39use vortex_array::validity::Validity;
40use vortex_arrow::ArrowExport;
41use vortex_arrow::ArrowExportOptions;
42use vortex_arrow::ArrowExtVTable;
43use vortex_arrow::ArrowImport;
44use vortex_arrow::ArrowMetadataPolicy;
45use vortex_arrow::ArrowSession;
46use vortex_arrow::ExecuteArrowExt;
47use vortex_error::VortexResult;
48use vortex_error::vortex_bail;
49use vortex_error::vortex_err;
50use vortex_session::registry::CachedId;
51use vortex_session::registry::Id;
52
53use super::SpatialMetadata;
54use super::coordinate::Dimension;
55use super::geoarrow_metadata;
56use super::spatial_metadata_from_arrow;
57
58/// An axis-aligned bounding box (`geoarrow.box`), stored as `Struct<xmin, ymin[, ..], xmax, ymax[, ..]>`.
59// Named `Rect`, not `Box`: matches `geo::Rect` / geoarrow-rs `RectArray`, and `Box` is a std name.
60#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
61pub struct Rect;
62
63impl ExtVTable for Rect {
64    type Metadata = SpatialMetadata;
65    type StoredMetadata = super::SpatialStoredMetadata;
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.serialize())
76    }
77
78    fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult<Self::StoredMetadata> {
79        super::SpatialStoredMetadata::deserialize(metadata)
80    }
81
82    fn metadata_from_storage(
83        &self,
84        stored_metadata: Self::StoredMetadata,
85        storage_dtype: &DType,
86    ) -> VortexResult<Self::Metadata> {
87        Ok(SpatialMetadata::from_stored_metadata(
88            stored_metadata,
89            Some(box_dimension(storage_dtype)?),
90        ))
91    }
92
93    fn storage_dtype(metadata: &Self::Metadata) -> DType {
94        box_storage_dtype(metadata.native_dimension(), Nullability::NonNullable)
95    }
96
97    fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> {
98        metadata.validate_native(Rect.id())
99    }
100
101    fn unpack_native<'a>(
102        _ext_dtype: &'a ExtDType<Self>,
103        storage_value: &'a ScalarValue,
104    ) -> VortexResult<&'a ScalarValue> {
105        Ok(storage_value)
106    }
107}
108
109/// The `geoarrow.box` storage field names for `dim`: the lower corner's ordinates followed by the
110/// upper corner's.
111pub(crate) fn box_field_names(dim: Dimension) -> &'static [&'static str] {
112    match dim {
113        Dimension::Xy => &["xmin", "ymin", "xmax", "ymax"],
114        Dimension::Xyz => &["xmin", "ymin", "zmin", "xmax", "ymax", "zmax"],
115        Dimension::Xym => &["xmin", "ymin", "mmin", "xmax", "ymax", "mmax"],
116        Dimension::Xyzm => &[
117            "xmin", "ymin", "zmin", "mmin", "xmax", "ymax", "zmax", "mmax",
118        ],
119    }
120}
121
122/// The dimension whose box field names match `names`, or `None` if none do.
123fn box_dimension_from_names(names: &FieldNames) -> Option<Dimension> {
124    [
125        Dimension::Xy,
126        Dimension::Xyz,
127        Dimension::Xym,
128        Dimension::Xyzm,
129    ]
130    .into_iter()
131    .find(|&dim| {
132        names
133            .iter()
134            .map(AsRef::as_ref)
135            .eq(box_field_names(dim).iter().copied())
136    })
137}
138
139/// Canonical box storage: a `Struct` of non-nullable `f64` min/max fields, with `nullability` at
140/// the struct (per-box) level.
141pub(crate) fn box_storage_dtype(dim: Dimension, nullability: Nullability) -> DType {
142    let names = box_field_names(dim);
143    let fields = std::iter::repeat_n(
144        DType::Primitive(PType::F64, Nullability::NonNullable),
145        names.len(),
146    )
147    .collect::<Vec<_>>();
148    DType::Struct(
149        StructFields::new(FieldNames::from(names), fields),
150        nullability,
151    )
152}
153
154/// Returns the [`Dimension`] from a box `Struct`'s field names, as [`box_field_names`] names them.
155///
156/// Field dtypes and nullability are not checked. Reads compare the complete storage dtype with
157/// the declaration after recovering the dimension, so a mismatch reports both storage dtypes.
158pub(crate) fn box_dimension(dtype: &DType) -> VortexResult<Dimension> {
159    let DType::Struct(fields, _) = dtype else {
160        vortex_bail!("box storage must be a Struct, got {dtype}");
161    };
162    box_dimension_from_names(fields.names())
163        .ok_or_else(|| vortex_err!("not a valid geoarrow.box dimension: {:?}", fields.names()))
164}
165
166/// Build a native [`Rect`] array from canonical min/max ordinate columns.
167pub(crate) fn build_rect_array(
168    ext_dtype: &ExtDType<Rect>,
169    corners: Vec<ArrayRef>,
170    len: usize,
171    validity: Validity,
172) -> VortexResult<ArrayRef> {
173    let dimension = ext_dtype.metadata().native_dimension();
174    let storage = StructArray::try_new(
175        FieldNames::from(box_field_names(dimension)),
176        corners,
177        len,
178        validity,
179    )?
180    .into_array();
181    Ok(ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array())
182}
183
184static ARROW_BOX: CachedId = CachedId::new(BoxType::NAME);
185
186/// The `geoarrow.box` extension type for `dimension`.
187fn box_type(spatial_metadata: &SpatialMetadata, dimension: Dimension) -> BoxType {
188    BoxType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
189}
190
191/// Build a geoarrow `RectArray` from a `Rect`'s box `Struct` storage.
192fn rect_array(storage: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<RectArray> {
193    let box_type = box_type(&SpatialMetadata::default(), box_dimension(storage.dtype())?);
194    let arrow = storage.clone().execute_arrow(None, ctx)?;
195    RectArray::try_from((arrow.as_ref(), box_type))
196        .map_err(|e| vortex_err!("failed to construct RectArray: {e}"))
197}
198
199/// Decode `Rect` storage to `geo_types` (2D [`Geometry::Rect`]), for the spatial scalar functions.
200pub(crate) fn rect_geometries(
201    storage: &ArrayRef,
202    ctx: &mut ExecutionCtx,
203) -> VortexResult<Vec<Geometry<f64>>> {
204    rect_array(storage, ctx)?
205        .iter()
206        .map(|geometry| -> VortexResult<Geometry<f64>> {
207            Ok(geometry
208                .ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
209                .map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
210                .to_geometry())
211        })
212        .collect()
213}
214
215impl ArrowExtVTable for Rect {
216    fn metadata_policy() -> ArrowMetadataPolicy {
217        ArrowMetadataPolicy::ArrowNative
218    }
219
220    fn arrow_ext_id(&self) -> Id {
221        *ARROW_BOX
222    }
223
224    fn to_arrow_field(
225        &self,
226        name: &str,
227        ext_dtype: &ExtDType<Self>,
228        session: &ArrowSession,
229    ) -> VortexResult<Option<Field>> {
230        let spatial_metadata = ext_dtype.metadata();
231        let dimension = spatial_metadata.native_dimension();
232
233        let mut field = session.to_arrow_field(name, ext_dtype.storage_dtype())?;
234        field.try_with_extension_type(box_type(spatial_metadata, dimension))?;
235
236        Ok(Some(field))
237    }
238
239    fn execute_arrow(
240        &self,
241        array: ArrayRef,
242        target: &Field,
243        options: &ArrowExportOptions,
244        ctx: &mut ExecutionCtx,
245    ) -> VortexResult<ArrowExport> {
246        let Ok(box_meta) = target.try_extension_type::<BoxType>() else {
247            return Ok(ArrowExport::Unsupported(array));
248        };
249
250        let executed = array.execute::<ExtensionArray>(ctx)?;
251        let storage = executed.storage_array().clone();
252
253        let storage_field = Field::new(
254            String::new(),
255            target.data_type().clone(),
256            target.is_nullable(),
257        );
258        let arrow_storage =
259            storage.execute_arrow_with_options(Some(&storage_field), options, ctx)?;
260
261        // Round-trip through GeoArrow's rect array; `into_arrow` is concrete, so wrap in `Arc`.
262        let rects = RectArray::try_from((arrow_storage.as_ref(), box_meta))
263            .map_err(|e| vortex_err!("failed to construct RectArray: {e}"))?;
264
265        Ok(ArrowExport::Exported(Arc::new(rects.into_arrow())))
266    }
267
268    fn from_arrow_field(
269        field: &Field,
270        _session: &ArrowSession,
271    ) -> VortexResult<Option<ExtDType<Self>>> {
272        let box_meta = field.try_extension_type::<BoxType>()?;
273
274        let metadata = spatial_metadata_from_arrow(box_meta.metadata())
275            .with_dimension(box_meta.dimension().into());
276        Ok(Some(ExtDType::try_with_vtable(
277            Rect,
278            metadata,
279            field.is_nullable().into(),
280        )?))
281    }
282
283    fn from_arrow_array(
284        array: ArrowArrayRef,
285        _field: &Field,
286        ext_dtype: &ExtDType<Self>,
287        session: &ArrowSession,
288    ) -> VortexResult<ArrowImport> {
289        session
290            .from_arrow_storage(array, &ext_dtype.clone().erased())
291            .map(ArrowImport::Imported)
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use std::sync::LazyLock;
298
299    use geo_types::Geometry;
300    use rstest::rstest;
301    use vortex_array::VortexSessionExecute;
302    use vortex_array::arrays::ExtensionArray;
303    use vortex_array::arrays::extension::ExtensionArrayExt;
304    use vortex_array::dtype::DType;
305    use vortex_array::dtype::Nullability;
306    use vortex_array::dtype::PType;
307    use vortex_array::dtype::extension::ExtDTypePlugin;
308    use vortex_error::VortexResult;
309    use vortex_session::VortexSession;
310
311    use super::Rect;
312    use super::box_dimension;
313    use super::box_storage_dtype;
314    use super::rect_geometries;
315    use crate::extension::SpatialMetadata;
316    use crate::extension::coordinate::Dimension;
317
318    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
319
320    fn spatial_meta() -> SpatialMetadata {
321        SpatialMetadata::new(Some("EPSG:4326".to_string()))
322    }
323
324    /// `Rect` reads the canonical box storage of every GeoArrow dimension, and the storage dtype
325    /// round-trips back to that dimension.
326    #[rstest]
327    #[case::xy(Dimension::Xy)]
328    #[case::xyz(Dimension::Xyz)]
329    #[case::xym(Dimension::Xym)]
330    #[case::xyzm(Dimension::Xyzm)]
331    fn box_reads_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
332        let storage = box_storage_dtype(dim, Nullability::NonNullable);
333        Rect.deserialize(&spatial_meta().serialize(), storage.clone())?;
334        assert_eq!(box_dimension(&storage)?, dim);
335        Ok(())
336    }
337
338    /// Invalid storage fails to read: non-struct storage and a struct with the wrong field names.
339    #[test]
340    fn box_rejects_invalid_storage() -> VortexResult<()> {
341        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
342        assert!(
343            Rect.deserialize(&spatial_meta().serialize(), primitive)
344                .is_err()
345        );
346
347        let point_like = box_storage_dtype(Dimension::Xy, Nullability::NonNullable);
348        let DType::Struct(fields, _) = &point_like else {
349            unreachable!("box storage is a struct");
350        };
351        // Rename a field so it no longer matches the geoarrow.box layout.
352        let renamed = DType::Struct(
353            vortex_array::dtype::StructFields::new(
354                ["x", "ymin", "xmax", "ymax"].into(),
355                fields.fields().collect(),
356            ),
357            Nullability::NonNullable,
358        );
359        assert!(
360            Rect.deserialize(&spatial_meta().serialize(), renamed)
361                .is_err()
362        );
363        Ok(())
364    }
365
366    /// A `Rect` column decodes to 2D `geo_types` rectangles.
367    #[test]
368    fn box_decodes_to_geo_types_rect() -> VortexResult<()> {
369        let mut ctx = SESSION.create_execution_ctx();
370
371        let rects = crate::test_harness::rect_column(vec![(0.0, 0.0, 2.0, 3.0)])?;
372        let storage = rects
373            .execute::<ExtensionArray>(&mut ctx)?
374            .storage_array()
375            .clone();
376
377        let geometries = rect_geometries(&storage, &mut ctx)?;
378        assert_eq!(
379            geometries,
380            vec![Geometry::Rect(geo_types::Rect::new((0.0, 0.0), (2.0, 3.0)))]
381        );
382        Ok(())
383    }
384}