Skip to main content

vortex_spatial/extension/
point.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! The [`Point`] geometry extension type (`vortex.st.point`): a location stored columnarly as
5//! `Struct<x, y[, z][, m]>` of non-nullable `f64` — the four GeoArrow dimensions XY, XYZ, XYM,
6//! XYZM — tagged with [`SpatialMetadata`] (CRS). `z` is an optional elevation and `m` an optional
7//! measure: an arbitrary per-point value such as distance along a route or a timestamp.
8
9use 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/// A single location: `geoarrow.point`, stored as `Struct<x, y[, z][, m]>` of non-nullable `f64`.
57#[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
95/// The `geoarrow.point` extension type for `dimension`, with separated (struct) coordinates
96/// matching `Point` storage.
97fn 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    /// Serialize points to WKB (a view array) — the form DuckDB `GEOMETRY` takes.
117    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
125/// Build a geoarrow `PointArray` from a `Point`'s `Struct<x, y[, ..]>` storage, shared by WKB export
126/// and `geo_types` decoding.
127fn 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
138/// Decode `Point` storage to `geo_types` points, for the spatial scalar functions.
139pub(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        // Round-trip through the GeoArrow point array type: this validates that the storage is
218        // the separated-coordinate struct layout expected for a `PointType` extension field.
219        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    /// Import a `geoarrow.point` field as the [`Point`] dtype. Keyed off the standard GeoArrow name,
232    /// so any producer (DataFusion, DuckDB, geoarrow-rs, …) resolves here. Accepts the full
233    /// `PointType` extension, or — for a metadata-less geometry literal — the name alone, inferring
234    /// the dimension from the coordinate field names.
235    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            // Infer the dimension from the field names, not the canonical storage check: a literal's
253            // coordinate fields may be nullable, which that check rejects.
254            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 std::sync::LazyLock;
301
302    use rstest::rstest;
303    use vortex_array::IntoArray;
304    use vortex_array::VortexSessionExecute;
305    use vortex_array::arrays::PrimitiveArray;
306    use vortex_array::arrays::StructArray;
307    use vortex_array::dtype::DType;
308    use vortex_array::dtype::Nullability;
309    use vortex_array::dtype::PType;
310    use vortex_array::dtype::extension::ExtDType;
311    use vortex_error::VortexResult;
312    use vortex_session::VortexSession;
313
314    use super::Point;
315    use crate::extension::SpatialMetadata;
316    use crate::extension::coordinate::Coordinate;
317    use crate::extension::coordinate::Dimension;
318    use crate::extension::coordinate::coordinate_storage_dtype;
319    use crate::test_harness::coordinate_from_scalar;
320    use crate::test_harness::point_column;
321
322    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
323
324    fn spatial_meta() -> SpatialMetadata {
325        SpatialMetadata {
326            crs: Some("EPSG:4326".to_string()),
327        }
328    }
329
330    /// `Point` accepts the canonical coordinate storage of every GeoArrow dimension.
331    #[rstest]
332    #[case::xy(Dimension::Xy)]
333    #[case::xyz(Dimension::Xyz)]
334    #[case::xym(Dimension::Xym)]
335    #[case::xyzm(Dimension::Xyzm)]
336    fn point_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
337        let storage = coordinate_storage_dtype(dim, Nullability::NonNullable);
338        ExtDType::<Point>::try_new(spatial_meta(), storage)?;
339        Ok(())
340    }
341
342    /// Invalid storage is rejected at dtype construction: both non-struct storage and a struct whose
343    /// fields are not GeoArrow coordinates.
344    #[test]
345    fn point_rejects_invalid_storage() -> VortexResult<()> {
346        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
347        assert!(ExtDType::<Point>::try_new(spatial_meta(), primitive).is_err());
348
349        let wrong_fields = StructArray::from_fields(&[
350            ("a", PrimitiveArray::from_iter(vec![0.0f64]).into_array()),
351            ("b", PrimitiveArray::from_iter(vec![0.0f64]).into_array()),
352        ])?
353        .into_array();
354        assert!(ExtDType::<Point>::try_new(spatial_meta(), wrong_fields.dtype().clone()).is_err());
355        Ok(())
356    }
357
358    /// A `Point` column round-trips through scalar execution back to the original coordinates.
359    #[test]
360    fn point_unpacks_coordinates() -> VortexResult<()> {
361        let mut ctx = SESSION.create_execution_ctx();
362
363        let points = point_column(vec![1.0, -111.7610], vec![2.0, 34.8697])?;
364
365        assert_eq!(
366            coordinate_from_scalar(&points.execute_scalar(0, &mut ctx)?)?,
367            Coordinate::xy(1.0, 2.0)
368        );
369        assert_eq!(
370            coordinate_from_scalar(&points.execute_scalar(1, &mut ctx)?)?,
371            Coordinate::xy(-111.7610, 34.8697)
372        );
373        Ok(())
374    }
375}