vortex-spatial 0.94.0

Spatial data types and compute for Vortex
Documentation
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

//! Native bounding-box geometry (`vortex.st.box`).
//!
//! [`Rect`] stores the lower corner's ordinates followed by the upper corner's ordinates as
//! `Struct<xmin, ymin[, zmin][, mmin], xmax, ymax[, zmax][, mmax]>` of non-nullable `f64` fields.
//! [`SpatialMetadata`] declares the coordinate dimension and optional coordinate reference system.
//! Its GeoArrow wire type is `geoarrow.box`.
//!
//! Decoding to [`Geometry::Rect`] produces a 2D rectangle and drops any `z` and `m` bounds.

use std::sync::Arc;

use arrow_array::ArrayRef as ArrowArrayRef;
use arrow_schema::Field;
use arrow_schema::extension::ExtensionType;
use geo_traits::to_geo::ToGeoGeometry;
use geo_types::Geometry;
use geoarrow::array::GeoArrowArrayAccessor;
use geoarrow::array::IntoArrow;
use geoarrow::array::RectArray;
use geoarrow::datatypes::BoxType;
use vortex_array::ArrayRef;
use vortex_array::ExecutionCtx;
use vortex_array::IntoArray;
use vortex_array::arrays::ExtensionArray;
use vortex_array::arrays::StructArray;
use vortex_array::arrays::extension::ExtensionArrayExt;
use vortex_array::dtype::DType;
use vortex_array::dtype::FieldNames;
use vortex_array::dtype::Nullability;
use vortex_array::dtype::PType;
use vortex_array::dtype::StructFields;
use vortex_array::dtype::extension::ExtDType;
use vortex_array::dtype::extension::ExtId;
use vortex_array::dtype::extension::ExtVTable;
use vortex_array::scalar::ScalarValue;
use vortex_array::validity::Validity;
use vortex_arrow::ArrowExport;
use vortex_arrow::ArrowExportOptions;
use vortex_arrow::ArrowExtVTable;
use vortex_arrow::ArrowImport;
use vortex_arrow::ArrowMetadataPolicy;
use vortex_arrow::ArrowSession;
use vortex_arrow::ExecuteArrowExt;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_err;
use vortex_session::registry::CachedId;
use vortex_session::registry::Id;

use super::SpatialMetadata;
use super::coordinate::Dimension;
use super::geoarrow_metadata;
use super::spatial_metadata_from_arrow;

/// An axis-aligned bounding box (`geoarrow.box`), stored as `Struct<xmin, ymin[, ..], xmax, ymax[, ..]>`.
// Named `Rect`, not `Box`: matches `geo::Rect` / geoarrow-rs `RectArray`, and `Box` is a std name.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct Rect;

impl ExtVTable for Rect {
    type Metadata = SpatialMetadata;
    type StoredMetadata = super::SpatialStoredMetadata;
    // No cheap owned value; expose the raw storage scalar like `Polygon`.
    type NativeValue<'a> = &'a ScalarValue;

    fn id(&self) -> ExtId {
        static ID: CachedId = CachedId::new("vortex.st.box");
        *ID
    }

    fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
        Ok(metadata.serialize())
    }

    fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult<Self::StoredMetadata> {
        super::SpatialStoredMetadata::deserialize(metadata)
    }

    fn metadata_from_storage(
        &self,
        stored_metadata: Self::StoredMetadata,
        storage_dtype: &DType,
    ) -> VortexResult<Self::Metadata> {
        Ok(SpatialMetadata::from_stored_metadata(
            stored_metadata,
            Some(box_dimension(storage_dtype)?),
        ))
    }

    fn storage_dtype(metadata: &Self::Metadata) -> DType {
        box_storage_dtype(metadata.native_dimension(), Nullability::NonNullable)
    }

    fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> {
        metadata.validate_native(Rect.id())
    }

    fn unpack_native<'a>(
        _ext_dtype: &'a ExtDType<Self>,
        storage_value: &'a ScalarValue,
    ) -> VortexResult<&'a ScalarValue> {
        Ok(storage_value)
    }
}

/// The `geoarrow.box` storage field names for `dim`: the lower corner's ordinates followed by the
/// upper corner's.
pub(crate) fn box_field_names(dim: Dimension) -> &'static [&'static str] {
    match dim {
        Dimension::Xy => &["xmin", "ymin", "xmax", "ymax"],
        Dimension::Xyz => &["xmin", "ymin", "zmin", "xmax", "ymax", "zmax"],
        Dimension::Xym => &["xmin", "ymin", "mmin", "xmax", "ymax", "mmax"],
        Dimension::Xyzm => &[
            "xmin", "ymin", "zmin", "mmin", "xmax", "ymax", "zmax", "mmax",
        ],
    }
}

/// The dimension whose box field names match `names`, or `None` if none do.
fn box_dimension_from_names(names: &FieldNames) -> Option<Dimension> {
    [
        Dimension::Xy,
        Dimension::Xyz,
        Dimension::Xym,
        Dimension::Xyzm,
    ]
    .into_iter()
    .find(|&dim| {
        names
            .iter()
            .map(AsRef::as_ref)
            .eq(box_field_names(dim).iter().copied())
    })
}

/// Canonical box storage: a `Struct` of non-nullable `f64` min/max fields, with `nullability` at
/// the struct (per-box) level.
pub(crate) fn box_storage_dtype(dim: Dimension, nullability: Nullability) -> DType {
    let names = box_field_names(dim);
    let fields = std::iter::repeat_n(
        DType::Primitive(PType::F64, Nullability::NonNullable),
        names.len(),
    )
    .collect::<Vec<_>>();
    DType::Struct(
        StructFields::new(FieldNames::from(names), fields),
        nullability,
    )
}

/// Returns the [`Dimension`] from a box `Struct`'s field names, as [`box_field_names`] names them.
///
/// Field dtypes and nullability are not checked. Reads compare the complete storage dtype with
/// the declaration after recovering the dimension, so a mismatch reports both storage dtypes.
pub(crate) fn box_dimension(dtype: &DType) -> VortexResult<Dimension> {
    let DType::Struct(fields, _) = dtype else {
        vortex_bail!("box storage must be a Struct, got {dtype}");
    };
    box_dimension_from_names(fields.names())
        .ok_or_else(|| vortex_err!("not a valid geoarrow.box dimension: {:?}", fields.names()))
}

/// Build a native [`Rect`] array from canonical min/max ordinate columns.
pub(crate) fn build_rect_array(
    ext_dtype: &ExtDType<Rect>,
    corners: Vec<ArrayRef>,
    len: usize,
    validity: Validity,
) -> VortexResult<ArrayRef> {
    let dimension = ext_dtype.metadata().native_dimension();
    let storage = StructArray::try_new(
        FieldNames::from(box_field_names(dimension)),
        corners,
        len,
        validity,
    )?
    .into_array();
    Ok(ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array())
}

static ARROW_BOX: CachedId = CachedId::new(BoxType::NAME);

/// The `geoarrow.box` extension type for `dimension`.
fn box_type(spatial_metadata: &SpatialMetadata, dimension: Dimension) -> BoxType {
    BoxType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
}

/// Build a geoarrow `RectArray` from a `Rect`'s box `Struct` storage.
fn rect_array(storage: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<RectArray> {
    let box_type = box_type(&SpatialMetadata::default(), box_dimension(storage.dtype())?);
    let arrow = storage.clone().execute_arrow(None, ctx)?;
    RectArray::try_from((arrow.as_ref(), box_type))
        .map_err(|e| vortex_err!("failed to construct RectArray: {e}"))
}

/// Decode `Rect` storage to `geo_types` (2D [`Geometry::Rect`]), for the spatial scalar functions.
pub(crate) fn rect_geometries(
    storage: &ArrayRef,
    ctx: &mut ExecutionCtx,
) -> VortexResult<Vec<Geometry<f64>>> {
    rect_array(storage, ctx)?
        .iter()
        .map(|geometry| -> VortexResult<Geometry<f64>> {
            Ok(geometry
                .ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
                .map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
                .to_geometry())
        })
        .collect()
}

impl ArrowExtVTable for Rect {
    fn metadata_policy() -> ArrowMetadataPolicy {
        ArrowMetadataPolicy::ArrowNative
    }

    fn arrow_ext_id(&self) -> Id {
        *ARROW_BOX
    }

    fn to_arrow_field(
        &self,
        name: &str,
        ext_dtype: &ExtDType<Self>,
        session: &ArrowSession,
    ) -> VortexResult<Option<Field>> {
        let spatial_metadata = ext_dtype.metadata();
        let dimension = spatial_metadata.native_dimension();

        let mut field = session.to_arrow_field(name, ext_dtype.storage_dtype())?;
        field.try_with_extension_type(box_type(spatial_metadata, dimension))?;

        Ok(Some(field))
    }

    fn execute_arrow(
        &self,
        array: ArrayRef,
        target: &Field,
        options: &ArrowExportOptions,
        ctx: &mut ExecutionCtx,
    ) -> VortexResult<ArrowExport> {
        let Ok(box_meta) = target.try_extension_type::<BoxType>() else {
            return Ok(ArrowExport::Unsupported(array));
        };

        let executed = array.execute::<ExtensionArray>(ctx)?;
        let storage = executed.storage_array().clone();

        let storage_field = Field::new(
            String::new(),
            target.data_type().clone(),
            target.is_nullable(),
        );
        let arrow_storage =
            storage.execute_arrow_with_options(Some(&storage_field), options, ctx)?;

        // Round-trip through GeoArrow's rect array; `into_arrow` is concrete, so wrap in `Arc`.
        let rects = RectArray::try_from((arrow_storage.as_ref(), box_meta))
            .map_err(|e| vortex_err!("failed to construct RectArray: {e}"))?;

        Ok(ArrowExport::Exported(Arc::new(rects.into_arrow())))
    }

    fn from_arrow_field(
        field: &Field,
        _session: &ArrowSession,
    ) -> VortexResult<Option<ExtDType<Self>>> {
        let box_meta = field.try_extension_type::<BoxType>()?;

        let metadata = spatial_metadata_from_arrow(box_meta.metadata())
            .with_dimension(box_meta.dimension().into());
        Ok(Some(ExtDType::try_with_vtable(
            Rect,
            metadata,
            field.is_nullable().into(),
        )?))
    }

    fn from_arrow_array(
        array: ArrowArrayRef,
        _field: &Field,
        ext_dtype: &ExtDType<Self>,
        session: &ArrowSession,
    ) -> VortexResult<ArrowImport> {
        session
            .from_arrow_storage(array, &ext_dtype.clone().erased())
            .map(ArrowImport::Imported)
    }
}

#[cfg(test)]
mod tests {
    use std::sync::LazyLock;

    use geo_types::Geometry;
    use rstest::rstest;
    use vortex_array::VortexSessionExecute;
    use vortex_array::arrays::ExtensionArray;
    use vortex_array::arrays::extension::ExtensionArrayExt;
    use vortex_array::dtype::DType;
    use vortex_array::dtype::Nullability;
    use vortex_array::dtype::PType;
    use vortex_array::dtype::extension::ExtDTypePlugin;
    use vortex_error::VortexResult;
    use vortex_session::VortexSession;

    use super::Rect;
    use super::box_dimension;
    use super::box_storage_dtype;
    use super::rect_geometries;
    use crate::extension::SpatialMetadata;
    use crate::extension::coordinate::Dimension;

    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);

    fn spatial_meta() -> SpatialMetadata {
        SpatialMetadata::new(Some("EPSG:4326".to_string()))
    }

    /// `Rect` reads the canonical box storage of every GeoArrow dimension, and the storage dtype
    /// round-trips back to that dimension.
    #[rstest]
    #[case::xy(Dimension::Xy)]
    #[case::xyz(Dimension::Xyz)]
    #[case::xym(Dimension::Xym)]
    #[case::xyzm(Dimension::Xyzm)]
    fn box_reads_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
        let storage = box_storage_dtype(dim, Nullability::NonNullable);
        Rect.deserialize(&spatial_meta().serialize(), storage.clone())?;
        assert_eq!(box_dimension(&storage)?, dim);
        Ok(())
    }

    /// Invalid storage fails to read: non-struct storage and a struct with the wrong field names.
    #[test]
    fn box_rejects_invalid_storage() -> VortexResult<()> {
        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
        assert!(
            Rect.deserialize(&spatial_meta().serialize(), primitive)
                .is_err()
        );

        let point_like = box_storage_dtype(Dimension::Xy, Nullability::NonNullable);
        let DType::Struct(fields, _) = &point_like else {
            unreachable!("box storage is a struct");
        };
        // Rename a field so it no longer matches the geoarrow.box layout.
        let renamed = DType::Struct(
            vortex_array::dtype::StructFields::new(
                ["x", "ymin", "xmax", "ymax"].into(),
                fields.fields().collect(),
            ),
            Nullability::NonNullable,
        );
        assert!(
            Rect.deserialize(&spatial_meta().serialize(), renamed)
                .is_err()
        );
        Ok(())
    }

    /// A `Rect` column decodes to 2D `geo_types` rectangles.
    #[test]
    fn box_decodes_to_geo_types_rect() -> VortexResult<()> {
        let mut ctx = SESSION.create_execution_ctx();

        let rects = crate::test_harness::rect_column(vec![(0.0, 0.0, 2.0, 3.0)])?;
        let storage = rects
            .execute::<ExtensionArray>(&mut ctx)?
            .storage_array()
            .clone();

        let geometries = rect_geometries(&storage, &mut ctx)?;
        assert_eq!(
            geometries,
            vec![Geometry::Rect(geo_types::Rect::new((0.0, 0.0), (2.0, 3.0)))]
        );
        Ok(())
    }
}