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