Skip to main content

vortex_spatial/extension/
linestring.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! The [`LineString`] geometry extension type (`vortex.st.linestring`): an ordered path of the
5//! [`Point`](super::Point) coordinate struct, stored as `List<Struct<x, y[, z][, m]>>` and tagged
6//! with [`SpatialMetadata`] (CRS).
7
8use std::sync::Arc;
9
10use arrow_array::ArrayRef as ArrowArrayRef;
11use arrow_schema::DataType;
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::LineStringArray;
19use geoarrow::datatypes::CoordType;
20use geoarrow::datatypes::LineStringType;
21use prost::Message;
22use vortex_array::ArrayRef;
23use vortex_array::ExecutionCtx;
24use vortex_array::IntoArray;
25use vortex_array::arrays::ConstantArray;
26use vortex_array::arrays::ExtensionArray;
27use vortex_array::arrays::InterleaveArray;
28use vortex_array::arrays::ListArray;
29use vortex_array::arrays::PrimitiveArray;
30use vortex_array::arrays::StructArray;
31use vortex_array::arrays::extension::ExtensionArrayExt;
32use vortex_array::arrays::struct_::StructArrayExt;
33use vortex_array::dtype::DType;
34use vortex_array::dtype::FieldNames;
35use vortex_array::dtype::Nullability;
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_buffer::Buffer;
49use vortex_error::VortexError;
50use vortex_error::VortexResult;
51use vortex_error::vortex_bail;
52use vortex_error::vortex_ensure;
53use vortex_error::vortex_ensure_eq;
54use vortex_error::vortex_err;
55use vortex_session::registry::CachedId;
56use vortex_session::registry::Id;
57
58use super::SpatialMetadata;
59use super::coordinate::Dimension;
60use super::coordinate::coordinate_dimension;
61use super::coordinate::coordinate_storage_dtype;
62use super::geoarrow_metadata;
63use super::geoarrow_to_wkb;
64use super::spatial_metadata_from_arrow;
65
66/// A line string: `geoarrow.linestring`, stored as `List<Struct<x, y[, z][, m]>>` (an ordered path
67/// of vertices).
68#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
69pub struct LineString;
70
71impl ExtVTable for LineString {
72    type Metadata = SpatialMetadata;
73    // No cheap owned value like Point's `Coordinate`; expose the raw storage scalar.
74    type NativeValue<'a> = &'a ScalarValue;
75
76    fn id(&self) -> ExtId {
77        static ID: CachedId = CachedId::new("vortex.st.linestring");
78        *ID
79    }
80
81    fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
82        Ok(metadata.encode_to_vec())
83    }
84
85    fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult<Self::Metadata> {
86        Ok(SpatialMetadata::decode(metadata)?)
87    }
88
89    fn validate_dtype(ext_dtype: &ExtDType<Self>) -> VortexResult<()> {
90        linestring_dimension(ext_dtype.storage_dtype()).map(|_| ())
91    }
92
93    fn unpack_native<'a>(
94        _ext_dtype: &'a ExtDType<Self>,
95        storage_value: &'a ScalarValue,
96    ) -> VortexResult<&'a ScalarValue> {
97        Ok(storage_value)
98    }
99}
100
101/// Canonical line-string storage: a list of the coordinate `Struct`.
102pub(crate) fn linestring_storage_dtype(dim: Dimension, nullability: Nullability) -> DType {
103    let coords = coordinate_storage_dtype(dim, Nullability::NonNullable);
104    DType::List(Arc::new(coords), nullability)
105}
106
107/// Validate that `dtype` equals [`linestring_storage_dtype`] for its [`Dimension`] and top-level
108/// nullability, and return that dimension. As in GeoArrow, only the outer `List` can be nullable.
109pub(crate) fn linestring_dimension(dtype: &DType) -> VortexResult<Dimension> {
110    let DType::List(coords, _) = dtype else {
111        vortex_bail!("linestring storage must be a List of coordinates, was {dtype}");
112    };
113    let dimension = coordinate_dimension(coords)?;
114
115    vortex_ensure_eq!(
116        *dtype,
117        linestring_storage_dtype(dimension, dtype.nullability()),
118        "linestring storage can be nullable only at its outer List"
119    );
120
121    Ok(dimension)
122}
123
124/// Return one coordinate ordinate, filling an ordinate absent from the point dimension with zero.
125fn point_ordinate(
126    points: &StructArray,
127    dimension: Dimension,
128    name: &str,
129) -> VortexResult<ArrayRef> {
130    if dimension.field_names().contains(&name) {
131        points.unmasked_field_by_name(name).cloned()
132    } else {
133        Ok(ConstantArray::new(0.0f64, points.len()).into_array())
134    }
135}
136
137/// Build one native [`LineString`] per corresponding pair of point coordinate rows.
138pub(crate) fn linestring_array_from_point_pairs(
139    ext_dtype: &ExtDType<LineString>,
140    starts: &StructArray,
141    ends: &StructArray,
142    validity: Validity,
143) -> VortexResult<ArrayRef> {
144    let len = starts.len();
145    vortex_ensure_eq!(
146        len,
147        ends.len(),
148        "spatial: line string point columns must have equal lengths"
149    );
150    let vertex_count = len
151        .checked_mul(2)
152        .ok_or_else(|| vortex_err!("spatial: two-vertex line string length overflow"))?;
153    let last_offset = i32::try_from(vertex_count)
154        .map_err(|_| vortex_err!("spatial: two-vertex line string offset overflow"))?;
155    let row_count = u32::try_from(len)
156        .map_err(|_| vortex_err!("spatial: two-vertex line string row count overflow"))?;
157    let dimension = linestring_dimension(ext_dtype.storage_dtype())?;
158    let start_dimension = coordinate_dimension(starts.dtype())?;
159    let end_dimension = coordinate_dimension(ends.dtype())?;
160
161    let array_indices = PrimitiveArray::from_iter((0..len).flat_map(|_| [0u8, 1])).into_array();
162    let row_indices = Buffer::from_iter((0..row_count).flat_map(|row| [row; 2])).into_array();
163
164    let ordinates = dimension
165        .field_names()
166        .iter()
167        .map(|name| {
168            Ok(InterleaveArray::try_new(
169                vec![
170                    point_ordinate(starts, start_dimension, name)?,
171                    point_ordinate(ends, end_dimension, name)?,
172                ],
173                array_indices.clone(),
174                row_indices.clone(),
175            )?
176            .into_array())
177        })
178        .collect::<VortexResult<Vec<_>>>()?;
179
180    let vertices = StructArray::try_new(
181        FieldNames::from(dimension.field_names()),
182        ordinates,
183        vertex_count,
184        Validity::NonNullable,
185    )?
186    .into_array();
187
188    let offsets = Buffer::from_iter((0..=last_offset).step_by(2)).into_array();
189    // SAFETY: each line string has two vertices, so the offsets step by two from zero up to the
190    // vertex count. The validity has one entry per row.
191    let storage = unsafe { ListArray::new_unchecked(vertices, offsets, validity) }.into_array();
192
193    Ok(ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array())
194}
195
196static ARROW_LINESTRING: CachedId = CachedId::new(LineStringType::NAME);
197
198/// The `geoarrow.linestring` extension type for `dimension`, with separated (struct) coordinates
199/// matching `LineString` storage.
200fn linestring_type(spatial_metadata: &SpatialMetadata, dimension: Dimension) -> LineStringType {
201    LineStringType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
202}
203
204/// Decode `LineString` storage (`List<coordinate>`) to `geo_types` line strings, for the spatial scalar
205/// functions. CRS does not affect planar geometry ops, so default metadata is used.
206pub(crate) fn linestring_geometries(
207    storage: &ArrayRef,
208    ctx: &mut ExecutionCtx,
209) -> VortexResult<Vec<Geometry<f64>>> {
210    linestring_array(storage, ctx)?
211        .iter()
212        .map(|geometry| -> VortexResult<Geometry<f64>> {
213            Ok(geometry
214                .ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
215                .map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
216                .to_geometry())
217        })
218        .collect()
219}
220
221/// Build a geoarrow `LineStringArray` from a `LineString`'s `List<coordinate>` storage.
222fn linestring_array(storage: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<LineStringArray> {
223    let linestring_type = linestring_type(
224        &SpatialMetadata::default(),
225        linestring_dimension(storage.dtype())?,
226    );
227    let session = ctx.session().clone();
228    let arrow = session.arrow().execute_arrow(storage.clone(), None, ctx)?;
229    LineStringArray::try_from((arrow.as_ref(), linestring_type))
230        .map_err(|e| vortex_err!("failed to construct LineStringArray: {e}"))
231}
232
233/// A validated `LineString` array (`try_from` checks the extension type).
234pub struct LineStringData(ExtensionArray);
235
236impl TryFrom<ExtensionArray> for LineStringData {
237    type Error = VortexError;
238
239    fn try_from(ext: ExtensionArray) -> Result<Self, Self::Error> {
240        vortex_ensure!(
241            ext.ext_dtype().is::<LineString>(),
242            "expected a LineString extension array"
243        );
244        Ok(LineStringData(ext))
245    }
246}
247
248impl LineStringData {
249    /// Serialize line strings to WKB (a view array) — the form DuckDB `GEOMETRY` takes.
250    pub fn to_wkb(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
251        geoarrow_to_wkb(
252            &linestring_array(self.0.storage_array(), ctx)?,
253            &ctx.session().arrow(),
254        )
255    }
256}
257
258impl ArrowExportVTable for LineString {
259    fn arrow_ext_id(&self) -> Id {
260        *ARROW_LINESTRING
261    }
262
263    fn vortex_id(&self) -> Id {
264        self.id()
265    }
266
267    fn to_arrow_field(
268        &self,
269        name: &str,
270        dtype: &DType,
271        session: &ArrowSession,
272    ) -> VortexResult<Option<Field>> {
273        let ext_type = dtype.as_extension();
274        let spatial_metadata = ext_type.metadata::<LineString>();
275        let dimension = linestring_dimension(ext_type.storage_dtype())?;
276
277        let mut field = session.to_arrow_field(name, ext_type.storage_dtype())?;
278        field.try_with_extension_type(linestring_type(spatial_metadata, dimension))?;
279
280        Ok(Some(field))
281    }
282
283    fn execute_arrow(
284        &self,
285        array: ArrayRef,
286        target: &Field,
287        options: &ArrowExportOptions,
288        ctx: &mut ExecutionCtx,
289    ) -> VortexResult<ArrowExport> {
290        let is_linestring = array
291            .dtype()
292            .as_extension_opt()
293            .map(|ext| ext.is::<LineString>())
294            .unwrap_or(false);
295        if !is_linestring {
296            return Ok(ArrowExport::Unsupported(array));
297        }
298
299        let Ok(linestring_meta) = target.try_extension_type::<LineStringType>() else {
300            return Ok(ArrowExport::Unsupported(array));
301        };
302        if linestring_meta.coord_type() != CoordType::Separated {
303            return Ok(ArrowExport::Unsupported(array));
304        }
305
306        let executed = array.execute::<ExtensionArray>(ctx)?;
307        let storage = executed.storage_array().clone();
308
309        let storage_field = Field::new(
310            String::new(),
311            target.data_type().clone(),
312            target.is_nullable(),
313        );
314        let session = ctx.session().clone();
315        let arrow_storage =
316            session
317                .arrow()
318                .exporter(options)
319                .execute_arrow(storage, Some(&storage_field), ctx)?;
320
321        // Round-trip through GeoArrow's line-string array; `into_arrow` is concrete, so wrap in `Arc`.
322        let linestrings = LineStringArray::try_from((arrow_storage.as_ref(), linestring_meta))
323            .map_err(|e| vortex_err!("failed to construct LineStringArray: {e}"))?;
324
325        Ok(ArrowExport::Exported(Arc::new(linestrings.into_arrow())))
326    }
327}
328
329impl ArrowImportVTable for LineString {
330    fn arrow_ext_id(&self) -> Id {
331        *ARROW_LINESTRING
332    }
333
334    /// Import a `geoarrow.linestring` field as the [`LineString`] dtype. Keyed off the standard
335    /// GeoArrow name, so any producer resolves here. Accepts the full `LineStringType` extension, or
336    /// — for a metadata-less geometry literal — the name alone, inferring the dimension from the
337    /// coordinate field names.
338    fn from_arrow_field(
339        &self,
340        field: &Field,
341        session: &ArrowSession,
342    ) -> VortexResult<Option<DType>> {
343        let (dimension, metadata) =
344            if let Ok(linestring_meta) = field.try_extension_type::<LineStringType>() {
345                vortex_ensure!(
346                    linestring_meta.coord_type() == CoordType::Separated,
347                    "geoarrow.linestring with interleaved coordinates is not supported; \
348             re-encode with separated (struct) coordinates"
349                );
350                (
351                    linestring_meta.dimension().into(),
352                    spatial_metadata_from_arrow(linestring_meta.metadata()),
353                )
354            } else {
355                // Literal: peel the `List` layer to the coordinate struct and read its dimension from
356                // the field names (the canonical check rejects nullable coordinates).
357                if field.extension_type_name() != Some(LineStringType::NAME) {
358                    return Ok(None);
359                }
360                let Ok(DType::List(coords, _)) =
361                    session.from_arrow_datatype(field.data_type(), field.is_nullable().into())
362                else {
363                    return Ok(None);
364                };
365                let DType::Struct(fields, _) = coords.as_ref() else {
366                    return Ok(None);
367                };
368                let Ok(dimension) = Dimension::from_field_names(fields.names()) else {
369                    return Ok(None);
370                };
371                (dimension, SpatialMetadata::default())
372            };
373
374        let storage_dtype = linestring_storage_dtype(dimension, field.is_nullable().into());
375        Ok(Some(DType::Extension(
376            ExtDType::try_with_vtable(LineString, metadata, storage_dtype)?.erased(),
377        )))
378    }
379
380    fn from_arrow_array(
381        &self,
382        array: ArrowArrayRef,
383        field: &Field,
384        dtype: &DType,
385        session: &ArrowSession,
386    ) -> VortexResult<ArrowImport> {
387        let Some(ext_dtype) = dtype.as_extension_opt() else {
388            return Ok(ArrowImport::Unsupported(array));
389        };
390        if !ext_dtype.is::<LineString>()
391            || field.try_extension_type::<LineStringType>().is_err()
392            || !matches!(array.data_type(), DataType::List(_))
393        {
394            return Ok(ArrowImport::Unsupported(array));
395        }
396
397        let storage = session.from_arrow_array(array, field.is_nullable())?;
398        Ok(ArrowImport::Imported(
399            ExtensionArray::try_new(ext_dtype.clone(), storage)?.into_array(),
400        ))
401    }
402}
403
404#[cfg(test)]
405mod tests {
406    use rstest::rstest;
407    use vortex_array::dtype::DType;
408    use vortex_array::dtype::Nullability;
409    use vortex_array::dtype::PType;
410    use vortex_array::dtype::extension::ExtDType;
411    use vortex_error::VortexResult;
412
413    use super::LineString;
414    use super::linestring_storage_dtype;
415    use crate::extension::SpatialMetadata;
416    use crate::extension::coordinate::Dimension;
417
418    fn spatial_meta() -> SpatialMetadata {
419        SpatialMetadata {
420            crs: Some("EPSG:4326".to_string()),
421        }
422    }
423
424    /// `LineString` accepts the canonical `List<coordinate-struct>` storage of every dimension.
425    #[rstest]
426    #[case::xy(Dimension::Xy)]
427    #[case::xyz(Dimension::Xyz)]
428    #[case::xym(Dimension::Xym)]
429    #[case::xyzm(Dimension::Xyzm)]
430    fn linestring_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
431        let storage = linestring_storage_dtype(dim, Nullability::NonNullable);
432        ExtDType::<LineString>::try_new(spatial_meta(), storage)?;
433        Ok(())
434    }
435
436    /// Non-linestring storage is rejected at dtype construction: a bare coordinate struct (point) is
437    /// not a list of coordinates.
438    #[test]
439    fn linestring_rejects_invalid_storage() -> VortexResult<()> {
440        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
441        assert!(ExtDType::<LineString>::try_new(spatial_meta(), primitive).is_err());
442        Ok(())
443    }
444}