Skip to main content

vortex_spatial/scalar_fn/
length.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! `ST_Length`: planar (Euclidean) length of native lineal geometries.
5
6use vortex_array::ArrayRef;
7use vortex_array::ExecutionCtx;
8use vortex_array::IntoArray;
9use vortex_array::arrays::ConstantArray;
10use vortex_array::arrays::ExtensionArray;
11use vortex_array::arrays::ListArray;
12use vortex_array::arrays::ListViewArray;
13use vortex_array::arrays::PrimitiveArray;
14use vortex_array::arrays::ScalarFnArray;
15use vortex_array::arrays::StructArray;
16use vortex_array::arrays::extension::ExtensionArrayExt;
17use vortex_array::arrays::list::ListArraySlotsExt;
18use vortex_array::arrays::listview::list_from_list_view;
19use vortex_array::builtins::ArrayBuiltins;
20use vortex_array::dtype::DType;
21use vortex_array::dtype::Nullability;
22use vortex_array::dtype::PType;
23use vortex_array::scalar_fn::Arity;
24use vortex_array::scalar_fn::ChildName;
25use vortex_array::scalar_fn::EmptyOptions;
26use vortex_array::scalar_fn::ExecutionArgs;
27use vortex_array::scalar_fn::ScalarFnId;
28use vortex_array::scalar_fn::ScalarFnVTable;
29use vortex_array::scalar_fn::TypedScalarFnInstance;
30use vortex_array::validity::Validity;
31use vortex_buffer::Buffer;
32use vortex_error::VortexResult;
33use vortex_error::vortex_ensure;
34use vortex_error::vortex_ensure_eq;
35use vortex_error::vortex_err;
36use vortex_session::VortexSession;
37use vortex_session::registry::CachedId;
38
39use crate::extension::LineString;
40use crate::extension::MultiLineString;
41use crate::extension::coordinate::ordinates;
42use crate::extension::flatten_row_offsets;
43use crate::scalar_fn::execute::Execution;
44use crate::scalar_fn::execute::Operand;
45use crate::scalar_fn::execute::dispatch_unary;
46
47/// Validate the native lineal operand accepted by `ST_Length`.
48fn validate_length_operands(dtypes: &[DType]) -> VortexResult<()> {
49    vortex_ensure_eq!(
50        dtypes.len(),
51        1,
52        "spatial: length requires exactly one lineal operand"
53    );
54    vortex_ensure!(
55        dtypes[0].as_extension_opt().is_some_and(|extension| {
56            extension.is::<LineString>() || extension.is::<MultiLineString>()
57        }),
58        "spatial: length operand {} is not a native LineString or MultiLineString",
59        dtypes[0]
60    );
61    Ok(())
62}
63
64fn list_offsets(list: &ListArray, ctx: &mut ExecutionCtx) -> VortexResult<Vec<usize>> {
65    list.offsets()
66        .clone()
67        .cast(DType::Primitive(PType::U64, Nullability::NonNullable))?
68        .execute::<Buffer<u64>>(ctx)?
69        .iter()
70        .map(|&offset| {
71            usize::try_from(offset).map_err(|_| vortex_err!("spatial: list offset exceeds usize"))
72        })
73        .collect()
74}
75
76fn linestring_length(xs: &[f64], ys: &[f64]) -> f64 {
77    xs.windows(2)
78        .zip(ys.windows(2))
79        .map(|(x, y)| (x[1] - x[0]).hypot(y[1] - y[0]))
80        .fold(0.0, |length, segment| length + segment)
81}
82
83fn linestring_lengths(storage: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Buffer<f64>> {
84    let (row_offsets, coords) = flatten_row_offsets(storage, ctx)?;
85    let xs = ordinates(&coords, "x", ctx)?;
86    let ys = ordinates(&coords, "y", ctx)?;
87    Ok(Buffer::from_iter(row_offsets.windows(2).map(|offsets| {
88        linestring_length(&xs[offsets[0]..offsets[1]], &ys[offsets[0]..offsets[1]])
89    })))
90}
91
92fn multilinestring_lengths(storage: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Buffer<f64>> {
93    let rows = list_from_list_view(storage.execute::<ListViewArray>(ctx)?, ctx)?;
94    let row_offsets = list_offsets(&rows, ctx)?;
95    let lines = list_from_list_view(rows.elements().clone().execute::<ListViewArray>(ctx)?, ctx)?;
96    let line_offsets = list_offsets(&lines, ctx)?;
97    let coords = lines.elements().clone().execute::<StructArray>(ctx)?;
98    let xs = ordinates(&coords, "x", ctx)?;
99    let ys = ordinates(&coords, "y", ctx)?;
100
101    Ok(Buffer::from_iter(row_offsets.windows(2).map(|row| {
102        line_offsets[row[0]..=row[1]]
103            .windows(2)
104            .map(|line| linestring_length(&xs[line[0]..line[1]], &ys[line[0]..line[1]]))
105            .fold(0.0, |length, line| length + line)
106    })))
107}
108
109/// Compute planar lengths directly over native lineal offsets and coordinate buffers.
110fn length_array(
111    array: ArrayRef,
112    validity: Validity,
113    ctx: &mut ExecutionCtx,
114) -> VortexResult<ArrayRef> {
115    let is_linestring = array
116        .dtype()
117        .as_extension_opt()
118        .is_some_and(|extension| extension.is::<LineString>());
119    let storage = array
120        .execute::<ExtensionArray>(ctx)?
121        .storage_array()
122        .clone();
123    let lengths = if is_linestring {
124        linestring_lengths(storage, ctx)?
125    } else {
126        multilinestring_lengths(storage, ctx)?
127    };
128    Ok(PrimitiveArray::new(lengths, validity).into_array())
129}
130
131/// Execute length after shared constant/column and null dispatch.
132fn execute_length(
133    execution: Execution<1, Validity>,
134    ctx: &mut ExecutionCtx,
135) -> VortexResult<ArrayRef> {
136    match execution.operands {
137        [Operand::Constant(line)] => {
138            let validity = Validity::from(execution.nullability);
139            let one = length_array(ConstantArray::new(line, 1).into_array(), validity, ctx)?;
140            Ok(ConstantArray::new(one.execute_scalar(0, ctx)?, execution.len).into_array())
141        }
142        [Operand::Column(lines)] => length_array(lines, execution.valid, ctx),
143    }
144}
145
146/// Planar (Euclidean) `ST_Length` (no geodesic correction) of native lineal geometries.
147#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
148pub struct SpatialLength;
149
150impl SpatialLength {
151    /// A lazy `ScalarFnArray` computing the per-row length of a lineal geometry operand.
152    pub fn try_new(array: ArrayRef) -> VortexResult<ScalarFnArray> {
153        ScalarFnArray::try_new(
154            TypedScalarFnInstance::new(SpatialLength, EmptyOptions).erased(),
155            vec![array],
156        )
157    }
158}
159
160impl ScalarFnVTable for SpatialLength {
161    type Options = EmptyOptions;
162
163    fn id(&self) -> ScalarFnId {
164        static ID: CachedId = CachedId::new("vortex.st.length");
165        *ID
166    }
167
168    fn serialize(&self, _: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
169        Ok(Some(vec![]))
170    }
171
172    fn deserialize(&self, _: &[u8], _: &VortexSession) -> VortexResult<Self::Options> {
173        Ok(EmptyOptions)
174    }
175
176    fn arity(&self, _: &Self::Options) -> Arity {
177        Arity::Exact(1)
178    }
179
180    fn child_name(&self, _: &Self::Options, child_idx: usize) -> ChildName {
181        match child_idx {
182            0 => ChildName::from("geometry"),
183            _ => unreachable!("length has exactly one child"),
184        }
185    }
186
187    fn return_dtype(&self, _: &Self::Options, dtypes: &[DType]) -> VortexResult<DType> {
188        validate_length_operands(dtypes)?;
189        Ok(DType::Primitive(PType::F64, dtypes[0].nullability()))
190    }
191
192    fn execute(
193        &self,
194        _: &Self::Options,
195        args: &dyn ExecutionArgs,
196        ctx: &mut ExecutionCtx,
197    ) -> VortexResult<ArrayRef> {
198        let array = args.get(0)?;
199        dispatch_unary(
200            &array,
201            DType::Primitive(PType::F64, array.dtype().nullability()),
202            execute_length,
203            ctx,
204        )
205    }
206
207    fn is_strict(&self, _: &Self::Options) -> bool {
208        true
209    }
210
211    fn is_infallible(&self, _: &Self::Options) -> bool {
212        true
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use vortex_array::ArrayRef;
219    use vortex_array::Columnar;
220    use vortex_array::ExecutionCtx;
221    use vortex_array::IntoArray;
222    use vortex_array::VortexSessionExecute;
223    use vortex_array::arrays::ConstantArray;
224    use vortex_array::arrays::MaskedArray;
225    use vortex_array::arrays::PrimitiveArray;
226    use vortex_array::assert_arrays_eq;
227    use vortex_array::dtype::DType;
228    use vortex_array::dtype::Nullability;
229    use vortex_array::dtype::PType;
230    use vortex_array::scalar::Scalar;
231    use vortex_array::scalar_fn::EmptyOptions;
232    use vortex_array::scalar_fn::ScalarFnVTable;
233    use vortex_array::validity::Validity;
234    use vortex_error::VortexResult;
235    use vortex_error::vortex_err;
236
237    use super::SpatialLength;
238    use crate::test_harness::linestring_column;
239    use crate::test_harness::multilinestring_column;
240    use crate::test_harness::point_column;
241
242    fn line_constant(
243        line: Vec<(f64, f64)>,
244        len: usize,
245        ctx: &mut ExecutionCtx,
246    ) -> VortexResult<ArrayRef> {
247        let scalar = linestring_column(vec![line])?.execute_scalar(0, ctx)?;
248        Ok(ConstantArray::new(scalar, len).into_array())
249    }
250
251    #[test]
252    fn measures_each_linestring() -> VortexResult<()> {
253        let session = vortex_array::array_session();
254        let mut ctx = session.create_execution_ctx();
255        let lines = linestring_column(vec![
256            vec![(0.0, 0.0), (3.0, 4.0)],
257            vec![(0.0, 0.0), (3.0, 4.0), (3.0, 8.0)],
258            vec![(1.0, 2.0)],
259            vec![],
260        ])?;
261
262        let lengths = SpatialLength::try_new(lines)?.into_array();
263        let expected = PrimitiveArray::from_iter([5.0f64, 9.0, 0.0, 0.0]).into_array();
264
265        assert_arrays_eq!(lengths, expected, &mut ctx);
266        Ok(())
267    }
268
269    #[test]
270    fn measures_each_multilinestring() -> VortexResult<()> {
271        let session = vortex_array::array_session();
272        let mut ctx = session.create_execution_ctx();
273        let lines = multilinestring_column(vec![
274            vec![
275                vec![(0.0, 0.0), (3.0, 4.0)],
276                vec![(10.0, 10.0), (10.0, 14.0)],
277            ],
278            vec![],
279            vec![vec![], vec![(1.0, 2.0)], vec![(0.0, 0.0), (0.0, 5.0)]],
280        ])?;
281
282        let lengths = SpatialLength::try_new(lines)?.into_array();
283        let expected = PrimitiveArray::from_iter([9.0f64, 0.0, 5.0]).into_array();
284
285        assert_arrays_eq!(lengths, expected, &mut ctx);
286        Ok(())
287    }
288
289    #[test]
290    fn propagates_nullable_multilinestring_rows() -> VortexResult<()> {
291        let session = vortex_array::array_session();
292        let mut ctx = session.create_execution_ctx();
293        let lines = MaskedArray::try_new(
294            multilinestring_column(vec![
295                vec![vec![(0.0, 0.0), (3.0, 4.0)]],
296                vec![vec![(0.0, 0.0), (1.0, 1.0)]],
297                vec![vec![(0.0, 0.0), (0.0, 5.0)]],
298            ])?,
299            Validity::from_iter([true, false, true]),
300        )?
301        .into_array();
302
303        let expected = PrimitiveArray::new(
304            vec![5.0, 0.0, 5.0],
305            Validity::from_iter([true, false, true]),
306        )
307        .into_array();
308        let lengths = SpatialLength::try_new(lines)?.into_array();
309
310        assert_arrays_eq!(lengths, expected, &mut ctx);
311        Ok(())
312    }
313
314    #[test]
315    fn constant_is_computed_once_and_remains_constant() -> VortexResult<()> {
316        let session = vortex_array::array_session();
317        let mut ctx = session.create_execution_ctx();
318        let lines = line_constant(vec![(0.0, 0.0), (3.0, 4.0), (3.0, 8.0)], 3, &mut ctx)?;
319
320        let result = SpatialLength::try_new(lines)?
321            .into_array()
322            .execute::<Columnar>(&mut ctx)?;
323        let Columnar::Constant(lengths) = result else {
324            return Err(vortex_err!("length of a constant should remain constant"));
325        };
326        assert_eq!(lengths.len(), 3);
327        assert_eq!(f64::try_from(lengths.scalar())?, 9.0);
328        Ok(())
329    }
330
331    #[test]
332    fn null_constant_is_all_null() -> VortexResult<()> {
333        let session = vortex_array::array_session();
334        let mut ctx = session.create_execution_ctx();
335        let dtype = linestring_column(vec![vec![]])?.dtype().as_nullable();
336        let lines = ConstantArray::new(Scalar::null(dtype), 2).into_array();
337
338        let result = SpatialLength::try_new(lines)?
339            .into_array()
340            .execute::<Columnar>(&mut ctx)?;
341        let Columnar::Constant(lengths) = result else {
342            return Err(vortex_err!(
343                "length of a null constant should remain constant"
344            ));
345        };
346        assert_eq!(lengths.len(), 2);
347        assert!(lengths.scalar().is_null());
348        Ok(())
349    }
350
351    #[test]
352    fn propagates_nullable_rows() -> VortexResult<()> {
353        let session = vortex_array::array_session();
354        let mut ctx = session.create_execution_ctx();
355        let lines = MaskedArray::try_new(
356            linestring_column(vec![
357                vec![(0.0, 0.0), (3.0, 4.0)],
358                vec![(0.0, 0.0), (1.0, 1.0)],
359                vec![(0.0, 0.0), (0.0, 4.0)],
360            ])?,
361            Validity::from_iter([true, false, true]),
362        )?
363        .into_array();
364
365        let expected = PrimitiveArray::new(
366            vec![5.0, 0.0, 4.0],
367            Validity::from_iter([true, false, true]),
368        )
369        .into_array();
370        let lengths = SpatialLength::try_new(lines)?.into_array();
371        assert_arrays_eq!(lengths, expected, &mut ctx);
372        Ok(())
373    }
374
375    #[test]
376    fn propagates_all_null_rows() -> VortexResult<()> {
377        let session = vortex_array::array_session();
378        let mut ctx = session.create_execution_ctx();
379        let lines = MaskedArray::try_new(
380            linestring_column(vec![
381                vec![(0.0, 0.0), (3.0, 4.0)],
382                vec![(0.0, 0.0), (0.0, 4.0)],
383            ])?,
384            Validity::from_iter([false, false]),
385        )?
386        .into_array();
387        let expected =
388            PrimitiveArray::new(vec![0.0, 0.0], Validity::from_iter([false, false])).into_array();
389
390        let lengths = SpatialLength::try_new(lines)?.into_array();
391
392        assert_arrays_eq!(lengths, expected, &mut ctx);
393        Ok(())
394    }
395
396    #[test]
397    fn rejects_non_lineal_dtype() -> VortexResult<()> {
398        let point = point_column(vec![0.0], vec![0.0])?;
399        assert!(
400            SpatialLength
401                .return_dtype(&EmptyOptions, std::slice::from_ref(point.dtype()))
402                .is_err()
403        );
404        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
405        assert!(
406            SpatialLength
407                .return_dtype(&EmptyOptions, &[primitive])
408                .is_err()
409        );
410        Ok(())
411    }
412}