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