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 polygon geometry (`vortex.st.polygon`).
//!
//! [`Polygon`] stores rings as `List<List<Struct<x, y[, z][, m]>>>`. The first ring is the exterior
//! boundary and the remaining rings are holes. [`SpatialMetadata`] declares the coordinate
//! dimension and optional coordinate reference system. Coordinates use non-nullable `f64` fields.
//! Only the outer list can be nullable.

use std::sync::Arc;

use arrow_array::ArrayRef as ArrowArrayRef;
use arrow_schema::Field;
use arrow_schema::extension::ExtensionType;
use geo::HasDimensions;
use geo_traits::to_geo::ToGeoGeometry;
use geo_types::Geometry;
use geoarrow::array::GeoArrowArrayAccessor;
use geoarrow::array::PolygonArray;
use geoarrow::datatypes::CoordType;
use geoarrow::datatypes::PolygonType;
use vortex_array::ArrayRef;
use vortex_array::ExecutionCtx;
use vortex_array::IntoArray;
use vortex_array::arrays::ExtensionArray;
use vortex_array::arrays::ListArray;
use vortex_array::arrays::PrimitiveArray;
use vortex_array::arrays::StructArray;
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::memory::BufferAllocatorRef;
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::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 polygon: `geoarrow.polygon`, stored as `List<List<Struct<x, y[, z][, m]>>>` (rings of vertices).
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct Polygon;

impl ExtVTable for Polygon {
    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.polygon");
        *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(polygon_dimension(storage_dtype)?),
        ))
    }

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

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

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

/// Canonical polygon storage: an outer list of rings, each a list of the coordinate `Struct`.
pub(crate) fn polygon_storage_dtype(dim: Dimension, nullability: Nullability) -> DType {
    let coords = coordinate_storage_dtype(dim, Nullability::NonNullable);
    let ring = DType::List(Arc::new(coords), Nullability::NonNullable);
    DType::List(Arc::new(ring), nullability)
}

/// Infers the coordinate [`Dimension`] of `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 polygon_dimension(dtype: &DType) -> VortexResult<Dimension> {
    let DType::List(ring, _) = dtype else {
        vortex_bail!("polygon storage must be a List of rings, got {dtype}");
    };
    let DType::List(coords, _) = ring.as_ref() else {
        vortex_bail!("polygon ring storage must be a List of coordinates, got {ring}");
    };
    coordinate_dimension(coords)
}

static ARROW_POLYGON: CachedId = CachedId::new(PolygonType::NAME);

/// The `geoarrow.polygon` extension type for `dimension`, with separated (struct) coordinates
/// matching `Polygon` storage.
fn polygon_type(spatial_metadata: &SpatialMetadata, dimension: Dimension) -> PolygonType {
    PolygonType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
}

/// Build canonical non-nullable 2-D polygon storage from row-oriented `geo_types` polygons.
pub(crate) fn build_polygon_storage(
    polygons: &[geo_types::Polygon<f64>],
    allocator: &BufferAllocatorRef,
) -> VortexResult<ArrayRef> {
    let mut xs = allocator.with_capacity::<f64>(0);
    let mut ys = allocator.with_capacity::<f64>(0);
    let mut ring_offsets = allocator.with_capacity::<u64>(1);
    ring_offsets.push(0);
    let mut polygon_offsets = allocator.with_capacity::<u64>(polygons.len() + 1);
    polygon_offsets.push(0);

    for polygon in polygons {
        let exterior = (!polygon.exterior().is_empty()).then_some(polygon.exterior());
        for ring in exterior.into_iter().chain(polygon.interiors()) {
            xs.extend(ring.0.iter().map(|coord| coord.x));
            ys.extend(ring.0.iter().map(|coord| coord.y));
            ring_offsets.push(
                u64::try_from(xs.len())
                    .map_err(|_| vortex_err!("spatial: polygon coordinate count exceeds u64"))?,
            );
        }
        polygon_offsets.push(
            u64::try_from(ring_offsets.len() - 1)
                .map_err(|_| vortex_err!("spatial: polygon ring count exceeds u64"))?,
        );
    }

    let coordinates = StructArray::from_fields(&[
        (
            "x",
            PrimitiveArray::new(xs.freeze(), Validity::NonNullable).into_array(),
        ),
        (
            "y",
            PrimitiveArray::new(ys.freeze(), Validity::NonNullable).into_array(),
        ),
    ])?
    .into_array();
    // SAFETY: the offsets start at zero and are pushed as the running coordinate and ring counts,
    // so they are sorted and end at the length of their elements.
    let rings = unsafe {
        ListArray::new_unchecked(
            coordinates,
            PrimitiveArray::new(ring_offsets.freeze(), Validity::NonNullable).into_array(),
            Validity::NonNullable,
        )
    }
    .into_array();
    // SAFETY: as above, for the polygon offsets into the rings.
    let storage = unsafe {
        ListArray::new_unchecked(
            rings,
            PrimitiveArray::new(polygon_offsets.freeze(), Validity::NonNullable).into_array(),
            Validity::NonNullable,
        )
    }
    .into_array();
    Ok(storage)
}

/// Decode `Polygon` storage (`List<List<coordinate>>`) to `geo_types` polygons, for the spatial scalar
/// functions. CRS does not affect planar geometry ops, so default metadata is used.
pub(crate) fn polygon_geometries(
    storage: &ArrayRef,
    ctx: &mut ExecutionCtx,
) -> VortexResult<Vec<Geometry<f64>>> {
    polygon_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 `PolygonArray` from a `Polygon`'s `List<List<coordinate>>` storage.
fn polygon_array(storage: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<PolygonArray> {
    let polygon_type = polygon_type(
        &SpatialMetadata::default(),
        polygon_dimension(storage.dtype())?,
    );
    let arrow = storage.clone().execute_arrow(None, ctx)?;
    PolygonArray::try_from((arrow.as_ref(), polygon_type))
        .map_err(|e| vortex_err!("failed to construct PolygonArray: {e}"))
}

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

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

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

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

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

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

    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 = polygon_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(polygon_meta) = target.try_extension_type::<PolygonType>() else {
            return Ok(ArrowExport::Unsupported(array));
        };
        if polygon_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 polygon_meta = field.try_extension_type::<PolygonType>()?;
        vortex_ensure!(
            polygon_meta.coord_type() == CoordType::Separated,
            "geoarrow.polygon with interleaved coordinates is not supported; \
             re-encode with separated (struct) coordinates"
        );

        let metadata = spatial_metadata_from_arrow(polygon_meta.metadata())
            .with_dimension(polygon_meta.dimension().into());
        Ok(Some(ExtDType::try_with_vtable(
            Polygon,
            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::Polygon;
    use super::polygon_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()))
    }

    /// `Polygon` reads the canonical `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 polygon_reads_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
        let storage = polygon_storage_dtype(dim, Nullability::NonNullable);
        Polygon.deserialize(&spatial_meta().serialize(), storage)?;
        Ok(())
    }

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

        // A single list of coordinates is a LineString, not a Polygon.
        let coords = coordinate_storage_dtype(Dimension::Xy, Nullability::NonNullable);
        let line = DType::List(Arc::new(coords), Nullability::NonNullable);
        assert!(
            Polygon
                .deserialize(&spatial_meta().serialize(), line)
                .is_err()
        );
        Ok(())
    }
}