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 line strings.
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::PrimitiveArray;
12use vortex_array::arrays::ScalarFnArray;
13use vortex_array::arrays::extension::ExtensionArrayExt;
14use vortex_array::dtype::DType;
15use vortex_array::dtype::PType;
16use vortex_array::expr::Expression;
17use vortex_array::expr::union_child_validities;
18use vortex_array::scalar_fn::Arity;
19use vortex_array::scalar_fn::ChildName;
20use vortex_array::scalar_fn::EmptyOptions;
21use vortex_array::scalar_fn::ExecutionArgs;
22use vortex_array::scalar_fn::ScalarFnId;
23use vortex_array::scalar_fn::ScalarFnVTable;
24use vortex_array::scalar_fn::TypedScalarFnInstance;
25use vortex_array::validity::Validity;
26use vortex_buffer::Buffer;
27use vortex_error::VortexResult;
28use vortex_error::vortex_ensure;
29use vortex_session::VortexSession;
30use vortex_session::registry::CachedId;
31
32use crate::extension::LineString;
33use crate::extension::coordinate::ordinates;
34use crate::extension::flatten_row_offsets;
35use crate::scalar_fn::execute::Execution;
36use crate::scalar_fn::execute::Operand;
37use crate::scalar_fn::execute::dispatch_unary;
38
39/// Validate the native line-string operand accepted by `ST_Length`.
40fn validate_length_operands(dtypes: &[DType]) -> VortexResult<()> {
41    vortex_ensure!(
42        dtypes.len() == 1,
43        "spatial: length requires exactly one line string operand, got {}",
44        dtypes.len()
45    );
46    vortex_ensure!(
47        dtypes[0]
48            .as_extension_opt()
49            .is_some_and(|extension| extension.is::<LineString>()),
50        "spatial: length operand {} is not a native line string",
51        dtypes[0]
52    );
53    Ok(())
54}
55
56/// Compute planar lengths directly over native line-string offsets and coordinate buffers.
57fn length_array(
58    array: ArrayRef,
59    validity: Validity,
60    ctx: &mut ExecutionCtx,
61) -> VortexResult<ArrayRef> {
62    let storage = array
63        .execute::<ExtensionArray>(ctx)?
64        .storage_array()
65        .clone();
66    let (row_offsets, coords) = flatten_row_offsets(storage, ctx)?;
67    let xs = ordinates(&coords, "x", ctx)?;
68    let ys = ordinates(&coords, "y", ctx)?;
69    let lengths = Buffer::from_iter(row_offsets.iter().zip(&row_offsets[1..]).map(
70        |(&start, &end)| {
71            xs[start..end]
72                .windows(2)
73                .zip(ys[start..end].windows(2))
74                .map(|(x, y)| (x[1] - x[0]).hypot(y[1] - y[0]))
75                .fold(0.0, |length, segment| length + segment)
76        },
77    ));
78    Ok(PrimitiveArray::new(lengths, validity).into_array())
79}
80
81/// Execute length after shared constant/column and null dispatch.
82fn execute_length(
83    execution: Execution<1, Validity>,
84    ctx: &mut ExecutionCtx,
85) -> VortexResult<ArrayRef> {
86    match execution.operands {
87        [Operand::Constant(line)] => {
88            let validity = Validity::from(execution.nullability);
89            let one = length_array(ConstantArray::new(line, 1).into_array(), validity, ctx)?;
90            Ok(ConstantArray::new(one.execute_scalar(0, ctx)?, execution.len).into_array())
91        }
92        [Operand::Column(lines)] => length_array(lines, execution.valid, ctx),
93    }
94}
95
96/// Planar (Euclidean) `ST_Length` (no geodesic correction) of native line strings.
97#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
98pub struct SpatialLength;
99
100impl SpatialLength {
101    /// A lazy `ScalarFnArray` computing the per-row length of a line string operand.
102    pub fn try_new(array: ArrayRef) -> VortexResult<ScalarFnArray> {
103        ScalarFnArray::try_new(
104            TypedScalarFnInstance::new(SpatialLength, EmptyOptions).erased(),
105            vec![array],
106        )
107    }
108}
109
110impl ScalarFnVTable for SpatialLength {
111    type Options = EmptyOptions;
112
113    fn id(&self) -> ScalarFnId {
114        static ID: CachedId = CachedId::new("vortex.st.length");
115        *ID
116    }
117
118    fn serialize(&self, _: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
119        Ok(Some(vec![]))
120    }
121
122    fn deserialize(&self, _: &[u8], _: &VortexSession) -> VortexResult<Self::Options> {
123        Ok(EmptyOptions)
124    }
125
126    fn arity(&self, _: &Self::Options) -> Arity {
127        Arity::Exact(1)
128    }
129
130    fn child_name(&self, _: &Self::Options, child_idx: usize) -> ChildName {
131        match child_idx {
132            0 => ChildName::from("geometry"),
133            _ => unreachable!("length has exactly one child"),
134        }
135    }
136
137    fn return_dtype(&self, _: &Self::Options, dtypes: &[DType]) -> VortexResult<DType> {
138        validate_length_operands(dtypes)?;
139        Ok(DType::Primitive(PType::F64, dtypes[0].nullability()))
140    }
141
142    fn execute(
143        &self,
144        _: &Self::Options,
145        args: &dyn ExecutionArgs,
146        ctx: &mut ExecutionCtx,
147    ) -> VortexResult<ArrayRef> {
148        let array = args.get(0)?;
149        dispatch_unary(
150            &array,
151            DType::Primitive(PType::F64, array.dtype().nullability()),
152            execute_length,
153            ctx,
154        )
155    }
156
157    fn validity(
158        &self,
159        _: &Self::Options,
160        expression: &Expression,
161    ) -> VortexResult<Option<Expression>> {
162        union_child_validities(expression)
163    }
164
165    fn is_strict(&self, _: &Self::Options) -> bool {
166        true
167    }
168
169    fn is_infallible(&self, _: &Self::Options) -> bool {
170        true
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use vortex_array::ArrayRef;
177    use vortex_array::Columnar;
178    use vortex_array::ExecutionCtx;
179    use vortex_array::IntoArray;
180    use vortex_array::VortexSessionExecute;
181    use vortex_array::arrays::ConstantArray;
182    use vortex_array::arrays::MaskedArray;
183    use vortex_array::arrays::PrimitiveArray;
184    use vortex_array::assert_arrays_eq;
185    use vortex_array::dtype::DType;
186    use vortex_array::dtype::Nullability;
187    use vortex_array::dtype::PType;
188    use vortex_array::scalar::Scalar;
189    use vortex_array::scalar_fn::EmptyOptions;
190    use vortex_array::scalar_fn::ScalarFnVTable;
191    use vortex_array::validity::Validity;
192    use vortex_error::VortexResult;
193    use vortex_error::vortex_err;
194
195    use super::SpatialLength;
196    use crate::test_harness::linestring_column;
197    use crate::test_harness::point_column;
198
199    fn line_constant(
200        line: Vec<(f64, f64)>,
201        len: usize,
202        ctx: &mut ExecutionCtx,
203    ) -> VortexResult<ArrayRef> {
204        let scalar = linestring_column(vec![line])?.execute_scalar(0, ctx)?;
205        Ok(ConstantArray::new(scalar, len).into_array())
206    }
207
208    #[test]
209    fn measures_each_linestring() -> VortexResult<()> {
210        let session = vortex_array::array_session();
211        let mut ctx = session.create_execution_ctx();
212        let lines = linestring_column(vec![
213            vec![(0.0, 0.0), (3.0, 4.0)],
214            vec![(0.0, 0.0), (3.0, 4.0), (3.0, 8.0)],
215            vec![(1.0, 2.0)],
216            vec![],
217        ])?;
218
219        let lengths = SpatialLength::try_new(lines)?.into_array();
220        let expected = PrimitiveArray::from_iter([5.0f64, 9.0, 0.0, 0.0]).into_array();
221
222        assert_arrays_eq!(lengths, expected, &mut ctx);
223        Ok(())
224    }
225
226    #[test]
227    fn constant_is_computed_once_and_remains_constant() -> VortexResult<()> {
228        let session = vortex_array::array_session();
229        let mut ctx = session.create_execution_ctx();
230        let lines = line_constant(vec![(0.0, 0.0), (3.0, 4.0), (3.0, 8.0)], 3, &mut ctx)?;
231
232        let result = SpatialLength::try_new(lines)?
233            .into_array()
234            .execute::<Columnar>(&mut ctx)?;
235        let Columnar::Constant(lengths) = result else {
236            return Err(vortex_err!("length of a constant should remain constant"));
237        };
238        assert_eq!(lengths.len(), 3);
239        assert_eq!(f64::try_from(lengths.scalar())?, 9.0);
240        Ok(())
241    }
242
243    #[test]
244    fn null_constant_is_all_null() -> VortexResult<()> {
245        let session = vortex_array::array_session();
246        let mut ctx = session.create_execution_ctx();
247        let dtype = linestring_column(vec![vec![]])?.dtype().as_nullable();
248        let lines = ConstantArray::new(Scalar::null(dtype), 2).into_array();
249
250        let result = SpatialLength::try_new(lines)?
251            .into_array()
252            .execute::<Columnar>(&mut ctx)?;
253        let Columnar::Constant(lengths) = result else {
254            return Err(vortex_err!(
255                "length of a null constant should remain constant"
256            ));
257        };
258        assert_eq!(lengths.len(), 2);
259        assert!(lengths.scalar().is_null());
260        Ok(())
261    }
262
263    #[test]
264    fn propagates_nullable_rows() -> VortexResult<()> {
265        let session = vortex_array::array_session();
266        let mut ctx = session.create_execution_ctx();
267        let lines = MaskedArray::try_new(
268            linestring_column(vec![
269                vec![(0.0, 0.0), (3.0, 4.0)],
270                vec![(0.0, 0.0), (1.0, 1.0)],
271                vec![(0.0, 0.0), (0.0, 4.0)],
272            ])?,
273            Validity::from_iter([true, false, true]),
274        )?
275        .into_array();
276
277        let expected = PrimitiveArray::new(
278            vec![5.0, 0.0, 4.0],
279            Validity::from_iter([true, false, true]),
280        )
281        .into_array();
282        let lengths = SpatialLength::try_new(lines)?.into_array();
283        assert_arrays_eq!(lengths, expected, &mut ctx);
284        Ok(())
285    }
286
287    #[test]
288    fn propagates_all_null_rows() -> VortexResult<()> {
289        let session = vortex_array::array_session();
290        let mut ctx = session.create_execution_ctx();
291        let lines = MaskedArray::try_new(
292            linestring_column(vec![
293                vec![(0.0, 0.0), (3.0, 4.0)],
294                vec![(0.0, 0.0), (0.0, 4.0)],
295            ])?,
296            Validity::from_iter([false, false]),
297        )?
298        .into_array();
299        let expected =
300            PrimitiveArray::new(vec![0.0, 0.0], Validity::from_iter([false, false])).into_array();
301
302        let lengths = SpatialLength::try_new(lines)?.into_array();
303
304        assert_arrays_eq!(lengths, expected, &mut ctx);
305        Ok(())
306    }
307
308    #[test]
309    fn rejects_non_linestring_dtype() -> VortexResult<()> {
310        let point = point_column(vec![0.0], vec![0.0])?;
311        assert!(
312            SpatialLength
313                .return_dtype(&EmptyOptions, std::slice::from_ref(point.dtype()))
314                .is_err()
315        );
316        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
317        assert!(
318            SpatialLength
319                .return_dtype(&EmptyOptions, &[primitive])
320                .is_err()
321        );
322        Ok(())
323    }
324}