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    // SAFETY: each line string has two vertices, so the offsets step by two from zero up to the
181    // vertex count. The validity has one entry per row.
182    let storage = unsafe { ListArray::new_unchecked(vertices, offsets, validity) }.into_array();
183
184    Ok(ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array())
185}
186
187static ARROW_LINESTRING: CachedId = CachedId::new(LineStringType::NAME);
188
189/// The `geoarrow.linestring` extension type for `dimension`, with separated (struct) coordinates
190/// matching `LineString` storage.
191fn linestring_type(spatial_metadata: &SpatialMetadata, dimension: Dimension) -> LineStringType {
192    LineStringType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
193}
194
195/// Decode `LineString` storage (`List<coordinate>`) to `geo_types` line strings, for the spatial scalar
196/// functions. CRS does not affect planar geometry ops, so default metadata is used.
197pub(crate) fn linestring_geometries(
198    storage: &ArrayRef,
199    ctx: &mut ExecutionCtx,
200) -> VortexResult<Vec<Geometry<f64>>> {
201    linestring_array(storage, ctx)?
202        .iter()
203        .map(|geometry| -> VortexResult<Geometry<f64>> {
204            Ok(geometry
205                .ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
206                .map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
207                .to_geometry())
208        })
209        .collect()
210}
211
212/// Build a geoarrow `LineStringArray` from a `LineString`'s `List<coordinate>` storage.
213fn linestring_array(storage: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<LineStringArray> {
214    let linestring_type = linestring_type(
215        &SpatialMetadata::default(),
216        linestring_dimension(storage.dtype())?,
217    );
218    let session = ctx.session().clone();
219    let arrow = session.arrow().execute_arrow(storage.clone(), None, ctx)?;
220    LineStringArray::try_from((arrow.as_ref(), linestring_type))
221        .map_err(|e| vortex_err!("failed to construct LineStringArray: {e}"))
222}
223
224/// A validated `LineString` array (`try_from` checks the extension type).
225pub struct LineStringData(ExtensionArray);
226
227impl TryFrom<ExtensionArray> for LineStringData {
228    type Error = VortexError;
229
230    fn try_from(ext: ExtensionArray) -> Result<Self, Self::Error> {
231        vortex_ensure!(
232            ext.ext_dtype().is::<LineString>(),
233            "expected a LineString extension array"
234        );
235        Ok(LineStringData(ext))
236    }
237}
238
239impl LineStringData {
240    /// Serialize line strings to WKB (a view array) — the form DuckDB `GEOMETRY` takes.
241    pub fn to_wkb(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
242        geoarrow_to_wkb(
243            &linestring_array(self.0.storage_array(), ctx)?,
244            &ctx.session().arrow(),
245        )
246    }
247}
248
249impl ArrowExportVTable for LineString {
250    fn arrow_ext_id(&self) -> Id {
251        *ARROW_LINESTRING
252    }
253
254    fn vortex_id(&self) -> Id {
255        self.id()
256    }
257
258    fn to_arrow_field(
259        &self,
260        name: &str,
261        dtype: &DType,
262        session: &ArrowSession,
263    ) -> VortexResult<Option<Field>> {
264        let ext_type = dtype.as_extension();
265        let spatial_metadata = ext_type.metadata::<LineString>();
266        let dimension = linestring_dimension(ext_type.storage_dtype())?;
267
268        let mut field = session.to_arrow_field(name, ext_type.storage_dtype())?;
269        field.try_with_extension_type(linestring_type(spatial_metadata, dimension))?;
270
271        Ok(Some(field))
272    }
273
274    fn execute_arrow(
275        &self,
276        array: ArrayRef,
277        target: &Field,
278        options: &ArrowExportOptions,
279        ctx: &mut ExecutionCtx,
280    ) -> VortexResult<ArrowExport> {
281        let is_linestring = array
282            .dtype()
283            .as_extension_opt()
284            .map(|ext| ext.is::<LineString>())
285            .unwrap_or(false);
286        if !is_linestring {
287            return Ok(ArrowExport::Unsupported(array));
288        }
289
290        let Ok(linestring_meta) = target.try_extension_type::<LineStringType>() else {
291            return Ok(ArrowExport::Unsupported(array));
292        };
293        if linestring_meta.coord_type() != CoordType::Separated {
294            return Ok(ArrowExport::Unsupported(array));
295        }
296
297        let executed = array.execute::<ExtensionArray>(ctx)?;
298        let storage = executed.storage_array().clone();
299
300        let storage_field = Field::new(
301            String::new(),
302            target.data_type().clone(),
303            target.is_nullable(),
304        );
305        let session = ctx.session().clone();
306        let arrow_storage =
307            session
308                .arrow()
309                .exporter(options)
310                .execute_arrow(storage, Some(&storage_field), ctx)?;
311
312        // Round-trip through GeoArrow's line-string array; `into_arrow` is concrete, so wrap in `Arc`.
313        let linestrings = LineStringArray::try_from((arrow_storage.as_ref(), linestring_meta))
314            .map_err(|e| vortex_err!("failed to construct LineStringArray: {e}"))?;
315
316        Ok(ArrowExport::Exported(Arc::new(linestrings.into_arrow())))
317    }
318}
319
320impl ArrowImportVTable for LineString {
321    fn arrow_ext_id(&self) -> Id {
322        *ARROW_LINESTRING
323    }
324
325    /// Import a `geoarrow.linestring` field as the [`LineString`] dtype. Keyed off the standard
326    /// GeoArrow name, so any producer resolves here. Accepts the full `LineStringType` extension, or
327    /// — for a metadata-less geometry literal — the name alone, inferring the dimension from the
328    /// coordinate field names.
329    fn from_arrow_field(
330        &self,
331        field: &Field,
332        session: &ArrowSession,
333    ) -> VortexResult<Option<DType>> {
334        let (dimension, metadata) =
335            if let Ok(linestring_meta) = field.try_extension_type::<LineStringType>() {
336                vortex_ensure!(
337                    linestring_meta.coord_type() == CoordType::Separated,
338                    "geoarrow.linestring with interleaved coordinates is not supported; \
339                 re-encode with separated (struct) coordinates"
340                );
341                (
342                    linestring_meta.dimension().into(),
343                    spatial_metadata_from_arrow(linestring_meta.metadata()),
344                )
345            } else {
346                // Literal: peel the `List` layer to the coordinate struct and read its dimension from
347                // the field names (the canonical check rejects nullable coordinates).
348                if field.extension_type_name() != Some(LineStringType::NAME) {
349                    return Ok(None);
350                }
351                let Ok(DType::List(coords, _)) =
352                    session.from_arrow_datatype(field.data_type(), field.is_nullable().into())
353                else {
354                    return Ok(None);
355                };
356                let DType::Struct(fields, _) = coords.as_ref() else {
357                    return Ok(None);
358                };
359                let Ok(dimension) = Dimension::from_field_names(fields.names()) else {
360                    return Ok(None);
361                };
362                (dimension, SpatialMetadata::default())
363            };
364
365        let storage_dtype = linestring_storage_dtype(dimension, field.is_nullable().into());
366        Ok(Some(DType::Extension(
367            ExtDType::try_with_vtable(LineString, metadata, storage_dtype)?.erased(),
368        )))
369    }
370
371    fn from_arrow_array(
372        &self,
373        array: ArrowArrayRef,
374        field: &Field,
375        dtype: &DType,
376        session: &ArrowSession,
377    ) -> VortexResult<ArrowImport> {
378        let Some(ext_dtype) = dtype.as_extension_opt() else {
379            return Ok(ArrowImport::Unsupported(array));
380        };
381        if !ext_dtype.is::<LineString>()
382            || field.try_extension_type::<LineStringType>().is_err()
383            || !matches!(array.data_type(), DataType::List(_))
384        {
385            return Ok(ArrowImport::Unsupported(array));
386        }
387
388        let storage = session.from_arrow_array(array, field.is_nullable())?;
389        Ok(ArrowImport::Imported(
390            ExtensionArray::try_new(ext_dtype.clone(), storage)?.into_array(),
391        ))
392    }
393}
394
395#[cfg(test)]
396mod tests {
397    use rstest::rstest;
398    use vortex_array::dtype::DType;
399    use vortex_array::dtype::Nullability;
400    use vortex_array::dtype::PType;
401    use vortex_array::dtype::extension::ExtDType;
402    use vortex_error::VortexResult;
403
404    use super::LineString;
405    use super::linestring_storage_dtype;
406    use crate::extension::SpatialMetadata;
407    use crate::extension::coordinate::Dimension;
408
409    fn spatial_meta() -> SpatialMetadata {
410        SpatialMetadata {
411            crs: Some("EPSG:4326".to_string()),
412        }
413    }
414
415    /// `LineString` accepts the canonical `List<coordinate-struct>` storage of every dimension.
416    #[rstest]
417    #[case::xy(Dimension::Xy)]
418    #[case::xyz(Dimension::Xyz)]
419    #[case::xym(Dimension::Xym)]
420    #[case::xyzm(Dimension::Xyzm)]
421    fn linestring_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
422        let storage = linestring_storage_dtype(dim, Nullability::NonNullable);
423        ExtDType::<LineString>::try_new(spatial_meta(), storage)?;
424        Ok(())
425    }
426
427    /// Non-linestring storage is rejected at dtype construction: a bare coordinate struct (point) is
428    /// not a list of coordinates.
429    #[test]
430    fn linestring_rejects_invalid_storage() -> VortexResult<()> {
431        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
432        assert!(ExtDType::<LineString>::try_new(spatial_meta(), primitive).is_err());
433        Ok(())
434    }
435}