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 `dtype` is `List<coordinate-struct>` and return its [`Dimension`].
108pub(crate) fn linestring_dimension(dtype: &DType) -> VortexResult<Dimension> {
109    let DType::List(coords, _) = dtype else {
110        vortex_bail!("linestring storage must be a List of coordinates, was {dtype}");
111    };
112    coordinate_dimension(coords)
113}
114
115/// Return one coordinate ordinate, filling an ordinate absent from the point dimension with zero.
116fn point_ordinate(
117    points: &StructArray,
118    dimension: Dimension,
119    name: &str,
120) -> VortexResult<ArrayRef> {
121    if dimension.field_names().contains(&name) {
122        points.unmasked_field_by_name(name).cloned()
123    } else {
124        Ok(ConstantArray::new(0.0f64, points.len()).into_array())
125    }
126}
127
128/// Build one native [`LineString`] per corresponding pair of point coordinate rows.
129pub(crate) fn linestring_array_from_point_pairs(
130    ext_dtype: &ExtDType<LineString>,
131    starts: &StructArray,
132    ends: &StructArray,
133    validity: Validity,
134) -> VortexResult<ArrayRef> {
135    let len = starts.len();
136    vortex_ensure_eq!(
137        len,
138        ends.len(),
139        "spatial: line string point columns must have equal lengths"
140    );
141    let vertex_count = len
142        .checked_mul(2)
143        .ok_or_else(|| vortex_err!("spatial: two-vertex line string length overflow"))?;
144    let last_offset = i32::try_from(vertex_count)
145        .map_err(|_| vortex_err!("spatial: two-vertex line string offset overflow"))?;
146    let row_count = u32::try_from(len)
147        .map_err(|_| vortex_err!("spatial: two-vertex line string row count overflow"))?;
148    let dimension = linestring_dimension(ext_dtype.storage_dtype())?;
149    let start_dimension = coordinate_dimension(starts.dtype())?;
150    let end_dimension = coordinate_dimension(ends.dtype())?;
151
152    let array_indices = PrimitiveArray::from_iter((0..len).flat_map(|_| [0u8, 1])).into_array();
153    let row_indices = Buffer::from_iter((0..row_count).flat_map(|row| [row; 2])).into_array();
154
155    let ordinates = dimension
156        .field_names()
157        .iter()
158        .map(|name| {
159            Ok(InterleaveArray::try_new(
160                vec![
161                    point_ordinate(starts, start_dimension, name)?,
162                    point_ordinate(ends, end_dimension, name)?,
163                ],
164                array_indices.clone(),
165                row_indices.clone(),
166            )?
167            .into_array())
168        })
169        .collect::<VortexResult<Vec<_>>>()?;
170
171    let vertices = StructArray::try_new(
172        FieldNames::from(dimension.field_names()),
173        ordinates,
174        vertex_count,
175        Validity::NonNullable,
176    )?
177    .into_array();
178
179    let offsets = Buffer::from_iter((0..=last_offset).step_by(2)).into_array();
180    let storage = ListArray::try_new(vertices, offsets, validity)?.into_array();
181
182    Ok(ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array())
183}
184
185static ARROW_LINESTRING: CachedId = CachedId::new(LineStringType::NAME);
186
187/// The `geoarrow.linestring` extension type for `dimension`, with separated (struct) coordinates
188/// matching `LineString` storage.
189fn linestring_type(spatial_metadata: &SpatialMetadata, dimension: Dimension) -> LineStringType {
190    LineStringType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
191}
192
193/// Decode `LineString` storage (`List<coordinate>`) to `geo_types` line strings, for the spatial scalar
194/// functions. CRS does not affect planar geometry ops, so default metadata is used.
195pub(crate) fn linestring_geometries(
196    storage: &ArrayRef,
197    ctx: &mut ExecutionCtx,
198) -> VortexResult<Vec<Geometry<f64>>> {
199    linestring_array(storage, ctx)?
200        .iter()
201        .map(|geometry| -> VortexResult<Geometry<f64>> {
202            Ok(geometry
203                .ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
204                .map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
205                .to_geometry())
206        })
207        .collect()
208}
209
210/// Build a geoarrow `LineStringArray` from a `LineString`'s `List<coordinate>` storage.
211fn linestring_array(storage: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<LineStringArray> {
212    let linestring_type = linestring_type(
213        &SpatialMetadata::default(),
214        linestring_dimension(storage.dtype())?,
215    );
216    let session = ctx.session().clone();
217    let arrow = session.arrow().execute_arrow(storage.clone(), None, ctx)?;
218    LineStringArray::try_from((arrow.as_ref(), linestring_type))
219        .map_err(|e| vortex_err!("failed to construct LineStringArray: {e}"))
220}
221
222/// A validated `LineString` array (`try_from` checks the extension type).
223pub struct LineStringData(ExtensionArray);
224
225impl TryFrom<ExtensionArray> for LineStringData {
226    type Error = VortexError;
227
228    fn try_from(ext: ExtensionArray) -> Result<Self, Self::Error> {
229        vortex_ensure!(
230            ext.ext_dtype().is::<LineString>(),
231            "expected a LineString extension array"
232        );
233        Ok(LineStringData(ext))
234    }
235}
236
237impl LineStringData {
238    /// Serialize line strings to WKB (a view array) — the form DuckDB `GEOMETRY` takes.
239    pub fn to_wkb(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
240        geoarrow_to_wkb(
241            &linestring_array(self.0.storage_array(), ctx)?,
242            &ctx.session().arrow(),
243        )
244    }
245}
246
247impl ArrowExportVTable for LineString {
248    fn arrow_ext_id(&self) -> Id {
249        *ARROW_LINESTRING
250    }
251
252    fn vortex_id(&self) -> Id {
253        self.id()
254    }
255
256    fn to_arrow_field(
257        &self,
258        name: &str,
259        dtype: &DType,
260        session: &ArrowSession,
261    ) -> VortexResult<Option<Field>> {
262        let ext_type = dtype.as_extension();
263        let spatial_metadata = ext_type.metadata::<LineString>();
264        let dimension = linestring_dimension(ext_type.storage_dtype())?;
265
266        let mut field = session.to_arrow_field(name, ext_type.storage_dtype())?;
267        field.try_with_extension_type(linestring_type(spatial_metadata, dimension))?;
268
269        Ok(Some(field))
270    }
271
272    fn execute_arrow(
273        &self,
274        array: ArrayRef,
275        target: &Field,
276        options: &ArrowExportOptions,
277        ctx: &mut ExecutionCtx,
278    ) -> VortexResult<ArrowExport> {
279        let is_linestring = array
280            .dtype()
281            .as_extension_opt()
282            .map(|ext| ext.is::<LineString>())
283            .unwrap_or(false);
284        if !is_linestring {
285            return Ok(ArrowExport::Unsupported(array));
286        }
287
288        let Ok(linestring_meta) = target.try_extension_type::<LineStringType>() else {
289            return Ok(ArrowExport::Unsupported(array));
290        };
291        if linestring_meta.coord_type() != CoordType::Separated {
292            return Ok(ArrowExport::Unsupported(array));
293        }
294
295        let executed = array.execute::<ExtensionArray>(ctx)?;
296        let storage = executed.storage_array().clone();
297
298        let storage_field = Field::new(
299            String::new(),
300            target.data_type().clone(),
301            target.is_nullable(),
302        );
303        let session = ctx.session().clone();
304        let arrow_storage =
305            session
306                .arrow()
307                .exporter(options)
308                .execute_arrow(storage, Some(&storage_field), ctx)?;
309
310        // Round-trip through GeoArrow's line-string array; `into_arrow` is concrete, so wrap in `Arc`.
311        let linestrings = LineStringArray::try_from((arrow_storage.as_ref(), linestring_meta))
312            .map_err(|e| vortex_err!("failed to construct LineStringArray: {e}"))?;
313
314        Ok(ArrowExport::Exported(Arc::new(linestrings.into_arrow())))
315    }
316}
317
318impl ArrowImportVTable for LineString {
319    fn arrow_ext_id(&self) -> Id {
320        *ARROW_LINESTRING
321    }
322
323    /// Import a `geoarrow.linestring` field as the [`LineString`] dtype. Keyed off the standard
324    /// GeoArrow name, so any producer resolves here. Accepts the full `LineStringType` extension, or
325    /// — for a metadata-less geometry literal — the name alone, inferring the dimension from the
326    /// coordinate field names.
327    fn from_arrow_field(
328        &self,
329        field: &Field,
330        session: &ArrowSession,
331    ) -> VortexResult<Option<DType>> {
332        let (dimension, metadata) =
333            if let Ok(linestring_meta) = field.try_extension_type::<LineStringType>() {
334                vortex_ensure!(
335                    linestring_meta.coord_type() == CoordType::Separated,
336                    "geoarrow.linestring with interleaved coordinates is not supported; \
337                 re-encode with separated (struct) coordinates"
338                );
339                (
340                    linestring_meta.dimension().into(),
341                    spatial_metadata_from_arrow(linestring_meta.metadata()),
342                )
343            } else {
344                // Literal: peel the `List` layer to the coordinate struct and read its dimension from
345                // the field names (the canonical check rejects nullable coordinates).
346                if field.extension_type_name() != Some(LineStringType::NAME) {
347                    return Ok(None);
348                }
349                let Ok(DType::List(coords, _)) =
350                    session.from_arrow_datatype(field.data_type(), field.is_nullable().into())
351                else {
352                    return Ok(None);
353                };
354                let DType::Struct(fields, _) = coords.as_ref() else {
355                    return Ok(None);
356                };
357                let Ok(dimension) = Dimension::from_field_names(fields.names()) else {
358                    return Ok(None);
359                };
360                (dimension, SpatialMetadata::default())
361            };
362
363        let storage_dtype = linestring_storage_dtype(dimension, field.is_nullable().into());
364        Ok(Some(DType::Extension(
365            ExtDType::try_with_vtable(LineString, metadata, storage_dtype)?.erased(),
366        )))
367    }
368
369    fn from_arrow_array(
370        &self,
371        array: ArrowArrayRef,
372        field: &Field,
373        dtype: &DType,
374        session: &ArrowSession,
375    ) -> VortexResult<ArrowImport> {
376        let Some(ext_dtype) = dtype.as_extension_opt() else {
377            return Ok(ArrowImport::Unsupported(array));
378        };
379        if !ext_dtype.is::<LineString>()
380            || field.try_extension_type::<LineStringType>().is_err()
381            || !matches!(array.data_type(), DataType::List(_))
382        {
383            return Ok(ArrowImport::Unsupported(array));
384        }
385
386        let storage = session.from_arrow_array(array, field.is_nullable())?;
387        Ok(ArrowImport::Imported(
388            ExtensionArray::try_new(ext_dtype.clone(), storage)?.into_array(),
389        ))
390    }
391}
392
393#[cfg(test)]
394mod tests {
395    use rstest::rstest;
396    use vortex_array::dtype::DType;
397    use vortex_array::dtype::Nullability;
398    use vortex_array::dtype::PType;
399    use vortex_array::dtype::extension::ExtDType;
400    use vortex_error::VortexResult;
401
402    use super::LineString;
403    use super::linestring_storage_dtype;
404    use crate::extension::SpatialMetadata;
405    use crate::extension::coordinate::Dimension;
406
407    fn spatial_meta() -> SpatialMetadata {
408        SpatialMetadata {
409            crs: Some("EPSG:4326".to_string()),
410        }
411    }
412
413    /// `LineString` accepts the canonical `List<coordinate-struct>` storage of every dimension.
414    #[rstest]
415    #[case::xy(Dimension::Xy)]
416    #[case::xyz(Dimension::Xyz)]
417    #[case::xym(Dimension::Xym)]
418    #[case::xyzm(Dimension::Xyzm)]
419    fn linestring_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
420        let storage = linestring_storage_dtype(dim, Nullability::NonNullable);
421        ExtDType::<LineString>::try_new(spatial_meta(), storage)?;
422        Ok(())
423    }
424
425    /// Non-linestring storage is rejected at dtype construction: a bare coordinate struct (point) is
426    /// not a list of coordinates.
427    #[test]
428    fn linestring_rejects_invalid_storage() -> VortexResult<()> {
429        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
430        assert!(ExtDType::<LineString>::try_new(spatial_meta(), primitive).is_err());
431        Ok(())
432    }
433}