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