Skip to main content

vortex_spatial/extension/
multilinestring.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! The [`MultiLineString`] extension type (`vortex.st.multilinestring`), stored as
5//! `List<List<Struct<x, y[, z][, m]>>>` (line strings → coordinates) and tagged with
6//! [`SpatialMetadata`]. The storage layout matches [`Polygon`](super::Polygon); the two are
7//! distinguished by their GeoArrow extension name, not their shape.
8
9use std::sync::Arc;
10
11use arrow_array::ArrayRef as ArrowArrayRef;
12use arrow_schema::DataType;
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::IntoArrow;
19use geoarrow::array::MultiLineStringArray;
20use geoarrow::datatypes::CoordType;
21use geoarrow::datatypes::MultiLineStringType;
22use prost::Message;
23use vortex_array::ArrayRef;
24use vortex_array::ExecutionCtx;
25use vortex_array::IntoArray;
26use vortex_array::arrays::ExtensionArray;
27use vortex_array::arrays::extension::ExtensionArrayExt;
28use vortex_array::dtype::DType;
29use vortex_array::dtype::Nullability;
30use vortex_array::dtype::extension::ExtDType;
31use vortex_array::dtype::extension::ExtId;
32use vortex_array::dtype::extension::ExtVTable;
33use vortex_array::scalar::ScalarValue;
34use vortex_arrow::ArrowExport;
35use vortex_arrow::ArrowExportVTable;
36use vortex_arrow::ArrowImport;
37use vortex_arrow::ArrowImportVTable;
38use vortex_arrow::ArrowSession;
39use vortex_arrow::ArrowSessionExt;
40use vortex_error::VortexError;
41use vortex_error::VortexResult;
42use vortex_error::vortex_bail;
43use vortex_error::vortex_ensure;
44use vortex_error::vortex_err;
45use vortex_session::registry::CachedId;
46use vortex_session::registry::Id;
47
48use super::SpatialMetadata;
49use super::coordinate::Dimension;
50use super::coordinate::coordinate_dimension;
51use super::coordinate::coordinate_storage_dtype;
52use super::geoarrow_metadata;
53use super::geoarrow_to_wkb;
54use super::spatial_metadata_from_arrow;
55
56/// A multilinestring: `geoarrow.multilinestring`, stored as `List<List<Struct<x, y[, z][, m]>>>`
57/// (line strings of vertices).
58#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
59pub struct MultiLineString;
60
61impl ExtVTable for MultiLineString {
62    type Metadata = SpatialMetadata;
63    // No cheap owned value like Point's `Coordinate`; expose the raw storage scalar.
64    type NativeValue<'a> = &'a ScalarValue;
65
66    fn id(&self) -> ExtId {
67        static ID: CachedId = CachedId::new("vortex.st.multilinestring");
68        *ID
69    }
70
71    fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
72        Ok(metadata.encode_to_vec())
73    }
74
75    fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult<Self::Metadata> {
76        Ok(SpatialMetadata::decode(metadata)?)
77    }
78
79    fn validate_dtype(ext_dtype: &ExtDType<Self>) -> VortexResult<()> {
80        multilinestring_dimension(ext_dtype.storage_dtype()).map(|_| ())
81    }
82
83    fn unpack_native<'a>(
84        _ext_dtype: &'a ExtDType<Self>,
85        storage_value: &'a ScalarValue,
86    ) -> VortexResult<&'a ScalarValue> {
87        Ok(storage_value)
88    }
89}
90
91/// Canonical multilinestring storage: an outer list of line strings, each a list of the coordinate
92/// `Struct`.
93pub(crate) fn multilinestring_storage_dtype(dim: Dimension, nullability: Nullability) -> DType {
94    let coords = coordinate_storage_dtype(dim, Nullability::NonNullable);
95    let line = DType::List(Arc::new(coords), Nullability::NonNullable);
96    DType::List(Arc::new(line), nullability)
97}
98
99/// Validate `dtype` is `List<List<coordinate-struct>>` and return its [`Dimension`].
100pub(crate) fn multilinestring_dimension(dtype: &DType) -> VortexResult<Dimension> {
101    let DType::List(line, _) = dtype else {
102        vortex_bail!("multilinestring storage must be a List of line strings, was {dtype}");
103    };
104    let DType::List(coords, _) = line.as_ref() else {
105        vortex_bail!("multilinestring line storage must be a List of coordinates, was {line}");
106    };
107    coordinate_dimension(coords)
108}
109
110static ARROW_MULTILINESTRING: CachedId = CachedId::new(MultiLineStringType::NAME);
111
112/// The `geoarrow.multilinestring` type for `dimension`, with separated (struct) coordinates.
113fn multilinestring_type(
114    spatial_metadata: &SpatialMetadata,
115    dimension: Dimension,
116) -> MultiLineStringType {
117    MultiLineStringType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
118}
119
120/// Decode storage to `geo_types` for the spatial scalar functions (CRS is irrelevant to planar ops).
121pub(crate) fn multilinestring_geometries(
122    storage: &ArrayRef,
123    ctx: &mut ExecutionCtx,
124) -> VortexResult<Vec<Geometry<f64>>> {
125    multilinestring_array(storage, ctx)?
126        .iter()
127        .map(|geometry| -> VortexResult<Geometry<f64>> {
128            Ok(geometry
129                .ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
130                .map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
131                .to_geometry())
132        })
133        .collect()
134}
135
136/// Build a geoarrow `MultiLineStringArray` from the `MultiLineString` storage.
137fn multilinestring_array(
138    storage: &ArrayRef,
139    ctx: &mut ExecutionCtx,
140) -> VortexResult<MultiLineStringArray> {
141    let multilinestring_type = multilinestring_type(
142        &SpatialMetadata::default(),
143        multilinestring_dimension(storage.dtype())?,
144    );
145    let session = ctx.session().clone();
146    let arrow = session.arrow().execute_arrow(storage.clone(), None, ctx)?;
147    MultiLineStringArray::try_from((arrow.as_ref(), multilinestring_type))
148        .map_err(|e| vortex_err!("failed to construct MultiLineStringArray: {e}"))
149}
150
151/// A validated `MultiLineString` array (`try_from` checks the extension type).
152pub struct MultiLineStringData(ExtensionArray);
153
154impl TryFrom<ExtensionArray> for MultiLineStringData {
155    type Error = VortexError;
156
157    fn try_from(ext: ExtensionArray) -> Result<Self, Self::Error> {
158        vortex_ensure!(
159            ext.ext_dtype().is::<MultiLineString>(),
160            "expected a MultiLineString extension array"
161        );
162        Ok(MultiLineStringData(ext))
163    }
164}
165
166impl MultiLineStringData {
167    /// Serialize multilinestrings to WKB (a view array) — the form DuckDB `GEOMETRY` takes.
168    pub fn to_wkb(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
169        geoarrow_to_wkb(
170            &multilinestring_array(self.0.storage_array(), ctx)?,
171            &ctx.session().arrow(),
172        )
173    }
174}
175
176impl ArrowExportVTable for MultiLineString {
177    fn arrow_ext_id(&self) -> Id {
178        *ARROW_MULTILINESTRING
179    }
180
181    fn vortex_id(&self) -> Id {
182        self.id()
183    }
184
185    fn to_arrow_field(
186        &self,
187        name: &str,
188        dtype: &DType,
189        session: &ArrowSession,
190    ) -> VortexResult<Option<Field>> {
191        let ext_type = dtype.as_extension();
192        let spatial_metadata = ext_type.metadata::<MultiLineString>();
193        let dimension = multilinestring_dimension(ext_type.storage_dtype())?;
194
195        let mut field = session.to_arrow_field(name, ext_type.storage_dtype())?;
196        field.try_with_extension_type(multilinestring_type(spatial_metadata, dimension))?;
197
198        Ok(Some(field))
199    }
200
201    fn execute_arrow(
202        &self,
203        array: ArrayRef,
204        target: &Field,
205        ctx: &mut ExecutionCtx,
206    ) -> VortexResult<ArrowExport> {
207        let is_multilinestring = array
208            .dtype()
209            .as_extension_opt()
210            .map(|ext| ext.is::<MultiLineString>())
211            .unwrap_or(false);
212        if !is_multilinestring {
213            return Ok(ArrowExport::Unsupported(array));
214        }
215
216        let Ok(multilinestring_meta) = target.try_extension_type::<MultiLineStringType>() else {
217            return Ok(ArrowExport::Unsupported(array));
218        };
219        if multilinestring_meta.coord_type() != CoordType::Separated {
220            return Ok(ArrowExport::Unsupported(array));
221        }
222
223        let executed = array.execute::<ExtensionArray>(ctx)?;
224        let storage = executed.storage_array().clone();
225
226        let storage_field = Field::new(
227            String::new(),
228            target.data_type().clone(),
229            target.is_nullable(),
230        );
231        let session = ctx.session().clone();
232        let arrow_storage = session
233            .arrow()
234            .execute_arrow(storage, Some(&storage_field), ctx)?;
235
236        let multilinestrings =
237            MultiLineStringArray::try_from((arrow_storage.as_ref(), multilinestring_meta))
238                .map_err(|e| vortex_err!("failed to construct MultiLineStringArray: {e}"))?;
239
240        Ok(ArrowExport::Exported(Arc::new(
241            multilinestrings.into_arrow(),
242        )))
243    }
244}
245
246impl ArrowImportVTable for MultiLineString {
247    fn arrow_ext_id(&self) -> Id {
248        *ARROW_MULTILINESTRING
249    }
250
251    /// Import a `geoarrow.multilinestring` field (matched by GeoArrow name). Accepts the full
252    /// `MultiLineStringType`, or a metadata-less literal (name only), inferring the dimension.
253    fn from_arrow_field(
254        &self,
255        field: &Field,
256        session: &ArrowSession,
257    ) -> VortexResult<Option<DType>> {
258        let (dimension, metadata) =
259            if let Ok(multilinestring_meta) = field.try_extension_type::<MultiLineStringType>() {
260                vortex_ensure!(
261                    multilinestring_meta.coord_type() == CoordType::Separated,
262                    "geoarrow.multilinestring with interleaved coordinates is not supported; \
263                 re-encode with separated (struct) coordinates"
264                );
265                (
266                    multilinestring_meta.dimension().into(),
267                    spatial_metadata_from_arrow(multilinestring_meta.metadata()),
268                )
269            } else {
270                // Literal: peel the two `List` layers to the coordinate struct and read its dimension
271                // from the field names (the canonical check rejects nullable coordinates).
272                if field.extension_type_name() != Some(MultiLineStringType::NAME) {
273                    return Ok(None);
274                }
275                let Ok(DType::List(line, _)) =
276                    session.from_arrow_datatype(field.data_type(), field.is_nullable().into())
277                else {
278                    return Ok(None);
279                };
280                let DType::List(coords, _) = line.as_ref() else {
281                    return Ok(None);
282                };
283                let DType::Struct(fields, _) = coords.as_ref() else {
284                    return Ok(None);
285                };
286                let Ok(dimension) = Dimension::from_field_names(fields.names()) else {
287                    return Ok(None);
288                };
289                (dimension, SpatialMetadata::default())
290            };
291
292        let storage_dtype = multilinestring_storage_dtype(dimension, field.is_nullable().into());
293        Ok(Some(DType::Extension(
294            ExtDType::try_with_vtable(MultiLineString, metadata, storage_dtype)?.erased(),
295        )))
296    }
297
298    fn from_arrow_array(
299        &self,
300        array: ArrowArrayRef,
301        field: &Field,
302        dtype: &DType,
303        session: &ArrowSession,
304    ) -> VortexResult<ArrowImport> {
305        let Some(ext_dtype) = dtype.as_extension_opt() else {
306            return Ok(ArrowImport::Unsupported(array));
307        };
308        if !ext_dtype.is::<MultiLineString>()
309            || field.try_extension_type::<MultiLineStringType>().is_err()
310            || !matches!(array.data_type(), DataType::List(_))
311        {
312            return Ok(ArrowImport::Unsupported(array));
313        }
314
315        let storage = session.from_arrow_array(array, field.is_nullable())?;
316        Ok(ArrowImport::Imported(
317            ExtensionArray::try_new(ext_dtype.clone(), storage)?.into_array(),
318        ))
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use std::sync::Arc;
325
326    use rstest::rstest;
327    use vortex_array::dtype::DType;
328    use vortex_array::dtype::Nullability;
329    use vortex_array::dtype::PType;
330    use vortex_array::dtype::extension::ExtDType;
331    use vortex_error::VortexResult;
332
333    use super::MultiLineString;
334    use super::multilinestring_storage_dtype;
335    use crate::extension::SpatialMetadata;
336    use crate::extension::coordinate::Dimension;
337    use crate::extension::coordinate::coordinate_storage_dtype;
338
339    fn spatial_meta() -> SpatialMetadata {
340        SpatialMetadata {
341            crs: Some("EPSG:4326".to_string()),
342        }
343    }
344
345    /// `MultiLineString` accepts the canonical `List<List<coordinate-struct>>` storage of every
346    /// dimension.
347    #[rstest]
348    #[case::xy(Dimension::Xy)]
349    #[case::xyz(Dimension::Xyz)]
350    #[case::xym(Dimension::Xym)]
351    #[case::xyzm(Dimension::Xyzm)]
352    fn multilinestring_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
353        let storage = multilinestring_storage_dtype(dim, Nullability::NonNullable);
354        ExtDType::<MultiLineString>::try_new(spatial_meta(), storage)?;
355        Ok(())
356    }
357
358    /// Non-multilinestring storage is rejected: a bare coordinate struct (point) fails.
359    #[test]
360    fn multilinestring_rejects_invalid_storage() -> VortexResult<()> {
361        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
362        assert!(ExtDType::<MultiLineString>::try_new(spatial_meta(), primitive).is_err());
363
364        // A bare list of coordinates is a single line string, not a multilinestring.
365        let coords = coordinate_storage_dtype(Dimension::Xy, Nullability::NonNullable);
366        let line = DType::List(Arc::new(coords), Nullability::NonNullable);
367        assert!(ExtDType::<MultiLineString>::try_new(spatial_meta(), line).is_err());
368        Ok(())
369    }
370}