Skip to main content

vortex_spatial/extension/
polygon.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Native polygon geometry (`vortex.st.polygon`).
5//!
6//! [`Polygon`] stores rings as `List<List<Struct<x, y[, z][, m]>>>`. The first ring is the exterior
7//! boundary and the remaining rings are holes. [`SpatialMetadata`] declares the coordinate
8//! dimension and optional coordinate reference system. Coordinates use non-nullable `f64` fields.
9//! Only the outer list can be nullable.
10
11use std::sync::Arc;
12
13use arrow_array::ArrayRef as ArrowArrayRef;
14use arrow_schema::Field;
15use arrow_schema::extension::ExtensionType;
16use geo::HasDimensions;
17use geo_traits::to_geo::ToGeoGeometry;
18use geo_types::Geometry;
19use geoarrow::array::GeoArrowArrayAccessor;
20use geoarrow::array::PolygonArray;
21use geoarrow::datatypes::CoordType;
22use geoarrow::datatypes::PolygonType;
23use vortex_array::ArrayRef;
24use vortex_array::ExecutionCtx;
25use vortex_array::IntoArray;
26use vortex_array::arrays::ExtensionArray;
27use vortex_array::arrays::ListArray;
28use vortex_array::arrays::PrimitiveArray;
29use vortex_array::arrays::StructArray;
30use vortex_array::arrays::extension::ExtensionArrayExt;
31use vortex_array::dtype::DType;
32use vortex_array::dtype::Nullability;
33use vortex_array::dtype::extension::ExtDType;
34use vortex_array::dtype::extension::ExtId;
35use vortex_array::dtype::extension::ExtVTable;
36use vortex_array::memory::BufferAllocatorRef;
37use vortex_array::scalar::ScalarValue;
38use vortex_array::validity::Validity;
39use vortex_arrow::ArrowExport;
40use vortex_arrow::ArrowExportOptions;
41use vortex_arrow::ArrowExtVTable;
42use vortex_arrow::ArrowImport;
43use vortex_arrow::ArrowMetadataPolicy;
44use vortex_arrow::ArrowSession;
45use vortex_arrow::ArrowSessionExt;
46use vortex_arrow::ExecuteArrowExt;
47use vortex_error::VortexError;
48use vortex_error::VortexResult;
49use vortex_error::vortex_bail;
50use vortex_error::vortex_ensure;
51use vortex_error::vortex_err;
52use vortex_session::registry::CachedId;
53use vortex_session::registry::Id;
54
55use super::SpatialMetadata;
56use super::coordinate::Dimension;
57use super::coordinate::coordinate_dimension;
58use super::coordinate::coordinate_storage_dtype;
59use super::geoarrow_metadata;
60use super::geoarrow_to_wkb;
61use super::spatial_metadata_from_arrow;
62
63/// A polygon: `geoarrow.polygon`, stored as `List<List<Struct<x, y[, z][, m]>>>` (rings of vertices).
64#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
65pub struct Polygon;
66
67impl ExtVTable for Polygon {
68    type Metadata = SpatialMetadata;
69    type StoredMetadata = super::SpatialStoredMetadata;
70    // No cheap owned value like Point's `Coordinate`; expose the raw storage scalar.
71    type NativeValue<'a> = &'a ScalarValue;
72
73    fn id(&self) -> ExtId {
74        static ID: CachedId = CachedId::new("vortex.st.polygon");
75        *ID
76    }
77
78    fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
79        Ok(metadata.serialize())
80    }
81
82    fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult<Self::StoredMetadata> {
83        super::SpatialStoredMetadata::deserialize(metadata)
84    }
85
86    fn metadata_from_storage(
87        &self,
88        stored_metadata: Self::StoredMetadata,
89        storage_dtype: &DType,
90    ) -> VortexResult<Self::Metadata> {
91        Ok(SpatialMetadata::from_stored_metadata(
92            stored_metadata,
93            Some(polygon_dimension(storage_dtype)?),
94        ))
95    }
96
97    fn storage_dtype(metadata: &Self::Metadata) -> DType {
98        polygon_storage_dtype(metadata.native_dimension(), Nullability::NonNullable)
99    }
100
101    fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> {
102        metadata.validate_native(Polygon.id())
103    }
104
105    fn unpack_native<'a>(
106        _ext_dtype: &'a ExtDType<Self>,
107        storage_value: &'a ScalarValue,
108    ) -> VortexResult<&'a ScalarValue> {
109        Ok(storage_value)
110    }
111}
112
113/// Canonical polygon storage: an outer list of rings, each a list of the coordinate `Struct`.
114pub(crate) fn polygon_storage_dtype(dim: Dimension, nullability: Nullability) -> DType {
115    let coords = coordinate_storage_dtype(dim, Nullability::NonNullable);
116    let ring = DType::List(Arc::new(coords), Nullability::NonNullable);
117    DType::List(Arc::new(ring), nullability)
118}
119
120/// Infers the coordinate [`Dimension`] of `List<List<coordinate-struct>>` storage.
121///
122/// Checks the list nesting and delegates coordinate field-name inference to
123/// [`coordinate_dimension`]. Reads validate the complete storage dtype against the declaration.
124pub(crate) fn polygon_dimension(dtype: &DType) -> VortexResult<Dimension> {
125    let DType::List(ring, _) = dtype else {
126        vortex_bail!("polygon storage must be a List of rings, got {dtype}");
127    };
128    let DType::List(coords, _) = ring.as_ref() else {
129        vortex_bail!("polygon ring storage must be a List of coordinates, got {ring}");
130    };
131    coordinate_dimension(coords)
132}
133
134static ARROW_POLYGON: CachedId = CachedId::new(PolygonType::NAME);
135
136/// The `geoarrow.polygon` extension type for `dimension`, with separated (struct) coordinates
137/// matching `Polygon` storage.
138fn polygon_type(spatial_metadata: &SpatialMetadata, dimension: Dimension) -> PolygonType {
139    PolygonType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
140}
141
142/// Build canonical non-nullable 2-D polygon storage from row-oriented `geo_types` polygons.
143pub(crate) fn build_polygon_storage(
144    polygons: &[geo_types::Polygon<f64>],
145    allocator: &BufferAllocatorRef,
146) -> VortexResult<ArrayRef> {
147    let mut xs = allocator.with_capacity::<f64>(0);
148    let mut ys = allocator.with_capacity::<f64>(0);
149    let mut ring_offsets = allocator.with_capacity::<u64>(1);
150    ring_offsets.push(0);
151    let mut polygon_offsets = allocator.with_capacity::<u64>(polygons.len() + 1);
152    polygon_offsets.push(0);
153
154    for polygon in polygons {
155        let exterior = (!polygon.exterior().is_empty()).then_some(polygon.exterior());
156        for ring in exterior.into_iter().chain(polygon.interiors()) {
157            xs.extend(ring.0.iter().map(|coord| coord.x));
158            ys.extend(ring.0.iter().map(|coord| coord.y));
159            ring_offsets.push(
160                u64::try_from(xs.len())
161                    .map_err(|_| vortex_err!("spatial: polygon coordinate count exceeds u64"))?,
162            );
163        }
164        polygon_offsets.push(
165            u64::try_from(ring_offsets.len() - 1)
166                .map_err(|_| vortex_err!("spatial: polygon ring count exceeds u64"))?,
167        );
168    }
169
170    let coordinates = StructArray::from_fields(&[
171        (
172            "x",
173            PrimitiveArray::new(xs.freeze(), Validity::NonNullable).into_array(),
174        ),
175        (
176            "y",
177            PrimitiveArray::new(ys.freeze(), Validity::NonNullable).into_array(),
178        ),
179    ])?
180    .into_array();
181    // SAFETY: the offsets start at zero and are pushed as the running coordinate and ring counts,
182    // so they are sorted and end at the length of their elements.
183    let rings = unsafe {
184        ListArray::new_unchecked(
185            coordinates,
186            PrimitiveArray::new(ring_offsets.freeze(), Validity::NonNullable).into_array(),
187            Validity::NonNullable,
188        )
189    }
190    .into_array();
191    // SAFETY: as above, for the polygon offsets into the rings.
192    let storage = unsafe {
193        ListArray::new_unchecked(
194            rings,
195            PrimitiveArray::new(polygon_offsets.freeze(), Validity::NonNullable).into_array(),
196            Validity::NonNullable,
197        )
198    }
199    .into_array();
200    Ok(storage)
201}
202
203/// Decode `Polygon` storage (`List<List<coordinate>>`) to `geo_types` polygons, for the spatial scalar
204/// functions. CRS does not affect planar geometry ops, so default metadata is used.
205pub(crate) fn polygon_geometries(
206    storage: &ArrayRef,
207    ctx: &mut ExecutionCtx,
208) -> VortexResult<Vec<Geometry<f64>>> {
209    polygon_array(storage, ctx)?
210        .iter()
211        .map(|geometry| -> VortexResult<Geometry<f64>> {
212            Ok(geometry
213                .ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
214                .map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
215                .to_geometry())
216        })
217        .collect()
218}
219
220/// Build a geoarrow `PolygonArray` from a `Polygon`'s `List<List<coordinate>>` storage.
221fn polygon_array(storage: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<PolygonArray> {
222    let polygon_type = polygon_type(
223        &SpatialMetadata::default(),
224        polygon_dimension(storage.dtype())?,
225    );
226    let arrow = storage.clone().execute_arrow(None, ctx)?;
227    PolygonArray::try_from((arrow.as_ref(), polygon_type))
228        .map_err(|e| vortex_err!("failed to construct PolygonArray: {e}"))
229}
230
231/// A validated `Polygon` array (`try_from` checks the extension type).
232pub struct PolygonData(ExtensionArray);
233
234impl TryFrom<ExtensionArray> for PolygonData {
235    type Error = VortexError;
236
237    fn try_from(ext: ExtensionArray) -> Result<Self, Self::Error> {
238        vortex_ensure!(
239            ext.ext_dtype().is::<Polygon>(),
240            "expected a Polygon extension array"
241        );
242        Ok(PolygonData(ext))
243    }
244}
245
246impl PolygonData {
247    /// Serialize polygons to WKB (a view array) — the form DuckDB `GEOMETRY` takes.
248    pub fn to_wkb(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
249        geoarrow_to_wkb(
250            &polygon_array(self.0.storage_array(), ctx)?,
251            &ctx.session().arrow(),
252        )
253    }
254}
255
256impl ArrowExtVTable for Polygon {
257    fn metadata_policy() -> ArrowMetadataPolicy {
258        ArrowMetadataPolicy::ArrowNative
259    }
260
261    fn arrow_ext_id(&self) -> Id {
262        *ARROW_POLYGON
263    }
264
265    fn to_arrow_field(
266        &self,
267        name: &str,
268        ext_dtype: &ExtDType<Self>,
269        _session: &ArrowSession,
270    ) -> VortexResult<Option<Field>> {
271        let spatial_metadata = ext_dtype.metadata();
272        let dimension = spatial_metadata.native_dimension();
273
274        let arrow_type = polygon_type(spatial_metadata, dimension);
275        let mut field = Field::new(
276            name,
277            arrow_type.data_type(),
278            ext_dtype.storage_dtype().is_nullable(),
279        );
280        field.try_with_extension_type(arrow_type)?;
281
282        Ok(Some(field))
283    }
284
285    fn execute_arrow(
286        &self,
287        array: ArrayRef,
288        target: &Field,
289        options: &ArrowExportOptions,
290        ctx: &mut ExecutionCtx,
291    ) -> VortexResult<ArrowExport> {
292        let Ok(polygon_meta) = target.try_extension_type::<PolygonType>() else {
293            return Ok(ArrowExport::Unsupported(array));
294        };
295        if polygon_meta.coord_type() != CoordType::Separated {
296            return Ok(ArrowExport::Unsupported(array));
297        }
298
299        let executed = array.execute::<ExtensionArray>(ctx)?;
300        let storage = executed.storage_array().clone();
301
302        let storage_field = Field::new(
303            String::new(),
304            target.data_type().clone(),
305            target.is_nullable(),
306        );
307        let arrow_storage =
308            storage.execute_arrow_with_options(Some(&storage_field), options, ctx)?;
309
310        // The validated target already shapes the storage. GeoArrow constructors can panic on
311        // valid Arrow lists that retain unused child values after filtering.
312        Ok(ArrowExport::Exported(arrow_storage))
313    }
314
315    fn from_arrow_field(
316        field: &Field,
317        _session: &ArrowSession,
318    ) -> VortexResult<Option<ExtDType<Self>>> {
319        let polygon_meta = field.try_extension_type::<PolygonType>()?;
320        vortex_ensure!(
321            polygon_meta.coord_type() == CoordType::Separated,
322            "geoarrow.polygon with interleaved coordinates is not supported; \
323             re-encode with separated (struct) coordinates"
324        );
325
326        let metadata = spatial_metadata_from_arrow(polygon_meta.metadata())
327            .with_dimension(polygon_meta.dimension().into());
328        Ok(Some(ExtDType::try_with_vtable(
329            Polygon,
330            metadata,
331            field.is_nullable().into(),
332        )?))
333    }
334
335    fn from_arrow_array(
336        array: ArrowArrayRef,
337        _field: &Field,
338        ext_dtype: &ExtDType<Self>,
339        session: &ArrowSession,
340    ) -> VortexResult<ArrowImport> {
341        session
342            .from_arrow_storage(array, &ext_dtype.clone().erased())
343            .map(ArrowImport::Imported)
344    }
345}
346
347#[cfg(test)]
348mod tests {
349    use std::sync::Arc;
350
351    use rstest::rstest;
352    use vortex_array::dtype::DType;
353    use vortex_array::dtype::Nullability;
354    use vortex_array::dtype::PType;
355    use vortex_array::dtype::extension::ExtDTypePlugin;
356    use vortex_error::VortexResult;
357
358    use super::Polygon;
359    use super::polygon_storage_dtype;
360    use crate::extension::SpatialMetadata;
361    use crate::extension::coordinate::Dimension;
362    use crate::extension::coordinate::coordinate_storage_dtype;
363
364    fn spatial_meta() -> SpatialMetadata {
365        SpatialMetadata::new(Some("EPSG:4326".to_string()))
366    }
367
368    /// `Polygon` reads the canonical `List<List<coordinate-struct>>` storage of every dimension.
369    #[rstest]
370    #[case::xy(Dimension::Xy)]
371    #[case::xyz(Dimension::Xyz)]
372    #[case::xym(Dimension::Xym)]
373    #[case::xyzm(Dimension::Xyzm)]
374    fn polygon_reads_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
375        let storage = polygon_storage_dtype(dim, Nullability::NonNullable);
376        Polygon.deserialize(&spatial_meta().serialize(), storage)?;
377        Ok(())
378    }
379
380    /// Non-polygon storage fails to read, for example `f64` or a single list (linestring).
381    #[test]
382    fn polygon_rejects_invalid_storage() -> VortexResult<()> {
383        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
384        assert!(
385            Polygon
386                .deserialize(&spatial_meta().serialize(), primitive)
387                .is_err()
388        );
389
390        // A single list of coordinates is a LineString, not a Polygon.
391        let coords = coordinate_storage_dtype(Dimension::Xy, Nullability::NonNullable);
392        let line = DType::List(Arc::new(coords), Nullability::NonNullable);
393        assert!(
394            Polygon
395                .deserialize(&spatial_meta().serialize(), line)
396                .is_err()
397        );
398        Ok(())
399    }
400}