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