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//! The [`Polygon`] geometry extension type (`vortex.st.polygon`): rings of the
5//! [`Point`](super::Point) coordinate struct, stored as `List<List<Struct<x, y[, z][, m]>>>` and tagged with
6//! [`SpatialMetadata`] (CRS). The first ring is the exterior boundary; the rest are holes.
7
8use std::sync::Arc;
9
10use arrow_array::ArrayRef as ArrowArrayRef;
11use arrow_schema::DataType;
12use arrow_schema::Field;
13use arrow_schema::extension::ExtensionType;
14use geo::HasDimensions;
15use geo_traits::to_geo::ToGeoGeometry;
16use geo_types::Geometry;
17use geoarrow::array::GeoArrowArrayAccessor;
18use geoarrow::array::IntoArrow;
19use geoarrow::array::PolygonArray;
20use geoarrow::datatypes::CoordType;
21use geoarrow::datatypes::PolygonType;
22use prost::Message;
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::ArrowExportVTable;
42use vortex_arrow::ArrowImport;
43use vortex_arrow::ArrowImportVTable;
44use vortex_arrow::ArrowSession;
45use vortex_arrow::ArrowSessionExt;
46use vortex_error::VortexError;
47use vortex_error::VortexResult;
48use vortex_error::vortex_bail;
49use vortex_error::vortex_ensure;
50use vortex_error::vortex_ensure_eq;
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    // No cheap owned value like Point's `Coordinate`; expose the raw storage scalar.
70    type NativeValue<'a> = &'a ScalarValue;
71
72    fn id(&self) -> ExtId {
73        static ID: CachedId = CachedId::new("vortex.st.polygon");
74        *ID
75    }
76
77    fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
78        Ok(metadata.encode_to_vec())
79    }
80
81    fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult<Self::Metadata> {
82        Ok(SpatialMetadata::decode(metadata)?)
83    }
84
85    fn validate_dtype(ext_dtype: &ExtDType<Self>) -> VortexResult<()> {
86        polygon_dimension(ext_dtype.storage_dtype()).map(|_| ())
87    }
88
89    fn unpack_native<'a>(
90        _ext_dtype: &'a ExtDType<Self>,
91        storage_value: &'a ScalarValue,
92    ) -> VortexResult<&'a ScalarValue> {
93        Ok(storage_value)
94    }
95}
96
97/// Canonical polygon storage: an outer list of rings, each a list of the coordinate `Struct`.
98pub(crate) fn polygon_storage_dtype(dim: Dimension, nullability: Nullability) -> DType {
99    let coords = coordinate_storage_dtype(dim, Nullability::NonNullable);
100    let ring = DType::List(Arc::new(coords), Nullability::NonNullable);
101    DType::List(Arc::new(ring), nullability)
102}
103
104/// Validate that `dtype` equals [`polygon_storage_dtype`] for its [`Dimension`] and top-level
105/// nullability, and return that dimension. As in GeoArrow, only the outer `List` can be nullable.
106pub(crate) fn polygon_dimension(dtype: &DType) -> VortexResult<Dimension> {
107    let DType::List(ring, _) = dtype else {
108        vortex_bail!("polygon storage must be a List of rings, was {dtype}");
109    };
110    let DType::List(coords, _) = ring.as_ref() else {
111        vortex_bail!("polygon ring storage must be a List of coordinates, was {ring}");
112    };
113    let dimension = coordinate_dimension(coords)?;
114
115    vortex_ensure_eq!(
116        *dtype,
117        polygon_storage_dtype(dimension, dtype.nullability()),
118        "polygon storage can be nullable only at its outer List"
119    );
120
121    Ok(dimension)
122}
123
124static ARROW_POLYGON: CachedId = CachedId::new(PolygonType::NAME);
125
126/// The `geoarrow.polygon` extension type for `dimension`, with separated (struct) coordinates
127/// matching `Polygon` storage.
128fn polygon_type(spatial_metadata: &SpatialMetadata, dimension: Dimension) -> PolygonType {
129    PolygonType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
130}
131
132/// Build canonical non-nullable 2-D polygon storage from row-oriented `geo_types` polygons.
133pub(crate) fn build_polygon_storage(
134    polygons: &[geo_types::Polygon<f64>],
135    allocator: &BufferAllocatorRef,
136) -> VortexResult<ArrayRef> {
137    let mut xs = allocator.with_capacity::<f64>(0);
138    let mut ys = allocator.with_capacity::<f64>(0);
139    let mut ring_offsets = allocator.with_capacity::<u64>(1);
140    ring_offsets.push(0);
141    let mut polygon_offsets = allocator.with_capacity::<u64>(polygons.len() + 1);
142    polygon_offsets.push(0);
143
144    for polygon in polygons {
145        let exterior = (!polygon.exterior().is_empty()).then_some(polygon.exterior());
146        for ring in exterior.into_iter().chain(polygon.interiors()) {
147            xs.extend(ring.0.iter().map(|coord| coord.x));
148            ys.extend(ring.0.iter().map(|coord| coord.y));
149            ring_offsets.push(
150                u64::try_from(xs.len())
151                    .map_err(|_| vortex_err!("spatial: polygon coordinate count exceeds u64"))?,
152            );
153        }
154        polygon_offsets.push(
155            u64::try_from(ring_offsets.len() - 1)
156                .map_err(|_| vortex_err!("spatial: polygon ring count exceeds u64"))?,
157        );
158    }
159
160    let coordinates = StructArray::from_fields(&[
161        (
162            "x",
163            PrimitiveArray::new(xs.freeze(), Validity::NonNullable).into_array(),
164        ),
165        (
166            "y",
167            PrimitiveArray::new(ys.freeze(), Validity::NonNullable).into_array(),
168        ),
169    ])?
170    .into_array();
171    // SAFETY: the offsets start at zero and are pushed as the running coordinate and ring counts,
172    // so they are sorted and end at the length of their elements.
173    let rings = unsafe {
174        ListArray::new_unchecked(
175            coordinates,
176            PrimitiveArray::new(ring_offsets.freeze(), Validity::NonNullable).into_array(),
177            Validity::NonNullable,
178        )
179    }
180    .into_array();
181    // SAFETY: as above, for the polygon offsets into the rings.
182    let storage = unsafe {
183        ListArray::new_unchecked(
184            rings,
185            PrimitiveArray::new(polygon_offsets.freeze(), Validity::NonNullable).into_array(),
186            Validity::NonNullable,
187        )
188    }
189    .into_array();
190    Ok(storage)
191}
192
193/// Decode `Polygon` storage (`List<List<coordinate>>`) to `geo_types` polygons, for the spatial scalar
194/// functions. CRS does not affect planar geometry ops, so default metadata is used.
195pub(crate) fn polygon_geometries(
196    storage: &ArrayRef,
197    ctx: &mut ExecutionCtx,
198) -> VortexResult<Vec<Geometry<f64>>> {
199    polygon_array(storage, ctx)?
200        .iter()
201        .map(|geometry| -> VortexResult<Geometry<f64>> {
202            Ok(geometry
203                .ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
204                .map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
205                .to_geometry())
206        })
207        .collect()
208}
209
210/// Build a geoarrow `PolygonArray` from a `Polygon`'s `List<List<coordinate>>` storage.
211fn polygon_array(storage: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<PolygonArray> {
212    let polygon_type = polygon_type(
213        &SpatialMetadata::default(),
214        polygon_dimension(storage.dtype())?,
215    );
216    let session = ctx.session().clone();
217    let arrow = session.arrow().execute_arrow(storage.clone(), None, ctx)?;
218    PolygonArray::try_from((arrow.as_ref(), polygon_type))
219        .map_err(|e| vortex_err!("failed to construct PolygonArray: {e}"))
220}
221
222/// A validated `Polygon` array (`try_from` checks the extension type).
223pub struct PolygonData(ExtensionArray);
224
225impl TryFrom<ExtensionArray> for PolygonData {
226    type Error = VortexError;
227
228    fn try_from(ext: ExtensionArray) -> Result<Self, Self::Error> {
229        vortex_ensure!(
230            ext.ext_dtype().is::<Polygon>(),
231            "expected a Polygon extension array"
232        );
233        Ok(PolygonData(ext))
234    }
235}
236
237impl PolygonData {
238    /// Serialize polygons to WKB (a view array) — the form DuckDB `GEOMETRY` takes.
239    pub fn to_wkb(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
240        geoarrow_to_wkb(
241            &polygon_array(self.0.storage_array(), ctx)?,
242            &ctx.session().arrow(),
243        )
244    }
245}
246
247impl ArrowExportVTable for Polygon {
248    fn arrow_ext_id(&self) -> Id {
249        *ARROW_POLYGON
250    }
251
252    fn vortex_id(&self) -> Id {
253        self.id()
254    }
255
256    fn to_arrow_field(
257        &self,
258        name: &str,
259        dtype: &DType,
260        session: &ArrowSession,
261    ) -> VortexResult<Option<Field>> {
262        let ext_type = dtype.as_extension();
263        let spatial_metadata = ext_type.metadata::<Polygon>();
264        let dimension = polygon_dimension(ext_type.storage_dtype())?;
265
266        let mut field = session.to_arrow_field(name, ext_type.storage_dtype())?;
267        field.try_with_extension_type(polygon_type(spatial_metadata, dimension))?;
268
269        Ok(Some(field))
270    }
271
272    fn execute_arrow(
273        &self,
274        array: ArrayRef,
275        target: &Field,
276        options: &ArrowExportOptions,
277        ctx: &mut ExecutionCtx,
278    ) -> VortexResult<ArrowExport> {
279        let is_polygon = array
280            .dtype()
281            .as_extension_opt()
282            .map(|ext| ext.is::<Polygon>())
283            .unwrap_or(false);
284        if !is_polygon {
285            return Ok(ArrowExport::Unsupported(array));
286        }
287
288        let Ok(polygon_meta) = target.try_extension_type::<PolygonType>() else {
289            return Ok(ArrowExport::Unsupported(array));
290        };
291        if polygon_meta.coord_type() != CoordType::Separated {
292            return Ok(ArrowExport::Unsupported(array));
293        }
294
295        let executed = array.execute::<ExtensionArray>(ctx)?;
296        let storage = executed.storage_array().clone();
297
298        let storage_field = Field::new(
299            String::new(),
300            target.data_type().clone(),
301            target.is_nullable(),
302        );
303        let session = ctx.session().clone();
304        let arrow_storage =
305            session
306                .arrow()
307                .exporter(options)
308                .execute_arrow(storage, Some(&storage_field), ctx)?;
309
310        // Round-trip through GeoArrow's polygon array; `into_arrow` is concrete, so wrap in `Arc`.
311        let polygons = PolygonArray::try_from((arrow_storage.as_ref(), polygon_meta))
312            .map_err(|e| vortex_err!("failed to construct PolygonArray: {e}"))?;
313
314        Ok(ArrowExport::Exported(Arc::new(polygons.into_arrow())))
315    }
316}
317
318impl ArrowImportVTable for Polygon {
319    fn arrow_ext_id(&self) -> Id {
320        *ARROW_POLYGON
321    }
322
323    /// Import a `geoarrow.polygon` field as the [`Polygon`] dtype. Keyed off the standard GeoArrow
324    /// name, so any producer (DataFusion, DuckDB, geoarrow-rs, …) resolves here. Accepts the full
325    /// `PolygonType` extension, or — for a metadata-less geometry literal — the name alone, inferring
326    /// the dimension from the coordinate field names.
327    fn from_arrow_field(
328        &self,
329        field: &Field,
330        session: &ArrowSession,
331    ) -> VortexResult<Option<DType>> {
332        let (dimension, metadata) =
333            if let Ok(polygon_meta) = field.try_extension_type::<PolygonType>() {
334                vortex_ensure!(
335                    polygon_meta.coord_type() == CoordType::Separated,
336                    "geoarrow.polygon with interleaved coordinates is not supported; \
337             re-encode with separated (struct) coordinates"
338                );
339                (
340                    polygon_meta.dimension().into(),
341                    spatial_metadata_from_arrow(polygon_meta.metadata()),
342                )
343            } else {
344                // Infer the dimension from the field names, not the canonical storage check: a literal's
345                // coordinate fields may be nullable, which that check rejects. Peel the two `List` layers
346                // (polygon → rings → coordinates) to reach the struct.
347                if field.extension_type_name() != Some(PolygonType::NAME) {
348                    return Ok(None);
349                }
350                let Ok(DType::List(ring, _)) =
351                    session.from_arrow_datatype(field.data_type(), field.is_nullable().into())
352                else {
353                    return Ok(None);
354                };
355                let DType::List(coords, _) = ring.as_ref() else {
356                    return Ok(None);
357                };
358                let DType::Struct(fields, _) = coords.as_ref() else {
359                    return Ok(None);
360                };
361                let Ok(dimension) = Dimension::from_field_names(fields.names()) else {
362                    return Ok(None);
363                };
364                (dimension, SpatialMetadata::default())
365            };
366
367        let storage_dtype = polygon_storage_dtype(dimension, field.is_nullable().into());
368        Ok(Some(DType::Extension(
369            ExtDType::try_with_vtable(Polygon, metadata, storage_dtype)?.erased(),
370        )))
371    }
372
373    fn from_arrow_array(
374        &self,
375        array: ArrowArrayRef,
376        field: &Field,
377        dtype: &DType,
378        session: &ArrowSession,
379    ) -> VortexResult<ArrowImport> {
380        let Some(ext_dtype) = dtype.as_extension_opt() else {
381            return Ok(ArrowImport::Unsupported(array));
382        };
383        if !ext_dtype.is::<Polygon>()
384            || field.try_extension_type::<PolygonType>().is_err()
385            || !matches!(array.data_type(), DataType::List(_))
386        {
387            return Ok(ArrowImport::Unsupported(array));
388        }
389
390        let storage = session.from_arrow_array(array, field.is_nullable())?;
391        Ok(ArrowImport::Imported(
392            ExtensionArray::try_new(ext_dtype.clone(), storage)?.into_array(),
393        ))
394    }
395}
396
397#[cfg(test)]
398mod tests {
399    use std::sync::Arc;
400
401    use rstest::rstest;
402    use vortex_array::dtype::DType;
403    use vortex_array::dtype::Nullability;
404    use vortex_array::dtype::PType;
405    use vortex_array::dtype::extension::ExtDType;
406    use vortex_error::VortexResult;
407
408    use super::Polygon;
409    use super::polygon_storage_dtype;
410    use crate::extension::SpatialMetadata;
411    use crate::extension::coordinate::Dimension;
412    use crate::extension::coordinate::coordinate_storage_dtype;
413
414    fn spatial_meta() -> SpatialMetadata {
415        SpatialMetadata {
416            crs: Some("EPSG:4326".to_string()),
417        }
418    }
419
420    /// `Polygon` accepts the canonical `List<List<coordinate-struct>>` storage of every dimension.
421    #[rstest]
422    #[case::xy(Dimension::Xy)]
423    #[case::xyz(Dimension::Xyz)]
424    #[case::xym(Dimension::Xym)]
425    #[case::xyzm(Dimension::Xyzm)]
426    fn polygon_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
427        let storage = polygon_storage_dtype(dim, Nullability::NonNullable);
428        ExtDType::<Polygon>::try_new(spatial_meta(), storage)?;
429        Ok(())
430    }
431
432    /// Non-polygon storage is rejected at dtype construction: a bare struct (point) and a single
433    /// list (linestring) both fail.
434    #[test]
435    fn polygon_rejects_invalid_storage() -> VortexResult<()> {
436        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
437        assert!(ExtDType::<Polygon>::try_new(spatial_meta(), primitive).is_err());
438
439        // A single list of coordinates is a LineString, not a Polygon.
440        let coords = coordinate_storage_dtype(Dimension::Xy, Nullability::NonNullable);
441        let line = DType::List(Arc::new(coords), Nullability::NonNullable);
442        assert!(ExtDType::<Polygon>::try_new(spatial_meta(), line).is_err());
443        Ok(())
444    }
445}