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::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#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
64pub struct Polygon;
65
66impl ExtVTable for Polygon {
67 type Metadata = SpatialMetadata;
68 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
96pub(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
103pub(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
116fn polygon_type(spatial_metadata: &SpatialMetadata, dimension: Dimension) -> PolygonType {
119 PolygonType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
120}
121
122pub(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 let rings = ListArray::try_new(
162 coordinates,
163 PrimitiveArray::new(ring_offsets.freeze(), Validity::NonNullable).into_array(),
164 Validity::NonNullable,
165 )?
166 .into_array();
167 let storage = ListArray::try_new(
168 rings,
169 PrimitiveArray::new(polygon_offsets.freeze(), Validity::NonNullable).into_array(),
170 Validity::NonNullable,
171 )?
172 .into_array();
173 Ok(storage)
174}
175
176pub(crate) fn polygon_geometries(
179 storage: &ArrayRef,
180 ctx: &mut ExecutionCtx,
181) -> VortexResult<Vec<Geometry<f64>>> {
182 polygon_array(storage, ctx)?
183 .iter()
184 .map(|geometry| -> VortexResult<Geometry<f64>> {
185 Ok(geometry
186 .ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
187 .map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
188 .to_geometry())
189 })
190 .collect()
191}
192
193fn polygon_array(storage: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<PolygonArray> {
195 let polygon_type = polygon_type(
196 &SpatialMetadata::default(),
197 polygon_dimension(storage.dtype())?,
198 );
199 let session = ctx.session().clone();
200 let arrow = session.arrow().execute_arrow(storage.clone(), None, ctx)?;
201 PolygonArray::try_from((arrow.as_ref(), polygon_type))
202 .map_err(|e| vortex_err!("failed to construct PolygonArray: {e}"))
203}
204
205pub struct PolygonData(ExtensionArray);
207
208impl TryFrom<ExtensionArray> for PolygonData {
209 type Error = VortexError;
210
211 fn try_from(ext: ExtensionArray) -> Result<Self, Self::Error> {
212 vortex_ensure!(
213 ext.ext_dtype().is::<Polygon>(),
214 "expected a Polygon extension array"
215 );
216 Ok(PolygonData(ext))
217 }
218}
219
220impl PolygonData {
221 pub fn to_wkb(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
223 geoarrow_to_wkb(
224 &polygon_array(self.0.storage_array(), ctx)?,
225 &ctx.session().arrow(),
226 )
227 }
228}
229
230impl ArrowExportVTable for Polygon {
231 fn arrow_ext_id(&self) -> Id {
232 *ARROW_POLYGON
233 }
234
235 fn vortex_id(&self) -> Id {
236 self.id()
237 }
238
239 fn to_arrow_field(
240 &self,
241 name: &str,
242 dtype: &DType,
243 session: &ArrowSession,
244 ) -> VortexResult<Option<Field>> {
245 let ext_type = dtype.as_extension();
246 let spatial_metadata = ext_type.metadata::<Polygon>();
247 let dimension = polygon_dimension(ext_type.storage_dtype())?;
248
249 let mut field = session.to_arrow_field(name, ext_type.storage_dtype())?;
250 field.try_with_extension_type(polygon_type(spatial_metadata, dimension))?;
251
252 Ok(Some(field))
253 }
254
255 fn execute_arrow(
256 &self,
257 array: ArrayRef,
258 target: &Field,
259 options: &ArrowExportOptions,
260 ctx: &mut ExecutionCtx,
261 ) -> VortexResult<ArrowExport> {
262 let is_polygon = array
263 .dtype()
264 .as_extension_opt()
265 .map(|ext| ext.is::<Polygon>())
266 .unwrap_or(false);
267 if !is_polygon {
268 return Ok(ArrowExport::Unsupported(array));
269 }
270
271 let Ok(polygon_meta) = target.try_extension_type::<PolygonType>() else {
272 return Ok(ArrowExport::Unsupported(array));
273 };
274 if polygon_meta.coord_type() != CoordType::Separated {
275 return Ok(ArrowExport::Unsupported(array));
276 }
277
278 let executed = array.execute::<ExtensionArray>(ctx)?;
279 let storage = executed.storage_array().clone();
280
281 let storage_field = Field::new(
282 String::new(),
283 target.data_type().clone(),
284 target.is_nullable(),
285 );
286 let session = ctx.session().clone();
287 let arrow_storage =
288 session
289 .arrow()
290 .exporter(options)
291 .execute_arrow(storage, Some(&storage_field), ctx)?;
292
293 let polygons = PolygonArray::try_from((arrow_storage.as_ref(), polygon_meta))
295 .map_err(|e| vortex_err!("failed to construct PolygonArray: {e}"))?;
296
297 Ok(ArrowExport::Exported(Arc::new(polygons.into_arrow())))
298 }
299}
300
301impl ArrowImportVTable for Polygon {
302 fn arrow_ext_id(&self) -> Id {
303 *ARROW_POLYGON
304 }
305
306 fn from_arrow_field(
311 &self,
312 field: &Field,
313 session: &ArrowSession,
314 ) -> VortexResult<Option<DType>> {
315 let (dimension, metadata) =
316 if let Ok(polygon_meta) = field.try_extension_type::<PolygonType>() {
317 vortex_ensure!(
318 polygon_meta.coord_type() == CoordType::Separated,
319 "geoarrow.polygon with interleaved coordinates is not supported; \
320 re-encode with separated (struct) coordinates"
321 );
322 (
323 polygon_meta.dimension().into(),
324 spatial_metadata_from_arrow(polygon_meta.metadata()),
325 )
326 } else {
327 if field.extension_type_name() != Some(PolygonType::NAME) {
331 return Ok(None);
332 }
333 let Ok(DType::List(ring, _)) =
334 session.from_arrow_datatype(field.data_type(), field.is_nullable().into())
335 else {
336 return Ok(None);
337 };
338 let DType::List(coords, _) = ring.as_ref() else {
339 return Ok(None);
340 };
341 let DType::Struct(fields, _) = coords.as_ref() else {
342 return Ok(None);
343 };
344 let Ok(dimension) = Dimension::from_field_names(fields.names()) else {
345 return Ok(None);
346 };
347 (dimension, SpatialMetadata::default())
348 };
349
350 let storage_dtype = polygon_storage_dtype(dimension, field.is_nullable().into());
351 Ok(Some(DType::Extension(
352 ExtDType::try_with_vtable(Polygon, metadata, storage_dtype)?.erased(),
353 )))
354 }
355
356 fn from_arrow_array(
357 &self,
358 array: ArrowArrayRef,
359 field: &Field,
360 dtype: &DType,
361 session: &ArrowSession,
362 ) -> VortexResult<ArrowImport> {
363 let Some(ext_dtype) = dtype.as_extension_opt() else {
364 return Ok(ArrowImport::Unsupported(array));
365 };
366 if !ext_dtype.is::<Polygon>()
367 || field.try_extension_type::<PolygonType>().is_err()
368 || !matches!(array.data_type(), DataType::List(_))
369 {
370 return Ok(ArrowImport::Unsupported(array));
371 }
372
373 let storage = session.from_arrow_array(array, field.is_nullable())?;
374 Ok(ArrowImport::Imported(
375 ExtensionArray::try_new(ext_dtype.clone(), storage)?.into_array(),
376 ))
377 }
378}
379
380#[cfg(test)]
381mod tests {
382 use std::sync::Arc;
383
384 use rstest::rstest;
385 use vortex_array::dtype::DType;
386 use vortex_array::dtype::Nullability;
387 use vortex_array::dtype::PType;
388 use vortex_array::dtype::extension::ExtDType;
389 use vortex_error::VortexResult;
390
391 use super::Polygon;
392 use super::polygon_storage_dtype;
393 use crate::extension::SpatialMetadata;
394 use crate::extension::coordinate::Dimension;
395 use crate::extension::coordinate::coordinate_storage_dtype;
396
397 fn spatial_meta() -> SpatialMetadata {
398 SpatialMetadata {
399 crs: Some("EPSG:4326".to_string()),
400 }
401 }
402
403 #[rstest]
405 #[case::xy(Dimension::Xy)]
406 #[case::xyz(Dimension::Xyz)]
407 #[case::xym(Dimension::Xym)]
408 #[case::xyzm(Dimension::Xyzm)]
409 fn polygon_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
410 let storage = polygon_storage_dtype(dim, Nullability::NonNullable);
411 ExtDType::<Polygon>::try_new(spatial_meta(), storage)?;
412 Ok(())
413 }
414
415 #[test]
418 fn polygon_rejects_invalid_storage() -> VortexResult<()> {
419 let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
420 assert!(ExtDType::<Polygon>::try_new(spatial_meta(), primitive).is_err());
421
422 let coords = coordinate_storage_dtype(Dimension::Xy, Nullability::NonNullable);
424 let line = DType::List(Arc::new(coords), Nullability::NonNullable);
425 assert!(ExtDType::<Polygon>::try_new(spatial_meta(), line).is_err());
426 Ok(())
427 }
428}