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//! Native multi-line-string geometry (`vortex.st.multilinestring`).
5//!
6//! [`MultiLineString`] stores line strings as `List<List<Struct<x, y[, z][, m]>>>`.
7//! [`SpatialMetadata`] declares the coordinate dimension and optional coordinate reference system.
8//! Coordinates use non-nullable `f64` fields, and only the outer list can be nullable. The storage
9//! layout matches [`Polygon`](super::Polygon), and the extension ID identifies the geometry type.
10
11use std::sync::Arc;
12
13use arrow_array::ArrayRef as ArrowArrayRef;
14use arrow_schema::Field;
15use arrow_schema::extension::ExtensionType;
16use geo_traits::to_geo::ToGeoGeometry;
17use geo_types::Geometry;
18use geoarrow::array::GeoArrowArrayAccessor;
19use geoarrow::array::MultiLineStringArray;
20use geoarrow::datatypes::CoordType;
21use geoarrow::datatypes::MultiLineStringType;
22use vortex_array::ArrayRef;
23use vortex_array::ExecutionCtx;
24use vortex_array::arrays::ExtensionArray;
25use vortex_array::arrays::extension::ExtensionArrayExt;
26use vortex_array::dtype::DType;
27use vortex_array::dtype::Nullability;
28use vortex_array::dtype::extension::ExtDType;
29use vortex_array::dtype::extension::ExtId;
30use vortex_array::dtype::extension::ExtVTable;
31use vortex_array::scalar::ScalarValue;
32use vortex_arrow::ArrowExport;
33use vortex_arrow::ArrowExportOptions;
34use vortex_arrow::ArrowExtVTable;
35use vortex_arrow::ArrowImport;
36use vortex_arrow::ArrowMetadataPolicy;
37use vortex_arrow::ArrowSession;
38use vortex_arrow::ArrowSessionExt;
39use vortex_arrow::ExecuteArrowExt;
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    type StoredMetadata = super::SpatialStoredMetadata;
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.serialize())
74    }
75
76    fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult<Self::StoredMetadata> {
77        super::SpatialStoredMetadata::deserialize(metadata)
78    }
79
80    fn metadata_from_storage(
81        &self,
82        stored_metadata: Self::StoredMetadata,
83        storage_dtype: &DType,
84    ) -> VortexResult<Self::Metadata> {
85        Ok(SpatialMetadata::from_stored_metadata(
86            stored_metadata,
87            Some(multilinestring_dimension(storage_dtype)?),
88        ))
89    }
90
91    fn storage_dtype(metadata: &Self::Metadata) -> DType {
92        multilinestring_storage_dtype(metadata.native_dimension(), Nullability::NonNullable)
93    }
94
95    fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> {
96        metadata.validate_native(MultiLineString.id())
97    }
98
99    fn unpack_native<'a>(
100        _ext_dtype: &'a ExtDType<Self>,
101        storage_value: &'a ScalarValue,
102    ) -> VortexResult<&'a ScalarValue> {
103        Ok(storage_value)
104    }
105}
106
107/// Canonical multilinestring storage: an outer list of line strings, each a list of the coordinate
108/// `Struct`.
109pub(crate) fn multilinestring_storage_dtype(dim: Dimension, nullability: Nullability) -> DType {
110    let coords = coordinate_storage_dtype(dim, Nullability::NonNullable);
111    let line = DType::List(Arc::new(coords), Nullability::NonNullable);
112    DType::List(Arc::new(line), nullability)
113}
114
115/// Infers the coordinate [`Dimension`] of `List<List<coordinate-struct>>` storage.
116///
117/// Checks the list nesting and delegates coordinate field-name inference to
118/// [`coordinate_dimension`]. Reads validate the complete storage dtype against the declaration.
119pub(crate) fn multilinestring_dimension(dtype: &DType) -> VortexResult<Dimension> {
120    let DType::List(line, _) = dtype else {
121        vortex_bail!("multilinestring storage must be a List of line strings, got {dtype}");
122    };
123    let DType::List(coords, _) = line.as_ref() else {
124        vortex_bail!("multilinestring line storage must be a List of coordinates, got {line}");
125    };
126    coordinate_dimension(coords)
127}
128
129static ARROW_MULTILINESTRING: CachedId = CachedId::new(MultiLineStringType::NAME);
130
131/// The `geoarrow.multilinestring` type for `dimension`, with separated (struct) coordinates.
132fn multilinestring_type(
133    spatial_metadata: &SpatialMetadata,
134    dimension: Dimension,
135) -> MultiLineStringType {
136    MultiLineStringType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
137}
138
139/// Decode storage to `geo_types` for the spatial scalar functions (CRS is irrelevant to planar ops).
140pub(crate) fn multilinestring_geometries(
141    storage: &ArrayRef,
142    ctx: &mut ExecutionCtx,
143) -> VortexResult<Vec<Geometry<f64>>> {
144    multilinestring_array(storage, ctx)?
145        .iter()
146        .map(|geometry| -> VortexResult<Geometry<f64>> {
147            Ok(geometry
148                .ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
149                .map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
150                .to_geometry())
151        })
152        .collect()
153}
154
155/// Build a geoarrow `MultiLineStringArray` from the `MultiLineString` storage.
156fn multilinestring_array(
157    storage: &ArrayRef,
158    ctx: &mut ExecutionCtx,
159) -> VortexResult<MultiLineStringArray> {
160    let multilinestring_type = multilinestring_type(
161        &SpatialMetadata::default(),
162        multilinestring_dimension(storage.dtype())?,
163    );
164    let arrow = storage.clone().execute_arrow(None, ctx)?;
165    MultiLineStringArray::try_from((arrow.as_ref(), multilinestring_type))
166        .map_err(|e| vortex_err!("failed to construct MultiLineStringArray: {e}"))
167}
168
169/// A validated `MultiLineString` array (`try_from` checks the extension type).
170pub struct MultiLineStringData(ExtensionArray);
171
172impl TryFrom<ExtensionArray> for MultiLineStringData {
173    type Error = VortexError;
174
175    fn try_from(ext: ExtensionArray) -> Result<Self, Self::Error> {
176        vortex_ensure!(
177            ext.ext_dtype().is::<MultiLineString>(),
178            "expected a MultiLineString extension array"
179        );
180        Ok(MultiLineStringData(ext))
181    }
182}
183
184impl MultiLineStringData {
185    /// Serialize multilinestrings to WKB (a view array) — the form DuckDB `GEOMETRY` takes.
186    pub fn to_wkb(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
187        geoarrow_to_wkb(
188            &multilinestring_array(self.0.storage_array(), ctx)?,
189            &ctx.session().arrow(),
190        )
191    }
192}
193
194impl ArrowExtVTable for MultiLineString {
195    fn metadata_policy() -> ArrowMetadataPolicy {
196        ArrowMetadataPolicy::ArrowNative
197    }
198
199    fn arrow_ext_id(&self) -> Id {
200        *ARROW_MULTILINESTRING
201    }
202
203    fn to_arrow_field(
204        &self,
205        name: &str,
206        ext_dtype: &ExtDType<Self>,
207        _session: &ArrowSession,
208    ) -> VortexResult<Option<Field>> {
209        let spatial_metadata = ext_dtype.metadata();
210        let dimension = spatial_metadata.native_dimension();
211
212        let arrow_type = multilinestring_type(spatial_metadata, dimension);
213        let mut field = Field::new(
214            name,
215            arrow_type.data_type(),
216            ext_dtype.storage_dtype().is_nullable(),
217        );
218        field.try_with_extension_type(arrow_type)?;
219
220        Ok(Some(field))
221    }
222
223    fn execute_arrow(
224        &self,
225        array: ArrayRef,
226        target: &Field,
227        options: &ArrowExportOptions,
228        ctx: &mut ExecutionCtx,
229    ) -> VortexResult<ArrowExport> {
230        let Ok(multilinestring_meta) = target.try_extension_type::<MultiLineStringType>() else {
231            return Ok(ArrowExport::Unsupported(array));
232        };
233        if multilinestring_meta.coord_type() != CoordType::Separated {
234            return Ok(ArrowExport::Unsupported(array));
235        }
236
237        let executed = array.execute::<ExtensionArray>(ctx)?;
238        let storage = executed.storage_array().clone();
239
240        let storage_field = Field::new(
241            String::new(),
242            target.data_type().clone(),
243            target.is_nullable(),
244        );
245        let arrow_storage =
246            storage.execute_arrow_with_options(Some(&storage_field), options, ctx)?;
247
248        // The validated target already shapes the storage. GeoArrow constructors can panic on
249        // valid Arrow lists that retain unused child values after filtering.
250        Ok(ArrowExport::Exported(arrow_storage))
251    }
252
253    fn from_arrow_field(
254        field: &Field,
255        _session: &ArrowSession,
256    ) -> VortexResult<Option<ExtDType<Self>>> {
257        let multilinestring_meta = field.try_extension_type::<MultiLineStringType>()?;
258        vortex_ensure!(
259            multilinestring_meta.coord_type() == CoordType::Separated,
260            "geoarrow.multilinestring with interleaved coordinates is not supported; \
261             re-encode with separated (struct) coordinates"
262        );
263
264        let metadata = spatial_metadata_from_arrow(multilinestring_meta.metadata())
265            .with_dimension(multilinestring_meta.dimension().into());
266        Ok(Some(ExtDType::try_with_vtable(
267            MultiLineString,
268            metadata,
269            field.is_nullable().into(),
270        )?))
271    }
272
273    fn from_arrow_array(
274        array: ArrowArrayRef,
275        _field: &Field,
276        ext_dtype: &ExtDType<Self>,
277        session: &ArrowSession,
278    ) -> VortexResult<ArrowImport> {
279        session
280            .from_arrow_storage(array, &ext_dtype.clone().erased())
281            .map(ArrowImport::Imported)
282    }
283}
284
285#[cfg(test)]
286mod tests {
287    use std::sync::Arc;
288
289    use rstest::rstest;
290    use vortex_array::dtype::DType;
291    use vortex_array::dtype::Nullability;
292    use vortex_array::dtype::PType;
293    use vortex_array::dtype::extension::ExtDTypePlugin;
294    use vortex_error::VortexResult;
295
296    use super::MultiLineString;
297    use super::multilinestring_storage_dtype;
298    use crate::extension::SpatialMetadata;
299    use crate::extension::coordinate::Dimension;
300    use crate::extension::coordinate::coordinate_storage_dtype;
301
302    fn spatial_meta() -> SpatialMetadata {
303        SpatialMetadata::new(Some("EPSG:4326".to_string()))
304    }
305
306    /// `MultiLineString` reads the canonical `List<List<coordinate-struct>>` storage of every
307    /// dimension.
308    #[rstest]
309    #[case::xy(Dimension::Xy)]
310    #[case::xyz(Dimension::Xyz)]
311    #[case::xym(Dimension::Xym)]
312    #[case::xyzm(Dimension::Xyzm)]
313    fn multilinestring_reads_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
314        let storage = multilinestring_storage_dtype(dim, Nullability::NonNullable);
315        MultiLineString.deserialize(&spatial_meta().serialize(), storage)?;
316        Ok(())
317    }
318
319    /// Non-multilinestring storage fails to read, for example `f64` or a single list (linestring).
320    #[test]
321    fn multilinestring_rejects_invalid_storage() -> VortexResult<()> {
322        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
323        assert!(
324            MultiLineString
325                .deserialize(&spatial_meta().serialize(), primitive)
326                .is_err()
327        );
328
329        // A bare list of coordinates is a single line string, not a multilinestring.
330        let coords = coordinate_storage_dtype(Dimension::Xy, Nullability::NonNullable);
331        let line = DType::List(Arc::new(coords), Nullability::NonNullable);
332        assert!(
333            MultiLineString
334                .deserialize(&spatial_meta().serialize(), line)
335                .is_err()
336        );
337        Ok(())
338    }
339}