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