vortex_spatial/extension/
rect.rs1use std::sync::Arc;
13
14use arrow_array::ArrayRef as ArrowArrayRef;
15use arrow_schema::DataType;
16use arrow_schema::Field;
17use arrow_schema::extension::ExtensionType;
18use geo_traits::to_geo::ToGeoGeometry;
19use geo_types::Geometry;
20use geoarrow::array::GeoArrowArrayAccessor;
21use geoarrow::array::IntoArrow;
22use geoarrow::array::RectArray;
23use geoarrow::datatypes::BoxType;
24use prost::Message;
25use vortex_array::ArrayRef;
26use vortex_array::ExecutionCtx;
27use vortex_array::IntoArray;
28use vortex_array::arrays::ExtensionArray;
29use vortex_array::arrays::StructArray;
30use vortex_array::arrays::extension::ExtensionArrayExt;
31use vortex_array::dtype::DType;
32use vortex_array::dtype::FieldNames;
33use vortex_array::dtype::Nullability;
34use vortex_array::dtype::PType;
35use vortex_array::dtype::StructFields;
36use vortex_array::dtype::extension::ExtDType;
37use vortex_array::dtype::extension::ExtId;
38use vortex_array::dtype::extension::ExtVTable;
39use vortex_array::scalar::ScalarValue;
40use vortex_array::validity::Validity;
41use vortex_arrow::ArrowExport;
42use vortex_arrow::ArrowExportOptions;
43use vortex_arrow::ArrowExportVTable;
44use vortex_arrow::ArrowImport;
45use vortex_arrow::ArrowImportVTable;
46use vortex_arrow::ArrowSession;
47use vortex_arrow::ArrowSessionExt;
48use vortex_error::VortexResult;
49use vortex_error::vortex_bail;
50use vortex_error::vortex_ensure;
51use vortex_error::vortex_err;
52use vortex_session::registry::CachedId;
53use vortex_session::registry::Id;
54
55use super::SpatialMetadata;
56use super::coordinate::Dimension;
57use super::geoarrow_metadata;
58use super::spatial_metadata_from_arrow;
59
60#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
63pub struct Rect;
64
65impl ExtVTable for Rect {
66 type Metadata = SpatialMetadata;
67 type NativeValue<'a> = &'a ScalarValue;
69
70 fn id(&self) -> ExtId {
71 static ID: CachedId = CachedId::new("vortex.st.box");
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 box_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
95pub(crate) fn box_field_names(dim: Dimension) -> &'static [&'static str] {
98 match dim {
99 Dimension::Xy => &["xmin", "ymin", "xmax", "ymax"],
100 Dimension::Xyz => &["xmin", "ymin", "zmin", "xmax", "ymax", "zmax"],
101 Dimension::Xym => &["xmin", "ymin", "mmin", "xmax", "ymax", "mmax"],
102 Dimension::Xyzm => &[
103 "xmin", "ymin", "zmin", "mmin", "xmax", "ymax", "zmax", "mmax",
104 ],
105 }
106}
107
108fn box_dimension_from_names(names: &FieldNames) -> Option<Dimension> {
110 [
111 Dimension::Xy,
112 Dimension::Xyz,
113 Dimension::Xym,
114 Dimension::Xyzm,
115 ]
116 .into_iter()
117 .find(|&dim| {
118 names
119 .iter()
120 .map(AsRef::as_ref)
121 .eq(box_field_names(dim).iter().copied())
122 })
123}
124
125pub(crate) fn box_storage_dtype(dim: Dimension, nullability: Nullability) -> DType {
128 let names = box_field_names(dim);
129 let fields = std::iter::repeat_n(
130 DType::Primitive(PType::F64, Nullability::NonNullable),
131 names.len(),
132 )
133 .collect::<Vec<_>>();
134 DType::Struct(
135 StructFields::new(FieldNames::from(names), fields),
136 nullability,
137 )
138}
139
140pub(crate) fn box_dimension(dtype: &DType) -> VortexResult<Dimension> {
143 let DType::Struct(fields, _) = dtype else {
144 vortex_bail!("box storage must be a Struct, was {dtype}");
145 };
146 for (name, field) in fields.names().iter().zip(fields.fields()) {
147 vortex_ensure!(
148 matches!(
149 field,
150 DType::Primitive(PType::F64, Nullability::NonNullable)
151 ),
152 "box field {name} must be non-nullable f64, was {field}"
153 );
154 }
155 box_dimension_from_names(fields.names())
156 .ok_or_else(|| vortex_err!("not a valid geoarrow.box dimension: {:?}", fields.names()))
157}
158
159pub(crate) fn build_rect_array(
161 ext_dtype: &ExtDType<Rect>,
162 corners: Vec<ArrayRef>,
163 len: usize,
164 validity: Validity,
165) -> VortexResult<ArrayRef> {
166 let dimension = box_dimension(ext_dtype.storage_dtype())?;
167 let storage = StructArray::try_new(
168 FieldNames::from(box_field_names(dimension)),
169 corners,
170 len,
171 validity,
172 )?
173 .into_array();
174 Ok(ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array())
175}
176
177static ARROW_BOX: CachedId = CachedId::new(BoxType::NAME);
178
179fn box_type(spatial_metadata: &SpatialMetadata, dimension: Dimension) -> BoxType {
181 BoxType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
182}
183
184fn rect_array(storage: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<RectArray> {
186 let box_type = box_type(&SpatialMetadata::default(), box_dimension(storage.dtype())?);
187 let session = ctx.session().clone();
188 let arrow = session.arrow().execute_arrow(storage.clone(), None, ctx)?;
189 RectArray::try_from((arrow.as_ref(), box_type))
190 .map_err(|e| vortex_err!("failed to construct RectArray: {e}"))
191}
192
193pub(crate) fn rect_geometries(
195 storage: &ArrayRef,
196 ctx: &mut ExecutionCtx,
197) -> VortexResult<Vec<Geometry<f64>>> {
198 rect_array(storage, ctx)?
199 .iter()
200 .map(|geometry| -> VortexResult<Geometry<f64>> {
201 Ok(geometry
202 .ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
203 .map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
204 .to_geometry())
205 })
206 .collect()
207}
208
209impl ArrowExportVTable for Rect {
210 fn arrow_ext_id(&self) -> Id {
211 *ARROW_BOX
212 }
213
214 fn vortex_id(&self) -> Id {
215 self.id()
216 }
217
218 fn to_arrow_field(
219 &self,
220 name: &str,
221 dtype: &DType,
222 session: &ArrowSession,
223 ) -> VortexResult<Option<Field>> {
224 let ext_type = dtype.as_extension();
225 let spatial_metadata = ext_type.metadata::<Rect>();
226 let dimension = box_dimension(ext_type.storage_dtype())?;
227
228 let mut field = session.to_arrow_field(name, ext_type.storage_dtype())?;
229 field.try_with_extension_type(box_type(spatial_metadata, dimension))?;
230
231 Ok(Some(field))
232 }
233
234 fn execute_arrow(
235 &self,
236 array: ArrayRef,
237 target: &Field,
238 options: &ArrowExportOptions,
239 ctx: &mut ExecutionCtx,
240 ) -> VortexResult<ArrowExport> {
241 let is_box = array
242 .dtype()
243 .as_extension_opt()
244 .map(|ext| ext.is::<Rect>())
245 .unwrap_or(false);
246 if !is_box {
247 return Ok(ArrowExport::Unsupported(array));
248 }
249
250 let Ok(box_meta) = target.try_extension_type::<BoxType>() else {
251 return Ok(ArrowExport::Unsupported(array));
252 };
253
254 let executed = array.execute::<ExtensionArray>(ctx)?;
255 let storage = executed.storage_array().clone();
256
257 let storage_field = Field::new(
258 String::new(),
259 target.data_type().clone(),
260 target.is_nullable(),
261 );
262 let session = ctx.session().clone();
263 let arrow_storage =
264 session
265 .arrow()
266 .exporter(options)
267 .execute_arrow(storage, Some(&storage_field), ctx)?;
268
269 let rects = RectArray::try_from((arrow_storage.as_ref(), box_meta))
271 .map_err(|e| vortex_err!("failed to construct RectArray: {e}"))?;
272
273 Ok(ArrowExport::Exported(Arc::new(rects.into_arrow())))
274 }
275}
276
277impl ArrowImportVTable for Rect {
278 fn arrow_ext_id(&self) -> Id {
279 *ARROW_BOX
280 }
281
282 fn from_arrow_field(
286 &self,
287 field: &Field,
288 session: &ArrowSession,
289 ) -> VortexResult<Option<DType>> {
290 let (dimension, metadata) = if let Ok(box_meta) = field.try_extension_type::<BoxType>() {
291 (
292 box_meta.dimension().into(),
293 spatial_metadata_from_arrow(box_meta.metadata()),
294 )
295 } else {
296 if field.extension_type_name() != Some(BoxType::NAME) {
297 return Ok(None);
298 }
299 let Ok(DType::Struct(fields, _)) =
302 session.from_arrow_datatype(field.data_type(), field.is_nullable().into())
303 else {
304 return Ok(None);
305 };
306 let Some(dimension) = box_dimension_from_names(fields.names()) else {
307 return Ok(None);
308 };
309 (dimension, SpatialMetadata::default())
310 };
311
312 let storage_dtype = box_storage_dtype(dimension, field.is_nullable().into());
313 Ok(Some(DType::Extension(
314 ExtDType::try_with_vtable(Rect, metadata, storage_dtype)?.erased(),
315 )))
316 }
317
318 fn from_arrow_array(
319 &self,
320 array: ArrowArrayRef,
321 field: &Field,
322 dtype: &DType,
323 session: &ArrowSession,
324 ) -> VortexResult<ArrowImport> {
325 let Some(ext_dtype) = dtype.as_extension_opt() else {
326 return Ok(ArrowImport::Unsupported(array));
327 };
328 if !ext_dtype.is::<Rect>()
329 || field.try_extension_type::<BoxType>().is_err()
330 || !matches!(array.data_type(), DataType::Struct(_))
331 {
332 return Ok(ArrowImport::Unsupported(array));
333 }
334
335 let storage = session.from_arrow_array(array, field.is_nullable())?;
336 Ok(ArrowImport::Imported(
337 ExtensionArray::try_new(ext_dtype.clone(), storage)?.into_array(),
338 ))
339 }
340}
341
342#[cfg(test)]
343mod tests {
344 use std::sync::LazyLock;
345
346 use geo_types::Geometry;
347 use rstest::rstest;
348 use vortex_array::VortexSessionExecute;
349 use vortex_array::arrays::ExtensionArray;
350 use vortex_array::arrays::extension::ExtensionArrayExt;
351 use vortex_array::dtype::DType;
352 use vortex_array::dtype::Nullability;
353 use vortex_array::dtype::PType;
354 use vortex_array::dtype::extension::ExtDType;
355 use vortex_error::VortexResult;
356 use vortex_session::VortexSession;
357
358 use super::Rect;
359 use super::box_dimension;
360 use super::box_storage_dtype;
361 use super::rect_geometries;
362 use crate::extension::SpatialMetadata;
363 use crate::extension::coordinate::Dimension;
364
365 static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
366
367 fn spatial_meta() -> SpatialMetadata {
368 SpatialMetadata {
369 crs: Some("EPSG:4326".to_string()),
370 }
371 }
372
373 #[rstest]
376 #[case::xy(Dimension::Xy)]
377 #[case::xyz(Dimension::Xyz)]
378 #[case::xym(Dimension::Xym)]
379 #[case::xyzm(Dimension::Xyzm)]
380 fn box_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
381 let storage = box_storage_dtype(dim, Nullability::NonNullable);
382 ExtDType::<Rect>::try_new(spatial_meta(), storage.clone())?;
383 assert_eq!(box_dimension(&storage)?, dim);
384 Ok(())
385 }
386
387 #[test]
390 fn box_rejects_invalid_storage() -> VortexResult<()> {
391 let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
392 assert!(ExtDType::<Rect>::try_new(spatial_meta(), primitive).is_err());
393
394 let point_like = box_storage_dtype(Dimension::Xy, Nullability::NonNullable);
395 let DType::Struct(fields, _) = &point_like else {
396 unreachable!("box storage is a struct");
397 };
398 let renamed = DType::Struct(
400 vortex_array::dtype::StructFields::new(
401 ["x", "ymin", "xmax", "ymax"].into(),
402 fields.fields().collect(),
403 ),
404 Nullability::NonNullable,
405 );
406 assert!(ExtDType::<Rect>::try_new(spatial_meta(), renamed).is_err());
407 Ok(())
408 }
409
410 #[test]
412 fn box_decodes_to_geo_types_rect() -> VortexResult<()> {
413 let mut ctx = SESSION.create_execution_ctx();
414
415 let rects = crate::test_harness::rect_column(vec![(0.0, 0.0, 2.0, 3.0)])?;
416 let storage = rects
417 .execute::<ExtensionArray>(&mut ctx)?
418 .storage_array()
419 .clone();
420
421 let geometries = rect_geometries(&storage, &mut ctx)?;
422 assert_eq!(
423 geometries,
424 vec![Geometry::Rect(geo_types::Rect::new((0.0, 0.0), (2.0, 3.0)))]
425 );
426 Ok(())
427 }
428}