vortex_spatial/extension/
point.rs1use arrow_array::ArrayRef as ArrowArrayRef;
10use arrow_schema::DataType;
11use arrow_schema::Field;
12use arrow_schema::extension::ExtensionType;
13use geo_traits::to_geo::ToGeoGeometry;
14use geo_types::Geometry;
15use geoarrow::array::GeoArrowArrayAccessor;
16use geoarrow::array::IntoArrow;
17use geoarrow::array::PointArray;
18use geoarrow::datatypes::CoordType;
19use geoarrow::datatypes::PointType;
20use prost::Message;
21use vortex_array::ArrayRef;
22use vortex_array::ExecutionCtx;
23use vortex_array::IntoArray;
24use vortex_array::arrays::ExtensionArray;
25use vortex_array::arrays::extension::ExtensionArrayExt;
26use vortex_array::dtype::DType;
27use vortex_array::dtype::extension::ExtDType;
28use vortex_array::dtype::extension::ExtId;
29use vortex_array::dtype::extension::ExtVTable;
30use vortex_array::scalar::Scalar;
31use vortex_array::scalar::ScalarValue;
32use vortex_arrow::ArrowExport;
33use vortex_arrow::ArrowExportVTable;
34use vortex_arrow::ArrowImport;
35use vortex_arrow::ArrowImportVTable;
36use vortex_arrow::ArrowSession;
37use vortex_arrow::ArrowSessionExt;
38use vortex_error::VortexError;
39use vortex_error::VortexResult;
40use vortex_error::vortex_ensure;
41use vortex_error::vortex_err;
42use vortex_session::registry::CachedId;
43use vortex_session::registry::Id;
44
45use super::SpatialMetadata;
46use super::coordinate::Coordinate;
47use super::coordinate::Dimension;
48use super::coordinate::coordinate_dimension;
49use super::coordinate::coordinate_from_struct;
50use super::coordinate::coordinate_storage_dtype;
51use super::geoarrow_metadata;
52use super::geoarrow_to_wkb;
53use super::spatial_metadata_from_arrow;
54
55#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
57pub struct Point;
58
59impl ExtVTable for Point {
60 type Metadata = SpatialMetadata;
61 type NativeValue<'a> = Coordinate;
62
63 fn id(&self) -> ExtId {
64 static ID: CachedId = CachedId::new("vortex.st.point");
65 *ID
66 }
67
68 fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
69 Ok(metadata.encode_to_vec())
70 }
71
72 fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult<Self::Metadata> {
73 Ok(SpatialMetadata::decode(metadata)?)
74 }
75
76 fn validate_dtype(ext_dtype: &ExtDType<Self>) -> VortexResult<()> {
77 coordinate_dimension(ext_dtype.storage_dtype()).map(|_| ())
78 }
79
80 fn unpack_native<'a>(
81 ext_dtype: &'a ExtDType<Self>,
82 storage_value: &'a ScalarValue,
83 ) -> VortexResult<Coordinate> {
84 let storage = Scalar::try_new(
85 ext_dtype.storage_dtype().clone(),
86 Some(storage_value.clone()),
87 )?;
88 coordinate_from_struct(&storage)
89 }
90}
91
92static ARROW_POINT: CachedId = CachedId::new(PointType::NAME);
93
94fn point_type(spatial_metadata: &SpatialMetadata, dimension: Dimension) -> PointType {
97 PointType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
98}
99
100pub struct PointData(ExtensionArray);
101
102impl TryFrom<ExtensionArray> for PointData {
103 type Error = VortexError;
104
105 fn try_from(ext: ExtensionArray) -> Result<Self, Self::Error> {
106 vortex_ensure!(
107 ext.ext_dtype().is::<Point>(),
108 "expected a Point extension array"
109 );
110 Ok(PointData(ext))
111 }
112}
113
114impl PointData {
115 pub fn to_wkb(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
117 geoarrow_to_wkb(
118 &point_array(self.0.storage_array(), ctx)?,
119 &ctx.session().arrow(),
120 )
121 }
122}
123
124fn point_array(storage: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<PointArray> {
127 let point_type = point_type(
128 &SpatialMetadata::default(),
129 coordinate_dimension(storage.dtype())?,
130 );
131 let session = ctx.session().clone();
132 let arrow = session.arrow().execute_arrow(storage.clone(), None, ctx)?;
133 PointArray::try_from((arrow.as_ref(), point_type))
134 .map_err(|e| vortex_err!("failed to construct PointArray: {e}"))
135}
136
137pub(crate) fn point_geometries(
139 storage: &ArrayRef,
140 ctx: &mut ExecutionCtx,
141) -> VortexResult<Vec<Geometry<f64>>> {
142 point_array(storage, ctx)?
143 .iter()
144 .map(|geometry| -> VortexResult<Geometry<f64>> {
145 Ok(geometry
146 .ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
147 .map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
148 .to_geometry())
149 })
150 .collect()
151}
152
153impl ArrowExportVTable for Point {
154 fn arrow_ext_id(&self) -> Id {
155 *ARROW_POINT
156 }
157
158 fn vortex_id(&self) -> Id {
159 self.id()
160 }
161
162 fn to_arrow_field(
163 &self,
164 name: &str,
165 dtype: &DType,
166 session: &ArrowSession,
167 ) -> VortexResult<Option<Field>> {
168 let ext_type = dtype.as_extension();
169 let spatial_metadata = ext_type.metadata::<Point>();
170 let dimension = coordinate_dimension(ext_type.storage_dtype())?;
171
172 let mut field = session.to_arrow_field(name, ext_type.storage_dtype())?;
173 field.try_with_extension_type(point_type(spatial_metadata, dimension))?;
174
175 Ok(Some(field))
176 }
177
178 fn execute_arrow(
179 &self,
180 array: ArrayRef,
181 target: &Field,
182 ctx: &mut ExecutionCtx,
183 ) -> VortexResult<ArrowExport> {
184 let is_point = array
185 .dtype()
186 .as_extension_opt()
187 .map(|ext| ext.is::<Point>())
188 .unwrap_or(false);
189 if !is_point {
190 return Ok(ArrowExport::Unsupported(array));
191 }
192
193 let Ok(point_meta) = target.try_extension_type::<PointType>() else {
194 return Ok(ArrowExport::Unsupported(array));
195 };
196 if point_meta.coord_type() != CoordType::Separated {
197 return Ok(ArrowExport::Unsupported(array));
198 }
199
200 let executed = array.execute::<ExtensionArray>(ctx)?;
201 let storage = executed.storage_array().clone();
202
203 let storage_field = Field::new(
204 String::new(),
205 target.data_type().clone(),
206 target.is_nullable(),
207 );
208 let session = ctx.session().clone();
209 let arrow_storage = session
210 .arrow()
211 .execute_arrow(storage, Some(&storage_field), ctx)?;
212
213 let points = PointArray::try_from((arrow_storage.as_ref(), point_meta))
216 .map_err(|e| vortex_err!("failed to construct PointArray: {e}"))?;
217
218 Ok(ArrowExport::Exported(points.into_arrow()))
219 }
220}
221
222impl ArrowImportVTable for Point {
223 fn arrow_ext_id(&self) -> Id {
224 *ARROW_POINT
225 }
226
227 fn from_arrow_field(
232 &self,
233 field: &Field,
234 session: &ArrowSession,
235 ) -> VortexResult<Option<DType>> {
236 let (dimension, metadata) = if let Ok(point_meta) = field.try_extension_type::<PointType>()
237 {
238 vortex_ensure!(
239 point_meta.coord_type() == CoordType::Separated,
240 "geoarrow.point with interleaved coordinates is not supported; \
241 re-encode with separated (struct) coordinates"
242 );
243 (
244 point_meta.dimension().into(),
245 spatial_metadata_from_arrow(point_meta.metadata()),
246 )
247 } else {
248 if field.extension_type_name() != Some(PointType::NAME) {
251 return Ok(None);
252 }
253 let Ok(DType::Struct(fields, _)) =
254 session.from_arrow_datatype(field.data_type(), field.is_nullable().into())
255 else {
256 return Ok(None);
257 };
258 let Ok(dimension) = Dimension::from_field_names(fields.names()) else {
259 return Ok(None);
260 };
261 (dimension, SpatialMetadata::default())
262 };
263
264 let storage_dtype = coordinate_storage_dtype(dimension, field.is_nullable().into());
265 Ok(Some(DType::Extension(
266 ExtDType::try_with_vtable(Point, metadata, storage_dtype)?.erased(),
267 )))
268 }
269
270 fn from_arrow_array(
271 &self,
272 array: ArrowArrayRef,
273 field: &Field,
274 dtype: &DType,
275 session: &ArrowSession,
276 ) -> VortexResult<ArrowImport> {
277 let Some(ext_dtype) = dtype.as_extension_opt() else {
278 return Ok(ArrowImport::Unsupported(array));
279 };
280 if !ext_dtype.is::<Point>()
281 || field.try_extension_type::<PointType>().is_err()
282 || !matches!(array.data_type(), DataType::Struct(_))
283 {
284 return Ok(ArrowImport::Unsupported(array));
285 }
286
287 let storage = session.from_arrow_array(array, field.is_nullable())?;
288 Ok(ArrowImport::Imported(
289 ExtensionArray::try_new(ext_dtype.clone(), storage)?.into_array(),
290 ))
291 }
292}
293
294#[cfg(test)]
295mod tests {
296 use rstest::rstest;
297 use vortex_array::IntoArray;
298 use vortex_array::VortexSessionExecute;
299 use vortex_array::arrays::PrimitiveArray;
300 use vortex_array::arrays::StructArray;
301 use vortex_array::dtype::DType;
302 use vortex_array::dtype::Nullability;
303 use vortex_array::dtype::PType;
304 use vortex_array::dtype::extension::ExtDType;
305 use vortex_error::VortexResult;
306
307 use super::Point;
308 use crate::extension::SpatialMetadata;
309 use crate::extension::coordinate::Coordinate;
310 use crate::extension::coordinate::Dimension;
311 use crate::extension::coordinate::coordinate_storage_dtype;
312 use crate::test_harness::coordinate_from_scalar;
313 use crate::test_harness::point_column;
314
315 fn spatial_meta() -> SpatialMetadata {
316 SpatialMetadata {
317 crs: Some("EPSG:4326".to_string()),
318 }
319 }
320
321 #[rstest]
323 #[case::xy(Dimension::Xy)]
324 #[case::xyz(Dimension::Xyz)]
325 #[case::xym(Dimension::Xym)]
326 #[case::xyzm(Dimension::Xyzm)]
327 fn point_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
328 let storage = coordinate_storage_dtype(dim, Nullability::NonNullable);
329 ExtDType::<Point>::try_new(spatial_meta(), storage)?;
330 Ok(())
331 }
332
333 #[test]
336 fn point_rejects_invalid_storage() -> VortexResult<()> {
337 let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
338 assert!(ExtDType::<Point>::try_new(spatial_meta(), primitive).is_err());
339
340 let wrong_fields = StructArray::from_fields(&[
341 ("a", PrimitiveArray::from_iter(vec![0.0f64]).into_array()),
342 ("b", PrimitiveArray::from_iter(vec![0.0f64]).into_array()),
343 ])?
344 .into_array();
345 assert!(ExtDType::<Point>::try_new(spatial_meta(), wrong_fields.dtype().clone()).is_err());
346 Ok(())
347 }
348
349 #[test]
351 fn point_unpacks_coordinates() -> VortexResult<()> {
352 let session = vortex_array::array_session();
353 let mut ctx = session.create_execution_ctx();
354
355 let points = point_column(vec![1.0, -111.7610], vec![2.0, 34.8697])?;
356
357 assert_eq!(
358 coordinate_from_scalar(&points.execute_scalar(0, &mut ctx)?)?,
359 Coordinate::xy(1.0, 2.0)
360 );
361 assert_eq!(
362 coordinate_from_scalar(&points.execute_scalar(1, &mut ctx)?)?,
363 Coordinate::xy(-111.7610, 34.8697)
364 );
365 Ok(())
366 }
367}