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