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//! Native point geometry (`vortex.st.point`).
5//!
6//! [`Point`] stores `Struct<x, y[, z][, m]>` coordinates with non-nullable `f64` fields.
7//! [`SpatialMetadata`] declares the coordinate dimension and optional coordinate reference system.
8//! The four GeoArrow dimensions are XY, XYZ, XYM, and XYZM. `z` is an elevation and `m` is a
9//! measure, such as distance along a route or a timestamp.
10
11use arrow_array::ArrayRef as ArrowArrayRef;
12use arrow_schema::Field;
13use arrow_schema::extension::ExtensionType;
14use geo_traits::to_geo::ToGeoGeometry;
15use geo_types::Geometry;
16use geoarrow::array::GeoArrowArrayAccessor;
17use geoarrow::array::IntoArrow;
18use geoarrow::array::PointArray;
19use geoarrow::datatypes::CoordType;
20use geoarrow::datatypes::PointType;
21use vortex_array::ArrayRef;
22use vortex_array::ExecutionCtx;
23use vortex_array::arrays::ExtensionArray;
24use vortex_array::arrays::extension::ExtensionArrayExt;
25use vortex_array::dtype::DType;
26use vortex_array::dtype::Nullability;
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::ArrowExtVTable;
35use vortex_arrow::ArrowImport;
36use vortex_arrow::ArrowMetadataPolicy;
37use vortex_arrow::ArrowSession;
38use vortex_arrow::ArrowSessionExt;
39use vortex_arrow::ExecuteArrowExt;
40use vortex_error::VortexError;
41use vortex_error::VortexResult;
42use vortex_error::vortex_ensure;
43use vortex_error::vortex_err;
44use vortex_session::registry::CachedId;
45use vortex_session::registry::Id;
46
47use super::SpatialMetadata;
48use super::coordinate::Coordinate;
49use super::coordinate::Dimension;
50use super::coordinate::coordinate_dimension;
51use super::coordinate::coordinate_from_struct;
52use super::coordinate::coordinate_storage_dtype;
53use super::geoarrow_metadata;
54use super::geoarrow_to_wkb;
55use super::spatial_metadata_from_arrow;
56
57/// A single location: `geoarrow.point`, stored as `Struct<x, y[, z][, m]>` of non-nullable `f64`.
58#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
59pub struct Point;
60
61impl ExtVTable for Point {
62    type Metadata = SpatialMetadata;
63    type StoredMetadata = super::SpatialStoredMetadata;
64    type NativeValue<'a> = Coordinate;
65
66    fn id(&self) -> ExtId {
67        static ID: CachedId = CachedId::new("vortex.st.point");
68        *ID
69    }
70
71    fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
72        Ok(metadata.serialize())
73    }
74
75    fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult<Self::StoredMetadata> {
76        super::SpatialStoredMetadata::deserialize(metadata)
77    }
78
79    fn metadata_from_storage(
80        &self,
81        stored_metadata: Self::StoredMetadata,
82        storage_dtype: &DType,
83    ) -> VortexResult<Self::Metadata> {
84        Ok(SpatialMetadata::from_stored_metadata(
85            stored_metadata,
86            Some(coordinate_dimension(storage_dtype)?),
87        ))
88    }
89
90    fn storage_dtype(metadata: &Self::Metadata) -> DType {
91        coordinate_storage_dtype(metadata.native_dimension(), Nullability::NonNullable)
92    }
93
94    fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> {
95        metadata.validate_native(Point.id())
96    }
97
98    fn unpack_native<'a>(
99        ext_dtype: &'a ExtDType<Self>,
100        storage_value: &'a ScalarValue,
101    ) -> VortexResult<Coordinate> {
102        let storage = Scalar::try_new(
103            ext_dtype.storage_dtype().clone(),
104            Some(storage_value.clone()),
105        )?;
106        coordinate_from_struct(&storage)
107    }
108}
109
110static ARROW_POINT: CachedId = CachedId::new(PointType::NAME);
111
112/// The `geoarrow.point` extension type for `dimension`, with separated (struct) coordinates
113/// matching `Point` storage.
114fn point_type(spatial_metadata: &SpatialMetadata, dimension: Dimension) -> PointType {
115    PointType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
116}
117
118pub struct PointData(ExtensionArray);
119
120impl TryFrom<ExtensionArray> for PointData {
121    type Error = VortexError;
122
123    fn try_from(ext: ExtensionArray) -> Result<Self, Self::Error> {
124        vortex_ensure!(
125            ext.ext_dtype().is::<Point>(),
126            "expected a Point extension array"
127        );
128        Ok(PointData(ext))
129    }
130}
131
132impl PointData {
133    /// Serialize points to WKB (a view array) — the form DuckDB `GEOMETRY` takes.
134    pub fn to_wkb(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
135        geoarrow_to_wkb(
136            &point_array(self.0.storage_array(), ctx)?,
137            &ctx.session().arrow(),
138        )
139    }
140}
141
142/// Build a geoarrow `PointArray` from a `Point`'s `Struct<x, y[, ..]>` storage, shared by WKB export
143/// and `geo_types` decoding.
144fn point_array(storage: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<PointArray> {
145    let point_type = point_type(
146        &SpatialMetadata::default(),
147        coordinate_dimension(storage.dtype())?,
148    );
149    let arrow = storage.clone().execute_arrow(None, ctx)?;
150    PointArray::try_from((arrow.as_ref(), point_type))
151        .map_err(|e| vortex_err!("failed to construct PointArray: {e}"))
152}
153
154/// Decode `Point` storage to `geo_types` points, for the spatial scalar functions.
155pub(crate) fn point_geometries(
156    storage: &ArrayRef,
157    ctx: &mut ExecutionCtx,
158) -> VortexResult<Vec<Geometry<f64>>> {
159    point_array(storage, ctx)?
160        .iter()
161        .map(|geometry| -> VortexResult<Geometry<f64>> {
162            Ok(geometry
163                .ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
164                .map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
165                .to_geometry())
166        })
167        .collect()
168}
169
170impl ArrowExtVTable for Point {
171    fn metadata_policy() -> ArrowMetadataPolicy {
172        ArrowMetadataPolicy::ArrowNative
173    }
174
175    fn arrow_ext_id(&self) -> Id {
176        *ARROW_POINT
177    }
178
179    fn to_arrow_field(
180        &self,
181        name: &str,
182        ext_dtype: &ExtDType<Self>,
183        session: &ArrowSession,
184    ) -> VortexResult<Option<Field>> {
185        let spatial_metadata = ext_dtype.metadata();
186        let dimension = spatial_metadata.native_dimension();
187
188        let mut field = session.to_arrow_field(name, ext_dtype.storage_dtype())?;
189        field.try_with_extension_type(point_type(spatial_metadata, dimension))?;
190
191        Ok(Some(field))
192    }
193
194    fn execute_arrow(
195        &self,
196        array: ArrayRef,
197        target: &Field,
198        options: &ArrowExportOptions,
199        ctx: &mut ExecutionCtx,
200    ) -> VortexResult<ArrowExport> {
201        let Ok(point_meta) = target.try_extension_type::<PointType>() else {
202            return Ok(ArrowExport::Unsupported(array));
203        };
204        if point_meta.coord_type() != CoordType::Separated {
205            return Ok(ArrowExport::Unsupported(array));
206        }
207
208        let executed = array.execute::<ExtensionArray>(ctx)?;
209        let storage = executed.storage_array().clone();
210
211        let storage_field = Field::new(
212            String::new(),
213            target.data_type().clone(),
214            target.is_nullable(),
215        );
216        let arrow_storage =
217            storage.execute_arrow_with_options(Some(&storage_field), options, ctx)?;
218
219        // Round-trip through the GeoArrow point array type: this validates that the storage is
220        // the separated-coordinate struct layout expected for a `PointType` extension field.
221        let points = PointArray::try_from((arrow_storage.as_ref(), point_meta))
222            .map_err(|e| vortex_err!("failed to construct PointArray: {e}"))?;
223
224        Ok(ArrowExport::Exported(points.into_arrow()))
225    }
226
227    fn from_arrow_field(
228        field: &Field,
229        _session: &ArrowSession,
230    ) -> VortexResult<Option<ExtDType<Self>>> {
231        let point_meta = field.try_extension_type::<PointType>()?;
232        vortex_ensure!(
233            point_meta.coord_type() == CoordType::Separated,
234            "geoarrow.point with interleaved coordinates is not supported; \
235             re-encode with separated (struct) coordinates"
236        );
237
238        let metadata = spatial_metadata_from_arrow(point_meta.metadata())
239            .with_dimension(point_meta.dimension().into());
240        Ok(Some(ExtDType::try_with_vtable(
241            Point,
242            metadata,
243            field.is_nullable().into(),
244        )?))
245    }
246
247    fn from_arrow_array(
248        array: ArrowArrayRef,
249        _field: &Field,
250        ext_dtype: &ExtDType<Self>,
251        session: &ArrowSession,
252    ) -> VortexResult<ArrowImport> {
253        session
254            .from_arrow_storage(array, &ext_dtype.clone().erased())
255            .map(ArrowImport::Imported)
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use std::sync::LazyLock;
262
263    use rstest::rstest;
264    use vortex_array::IntoArray;
265    use vortex_array::VortexSessionExecute;
266    use vortex_array::arrays::PrimitiveArray;
267    use vortex_array::arrays::StructArray;
268    use vortex_array::dtype::DType;
269    use vortex_array::dtype::Nullability;
270    use vortex_array::dtype::PType;
271    use vortex_array::dtype::extension::ExtDType;
272    use vortex_array::dtype::extension::ExtDTypePlugin;
273    use vortex_array::flatbuffers::WriteFlatBufferExt;
274    use vortex_error::VortexResult;
275    use vortex_session::VortexSession;
276
277    use super::Point;
278    use crate::extension::SpatialMetadata;
279    use crate::extension::coordinate::Coordinate;
280    use crate::extension::coordinate::Dimension;
281    use crate::extension::coordinate::coordinate_storage_dtype;
282    use crate::test_harness::coordinate_from_scalar;
283    use crate::test_harness::point_column;
284    use crate::test_harness::spatial_session;
285
286    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
287
288    fn spatial_meta() -> SpatialMetadata {
289        SpatialMetadata::new(Some("EPSG:4326".to_string()))
290    }
291
292    /// `Point` reads the canonical coordinate storage of every GeoArrow dimension.
293    #[rstest]
294    #[case::xy(Dimension::Xy)]
295    #[case::xyz(Dimension::Xyz)]
296    #[case::xym(Dimension::Xym)]
297    #[case::xyzm(Dimension::Xyzm)]
298    fn point_reads_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
299        let storage = coordinate_storage_dtype(dim, Nullability::NonNullable);
300        Point.deserialize(&spatial_meta().serialize(), storage)?;
301        Ok(())
302    }
303
304    /// A `Point` dtype round-trips through a flatbuffer. The read compares the stored storage
305    /// dtype, whose struct fields are flatbuffer views, with the declared one, whose fields are
306    /// owned.
307    #[test]
308    fn point_dtype_roundtrips_through_flatbuffer() -> VortexResult<()> {
309        let metadata = spatial_meta().with_dimension(Dimension::Xyz);
310        let dtype =
311            DType::Extension(ExtDType::<Point>::try_new(metadata, Nullability::Nullable)?.erased());
312
313        let bytes = dtype.write_flatbuffer_bytes()?;
314        assert_eq!(DType::from_flatbuffer(bytes, &spatial_session())?, dtype);
315
316        Ok(())
317    }
318
319    /// Invalid storage fails to read: both non-struct storage and a struct whose fields are not
320    /// GeoArrow coordinates.
321    #[test]
322    fn point_rejects_invalid_storage() -> VortexResult<()> {
323        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
324        assert!(
325            Point
326                .deserialize(&spatial_meta().serialize(), primitive)
327                .is_err()
328        );
329
330        let wrong_fields = StructArray::from_fields(&[
331            ("a", PrimitiveArray::from_iter(vec![0.0f64]).into_array()),
332            ("b", PrimitiveArray::from_iter(vec![0.0f64]).into_array()),
333        ])?
334        .into_array();
335        assert!(
336            Point
337                .deserialize(&spatial_meta().serialize(), wrong_fields.dtype().clone())
338                .is_err()
339        );
340        Ok(())
341    }
342
343    /// A `Point` column round-trips through scalar execution back to the original coordinates.
344    #[test]
345    fn point_unpacks_coordinates() -> VortexResult<()> {
346        let mut ctx = SESSION.create_execution_ctx();
347
348        let points = point_column(vec![1.0, -111.7610], vec![2.0, 34.8697])?;
349
350        assert_eq!(
351            coordinate_from_scalar(&points.execute_scalar(0, &mut ctx)?)?,
352            Coordinate::xy(1.0, 2.0)
353        );
354        assert_eq!(
355            coordinate_from_scalar(&points.execute_scalar(1, &mut ctx)?)?,
356            Coordinate::xy(-111.7610, 34.8697)
357        );
358        Ok(())
359    }
360}