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