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