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//! Native line-string geometry (`vortex.st.linestring`).
5//!
6//! [`LineString`] stores an ordered path as `List<Struct<x, y[, z][, m]>>`. [`SpatialMetadata`]
7//! declares its coordinate dimension and optional coordinate reference system. Coordinates use
8//! non-nullable `f64` fields, and only the outer list can be nullable.
9
10use std::sync::Arc;
11
12use arrow_array::ArrayRef as ArrowArrayRef;
13use arrow_schema::Field;
14use arrow_schema::extension::ExtensionType;
15use geo_traits::to_geo::ToGeoGeometry;
16use geo_types::Geometry;
17use geoarrow::array::GeoArrowArrayAccessor;
18use geoarrow::array::LineStringArray;
19use geoarrow::datatypes::CoordType;
20use geoarrow::datatypes::LineStringType;
21use vortex_array::ArrayRef;
22use vortex_array::ExecutionCtx;
23use vortex_array::IntoArray;
24use vortex_array::arrays::ConstantArray;
25use vortex_array::arrays::ExtensionArray;
26use vortex_array::arrays::InterleaveArray;
27use vortex_array::arrays::ListArray;
28use vortex_array::arrays::PrimitiveArray;
29use vortex_array::arrays::StructArray;
30use vortex_array::arrays::extension::ExtensionArrayExt;
31use vortex_array::arrays::struct_::StructArrayExt;
32use vortex_array::dtype::DType;
33use vortex_array::dtype::FieldNames;
34use vortex_array::dtype::Nullability;
35use vortex_array::dtype::extension::ExtDType;
36use vortex_array::dtype::extension::ExtId;
37use vortex_array::dtype::extension::ExtVTable;
38use vortex_array::scalar::ScalarValue;
39use vortex_array::validity::Validity;
40use vortex_arrow::ArrowExport;
41use vortex_arrow::ArrowExportOptions;
42use vortex_arrow::ArrowExtVTable;
43use vortex_arrow::ArrowImport;
44use vortex_arrow::ArrowMetadataPolicy;
45use vortex_arrow::ArrowSession;
46use vortex_arrow::ArrowSessionExt;
47use vortex_arrow::ExecuteArrowExt;
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    type StoredMetadata = super::SpatialStoredMetadata;
74    // No cheap owned value like Point's `Coordinate`; expose the raw storage scalar.
75    type NativeValue<'a> = &'a ScalarValue;
76
77    fn id(&self) -> ExtId {
78        static ID: CachedId = CachedId::new("vortex.st.linestring");
79        *ID
80    }
81
82    fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
83        Ok(metadata.serialize())
84    }
85
86    fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult<Self::StoredMetadata> {
87        super::SpatialStoredMetadata::deserialize(metadata)
88    }
89
90    fn metadata_from_storage(
91        &self,
92        stored_metadata: Self::StoredMetadata,
93        storage_dtype: &DType,
94    ) -> VortexResult<Self::Metadata> {
95        Ok(SpatialMetadata::from_stored_metadata(
96            stored_metadata,
97            Some(linestring_dimension(storage_dtype)?),
98        ))
99    }
100
101    fn storage_dtype(metadata: &Self::Metadata) -> DType {
102        linestring_storage_dtype(metadata.native_dimension(), Nullability::NonNullable)
103    }
104
105    fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> {
106        metadata.validate_native(LineString.id())
107    }
108
109    fn unpack_native<'a>(
110        _ext_dtype: &'a ExtDType<Self>,
111        storage_value: &'a ScalarValue,
112    ) -> VortexResult<&'a ScalarValue> {
113        Ok(storage_value)
114    }
115}
116
117/// Canonical line-string storage: a list of the coordinate `Struct`.
118pub(crate) fn linestring_storage_dtype(dim: Dimension, nullability: Nullability) -> DType {
119    let coords = coordinate_storage_dtype(dim, Nullability::NonNullable);
120    DType::List(Arc::new(coords), nullability)
121}
122
123/// Infers the coordinate [`Dimension`] of `List<coordinate-struct>` storage.
124///
125/// Checks the list nesting and delegates coordinate field-name inference to
126/// [`coordinate_dimension`]. Reads validate the complete storage dtype against the declaration.
127pub(crate) fn linestring_dimension(dtype: &DType) -> VortexResult<Dimension> {
128    let DType::List(coords, _) = dtype else {
129        vortex_bail!("linestring storage must be a List of coordinates, got {dtype}");
130    };
131    coordinate_dimension(coords)
132}
133
134/// Return one coordinate ordinate, filling an ordinate absent from the point dimension with zero.
135fn point_ordinate(
136    points: &StructArray,
137    dimension: Dimension,
138    name: &str,
139) -> VortexResult<ArrayRef> {
140    if dimension.field_names().contains(&name) {
141        points.unmasked_field_by_name(name).cloned()
142    } else {
143        Ok(ConstantArray::new(0.0f64, points.len()).into_array())
144    }
145}
146
147/// Build one native [`LineString`] per corresponding pair of point coordinate rows.
148pub(crate) fn linestring_array_from_point_pairs(
149    ext_dtype: &ExtDType<LineString>,
150    starts: &StructArray,
151    ends: &StructArray,
152    validity: Validity,
153) -> VortexResult<ArrayRef> {
154    let len = starts.len();
155    vortex_ensure_eq!(
156        len,
157        ends.len(),
158        "spatial: line string point columns must have equal lengths"
159    );
160    let vertex_count = len
161        .checked_mul(2)
162        .ok_or_else(|| vortex_err!("spatial: two-vertex line string length overflow"))?;
163    let last_offset = i32::try_from(vertex_count)
164        .map_err(|_| vortex_err!("spatial: two-vertex line string offset overflow"))?;
165    let row_count = u32::try_from(len)
166        .map_err(|_| vortex_err!("spatial: two-vertex line string row count overflow"))?;
167    let dimension = ext_dtype.metadata().native_dimension();
168    let start_dimension = coordinate_dimension(starts.dtype())?;
169    let end_dimension = coordinate_dimension(ends.dtype())?;
170
171    let array_indices = PrimitiveArray::from_iter((0..len).flat_map(|_| [0u8, 1])).into_array();
172    let row_indices = Buffer::from_iter((0..row_count).flat_map(|row| [row; 2])).into_array();
173
174    let ordinates = dimension
175        .field_names()
176        .iter()
177        .map(|name| {
178            Ok(InterleaveArray::try_new(
179                vec![
180                    point_ordinate(starts, start_dimension, name)?,
181                    point_ordinate(ends, end_dimension, name)?,
182                ],
183                array_indices.clone(),
184                row_indices.clone(),
185            )?
186            .into_array())
187        })
188        .collect::<VortexResult<Vec<_>>>()?;
189
190    let vertices = StructArray::try_new(
191        FieldNames::from(dimension.field_names()),
192        ordinates,
193        vertex_count,
194        Validity::NonNullable,
195    )?
196    .into_array();
197
198    let offsets = Buffer::from_iter((0..=last_offset).step_by(2)).into_array();
199    // SAFETY: each line string has two vertices, so the offsets step by two from zero up to the
200    // vertex count. The validity has one entry per row.
201    let storage = unsafe { ListArray::new_unchecked(vertices, offsets, validity) }.into_array();
202
203    Ok(ExtensionArray::try_new(ext_dtype.clone().erased(), storage)?.into_array())
204}
205
206static ARROW_LINESTRING: CachedId = CachedId::new(LineStringType::NAME);
207
208/// The `geoarrow.linestring` extension type for `dimension`, with separated (struct) coordinates
209/// matching `LineString` storage.
210fn linestring_type(spatial_metadata: &SpatialMetadata, dimension: Dimension) -> LineStringType {
211    LineStringType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
212}
213
214/// Decode `LineString` storage (`List<coordinate>`) to `geo_types` line strings, for the spatial scalar
215/// functions. CRS does not affect planar geometry ops, so default metadata is used.
216pub(crate) fn linestring_geometries(
217    storage: &ArrayRef,
218    ctx: &mut ExecutionCtx,
219) -> VortexResult<Vec<Geometry<f64>>> {
220    linestring_array(storage, ctx)?
221        .iter()
222        .map(|geometry| -> VortexResult<Geometry<f64>> {
223            Ok(geometry
224                .ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
225                .map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
226                .to_geometry())
227        })
228        .collect()
229}
230
231/// Build a geoarrow `LineStringArray` from a `LineString`'s `List<coordinate>` storage.
232fn linestring_array(storage: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<LineStringArray> {
233    let linestring_type = linestring_type(
234        &SpatialMetadata::default(),
235        linestring_dimension(storage.dtype())?,
236    );
237    let arrow = storage.clone().execute_arrow(None, ctx)?;
238    LineStringArray::try_from((arrow.as_ref(), linestring_type))
239        .map_err(|e| vortex_err!("failed to construct LineStringArray: {e}"))
240}
241
242/// A validated `LineString` array (`try_from` checks the extension type).
243pub struct LineStringData(ExtensionArray);
244
245impl TryFrom<ExtensionArray> for LineStringData {
246    type Error = VortexError;
247
248    fn try_from(ext: ExtensionArray) -> Result<Self, Self::Error> {
249        vortex_ensure!(
250            ext.ext_dtype().is::<LineString>(),
251            "expected a LineString extension array"
252        );
253        Ok(LineStringData(ext))
254    }
255}
256
257impl LineStringData {
258    /// Serialize line strings to WKB (a view array) — the form DuckDB `GEOMETRY` takes.
259    pub fn to_wkb(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
260        geoarrow_to_wkb(
261            &linestring_array(self.0.storage_array(), ctx)?,
262            &ctx.session().arrow(),
263        )
264    }
265}
266
267impl ArrowExtVTable for LineString {
268    fn metadata_policy() -> ArrowMetadataPolicy {
269        ArrowMetadataPolicy::ArrowNative
270    }
271
272    fn arrow_ext_id(&self) -> Id {
273        *ARROW_LINESTRING
274    }
275
276    fn to_arrow_field(
277        &self,
278        name: &str,
279        ext_dtype: &ExtDType<Self>,
280        _session: &ArrowSession,
281    ) -> VortexResult<Option<Field>> {
282        let spatial_metadata = ext_dtype.metadata();
283        let dimension = spatial_metadata.native_dimension();
284
285        let arrow_type = linestring_type(spatial_metadata, dimension);
286        let mut field = Field::new(
287            name,
288            arrow_type.data_type(),
289            ext_dtype.storage_dtype().is_nullable(),
290        );
291        field.try_with_extension_type(arrow_type)?;
292
293        Ok(Some(field))
294    }
295
296    fn execute_arrow(
297        &self,
298        array: ArrayRef,
299        target: &Field,
300        options: &ArrowExportOptions,
301        ctx: &mut ExecutionCtx,
302    ) -> VortexResult<ArrowExport> {
303        let Ok(linestring_meta) = target.try_extension_type::<LineStringType>() else {
304            return Ok(ArrowExport::Unsupported(array));
305        };
306        if linestring_meta.coord_type() != CoordType::Separated {
307            return Ok(ArrowExport::Unsupported(array));
308        }
309
310        let executed = array.execute::<ExtensionArray>(ctx)?;
311        let storage = executed.storage_array().clone();
312
313        let storage_field = Field::new(
314            String::new(),
315            target.data_type().clone(),
316            target.is_nullable(),
317        );
318        let arrow_storage =
319            storage.execute_arrow_with_options(Some(&storage_field), options, ctx)?;
320
321        // The validated target already shapes the storage. GeoArrow constructors can panic on
322        // valid Arrow lists that retain unused child values after filtering.
323        Ok(ArrowExport::Exported(arrow_storage))
324    }
325
326    fn from_arrow_field(
327        field: &Field,
328        _session: &ArrowSession,
329    ) -> VortexResult<Option<ExtDType<Self>>> {
330        let linestring_meta = field.try_extension_type::<LineStringType>()?;
331        vortex_ensure!(
332            linestring_meta.coord_type() == CoordType::Separated,
333            "geoarrow.linestring with interleaved coordinates is not supported; \
334             re-encode with separated (struct) coordinates"
335        );
336
337        let metadata = spatial_metadata_from_arrow(linestring_meta.metadata())
338            .with_dimension(linestring_meta.dimension().into());
339        Ok(Some(ExtDType::try_with_vtable(
340            LineString,
341            metadata,
342            field.is_nullable().into(),
343        )?))
344    }
345
346    fn from_arrow_array(
347        array: ArrowArrayRef,
348        _field: &Field,
349        ext_dtype: &ExtDType<Self>,
350        session: &ArrowSession,
351    ) -> VortexResult<ArrowImport> {
352        session
353            .from_arrow_storage(array, &ext_dtype.clone().erased())
354            .map(ArrowImport::Imported)
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use rstest::rstest;
361    use vortex_array::dtype::DType;
362    use vortex_array::dtype::Nullability;
363    use vortex_array::dtype::PType;
364    use vortex_array::dtype::extension::ExtDTypePlugin;
365    use vortex_error::VortexResult;
366
367    use super::LineString;
368    use super::linestring_storage_dtype;
369    use crate::extension::SpatialMetadata;
370    use crate::extension::coordinate::Dimension;
371
372    fn spatial_meta() -> SpatialMetadata {
373        SpatialMetadata::new(Some("EPSG:4326".to_string()))
374    }
375
376    /// `LineString` reads the canonical `List<coordinate-struct>` storage of every dimension.
377    #[rstest]
378    #[case::xy(Dimension::Xy)]
379    #[case::xyz(Dimension::Xyz)]
380    #[case::xym(Dimension::Xym)]
381    #[case::xyzm(Dimension::Xyzm)]
382    fn linestring_reads_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
383        let storage = linestring_storage_dtype(dim, Nullability::NonNullable);
384        LineString.deserialize(&spatial_meta().serialize(), storage)?;
385        Ok(())
386    }
387
388    /// Non-linestring storage fails to read: `f64` is not a list of coordinates.
389    #[test]
390    fn linestring_rejects_invalid_storage() -> VortexResult<()> {
391        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
392        assert!(
393            LineString
394                .deserialize(&spatial_meta().serialize(), primitive)
395                .is_err()
396        );
397        Ok(())
398    }
399}