vortex-spatial 0.95.0

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

//! Native multipolygon geometry (`vortex.st.multipolygon`).
//!
//! [`MultiPolygon`] stores polygons, their rings, and their coordinates as
//! `List<List<List<Struct<x, y[, z][, m]>>>>`. [`SpatialMetadata`] declares the coordinate
//! dimension and optional coordinate reference system. Coordinates use non-nullable `f64` fields.
//! Only the outer list can be nullable. A single polygon can be represented as a one-element
//! multipolygon.

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::MultiPolygonArray;
use geoarrow::datatypes::CoordType;
use geoarrow::datatypes::MultiPolygonType;
use vortex_array::ArrayRef;
use vortex_array::ExecutionCtx;
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::extension::ExtDType;
use vortex_array::dtype::extension::ExtId;
use vortex_array::dtype::extension::ExtVTable;
use vortex_array::scalar::ScalarValue;
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::ArrowSessionExt;
use vortex_arrow::ExecuteArrowExt;
use vortex_error::VortexError;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_ensure;
use vortex_error::vortex_err;
use vortex_session::registry::CachedId;
use vortex_session::registry::Id;

use super::SpatialMetadata;
use super::coordinate::Dimension;
use super::coordinate::coordinate_dimension;
use super::coordinate::coordinate_storage_dtype;
use super::geoarrow_metadata;
use super::geoarrow_to_wkb;
use super::spatial_metadata_from_arrow;

/// A multipolygon (`geoarrow.multipolygon`); a single `Polygon` is a one-element multipolygon.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct MultiPolygon;

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

    fn id(&self) -> ExtId {
        static ID: CachedId = CachedId::new("vortex.st.multipolygon");
        *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(multipolygon_dimension(storage_dtype)?),
        ))
    }

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

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

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

/// Storage `List<List<List<Struct>>>`: polygons → rings → coordinates.
pub(crate) fn multipolygon_storage_dtype(dim: Dimension, nullability: Nullability) -> DType {
    let coords = coordinate_storage_dtype(dim, Nullability::NonNullable);
    let ring = DType::List(Arc::new(coords), Nullability::NonNullable);
    let polygon = DType::List(Arc::new(ring), Nullability::NonNullable);
    DType::List(Arc::new(polygon), nullability)
}

/// Infers the coordinate [`Dimension`] of `List<List<List<coordinate-struct>>>` storage.
///
/// Checks the list nesting and delegates coordinate field-name inference to
/// [`coordinate_dimension`]. Reads validate the complete storage dtype against the declaration.
pub(crate) fn multipolygon_dimension(dtype: &DType) -> VortexResult<Dimension> {
    let DType::List(polygon, _) = dtype else {
        vortex_bail!("multipolygon storage must be a List of polygons, got {dtype}");
    };
    let DType::List(ring, _) = polygon.as_ref() else {
        vortex_bail!("multipolygon polygon storage must be a List of rings, got {polygon}");
    };
    let DType::List(coords, _) = ring.as_ref() else {
        vortex_bail!("multipolygon ring storage must be a List of coordinates, got {ring}");
    };
    coordinate_dimension(coords)
}

static ARROW_MULTIPOLYGON: CachedId = CachedId::new(MultiPolygonType::NAME);

/// The `geoarrow.multipolygon` type for `dimension`, with separated (struct) coordinates.
fn multipolygon_type(spatial_metadata: &SpatialMetadata, dimension: Dimension) -> MultiPolygonType {
    MultiPolygonType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
}

/// Decode storage to `geo_types` for the spatial scalar functions (CRS is irrelevant to planar ops).
pub(crate) fn multipolygon_geometries(
    storage: &ArrayRef,
    ctx: &mut ExecutionCtx,
) -> VortexResult<Vec<Geometry<f64>>> {
    multipolygon_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()
}

/// Build a geoarrow `MultiPolygonArray` from the `MultiPolygon` storage.
fn multipolygon_array(
    storage: &ArrayRef,
    ctx: &mut ExecutionCtx,
) -> VortexResult<MultiPolygonArray> {
    let multipolygon_type = multipolygon_type(
        &SpatialMetadata::default(),
        multipolygon_dimension(storage.dtype())?,
    );
    let arrow = storage.clone().execute_arrow(None, ctx)?;
    MultiPolygonArray::try_from((arrow.as_ref(), multipolygon_type))
        .map_err(|e| vortex_err!("failed to construct MultiPolygonArray: {e}"))
}

/// A validated `MultiPolygon` array (`try_from` checks the extension type).
pub struct MultiPolygonData(ExtensionArray);

impl TryFrom<ExtensionArray> for MultiPolygonData {
    type Error = VortexError;

    fn try_from(ext: ExtensionArray) -> Result<Self, Self::Error> {
        vortex_ensure!(
            ext.ext_dtype().is::<MultiPolygon>(),
            "expected a MultiPolygon extension array"
        );
        Ok(MultiPolygonData(ext))
    }
}

impl MultiPolygonData {
    /// Serialize multipolygons to WKB (a view array) — the form DuckDB `GEOMETRY` takes.
    pub fn to_wkb(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
        geoarrow_to_wkb(
            &multipolygon_array(self.0.storage_array(), ctx)?,
            &ctx.session().arrow(),
        )
    }
}

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

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

    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 arrow_type = multipolygon_type(spatial_metadata, dimension);
        let mut field = Field::new(
            name,
            arrow_type.data_type(),
            ext_dtype.storage_dtype().is_nullable(),
        );
        field.try_with_extension_type(arrow_type)?;

        Ok(Some(field))
    }

    fn execute_arrow(
        &self,
        array: ArrayRef,
        target: &Field,
        options: &ArrowExportOptions,
        ctx: &mut ExecutionCtx,
    ) -> VortexResult<ArrowExport> {
        let Ok(multipolygon_meta) = target.try_extension_type::<MultiPolygonType>() else {
            return Ok(ArrowExport::Unsupported(array));
        };
        if multipolygon_meta.coord_type() != CoordType::Separated {
            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)?;

        // The validated target already shapes the storage. GeoArrow constructors can panic on
        // valid Arrow lists that retain unused child values after filtering.
        Ok(ArrowExport::Exported(arrow_storage))
    }

    fn from_arrow_field(
        field: &Field,
        _session: &ArrowSession,
    ) -> VortexResult<Option<ExtDType<Self>>> {
        let multipolygon_meta = field.try_extension_type::<MultiPolygonType>()?;
        vortex_ensure!(
            multipolygon_meta.coord_type() == CoordType::Separated,
            "geoarrow.multipolygon with interleaved coordinates is not supported; \
             re-encode with separated (struct) coordinates"
        );

        let metadata = spatial_metadata_from_arrow(multipolygon_meta.metadata())
            .with_dimension(multipolygon_meta.dimension().into());
        Ok(Some(ExtDType::try_with_vtable(
            MultiPolygon,
            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::Arc;

    use rstest::rstest;
    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 super::MultiPolygon;
    use super::multipolygon_storage_dtype;
    use crate::extension::SpatialMetadata;
    use crate::extension::coordinate::Dimension;
    use crate::extension::coordinate::coordinate_storage_dtype;

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

    /// `MultiPolygon` reads the canonical `List<List<List<coordinate-struct>>>` storage of every
    /// dimension.
    #[rstest]
    #[case::xy(Dimension::Xy)]
    #[case::xyz(Dimension::Xyz)]
    #[case::xym(Dimension::Xym)]
    #[case::xyzm(Dimension::Xyzm)]
    fn multipolygon_reads_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
        let storage = multipolygon_storage_dtype(dim, Nullability::NonNullable);
        MultiPolygon.deserialize(&spatial_meta().serialize(), storage)?;
        Ok(())
    }

    /// Non-multipolygon storage fails to read, for example `f64` or a double list (polygon).
    #[test]
    fn multipolygon_rejects_invalid_storage() -> VortexResult<()> {
        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
        assert!(
            MultiPolygon
                .deserialize(&spatial_meta().serialize(), primitive)
                .is_err()
        );

        // A double list (polygon) is not a multipolygon.
        let coords = coordinate_storage_dtype(Dimension::Xy, Nullability::NonNullable);
        let ring = DType::List(Arc::new(coords), Nullability::NonNullable);
        let polygon = DType::List(Arc::new(ring), Nullability::NonNullable);
        assert!(
            MultiPolygon
                .deserialize(&spatial_meta().serialize(), polygon)
                .is_err()
        );
        Ok(())
    }
}