1use 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
47fn 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
109fn 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
131fn 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#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
148pub struct SpatialLength;
149
150impl SpatialLength {
151 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 std::sync::LazyLock;
219
220 use vortex_array::ArrayRef;
221 use vortex_array::Columnar;
222 use vortex_array::ExecutionCtx;
223 use vortex_array::IntoArray;
224 use vortex_array::VortexSessionExecute;
225 use vortex_array::arrays::ConstantArray;
226 use vortex_array::arrays::MaskedArray;
227 use vortex_array::arrays::PrimitiveArray;
228 use vortex_array::assert_arrays_eq;
229 use vortex_array::dtype::DType;
230 use vortex_array::dtype::Nullability;
231 use vortex_array::dtype::PType;
232 use vortex_array::scalar::Scalar;
233 use vortex_array::scalar_fn::EmptyOptions;
234 use vortex_array::scalar_fn::ScalarFnVTable;
235 use vortex_array::validity::Validity;
236 use vortex_error::VortexResult;
237 use vortex_error::vortex_err;
238 use vortex_session::VortexSession;
239
240 use super::SpatialLength;
241 use crate::test_harness::linestring_column;
242 use crate::test_harness::multilinestring_column;
243 use crate::test_harness::point_column;
244
245 static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
246
247 fn line_constant(
248 line: Vec<(f64, f64)>,
249 len: usize,
250 ctx: &mut ExecutionCtx,
251 ) -> VortexResult<ArrayRef> {
252 let scalar = linestring_column(vec![line])?.execute_scalar(0, ctx)?;
253 Ok(ConstantArray::new(scalar, len).into_array())
254 }
255
256 #[test]
257 fn measures_each_linestring() -> VortexResult<()> {
258 let mut ctx = SESSION.create_execution_ctx();
259 let lines = linestring_column(vec![
260 vec![(0.0, 0.0), (3.0, 4.0)],
261 vec![(0.0, 0.0), (3.0, 4.0), (3.0, 8.0)],
262 vec![(1.0, 2.0)],
263 vec![],
264 ])?;
265
266 let lengths = SpatialLength::try_new(lines)?.into_array();
267 let expected = PrimitiveArray::from_iter([5.0f64, 9.0, 0.0, 0.0]).into_array();
268
269 assert_arrays_eq!(lengths, expected, &mut ctx);
270 Ok(())
271 }
272
273 #[test]
274 fn measures_each_multilinestring() -> VortexResult<()> {
275 let mut ctx = SESSION.create_execution_ctx();
276 let lines = multilinestring_column(vec![
277 vec![
278 vec![(0.0, 0.0), (3.0, 4.0)],
279 vec![(10.0, 10.0), (10.0, 14.0)],
280 ],
281 vec![],
282 vec![vec![], vec![(1.0, 2.0)], vec![(0.0, 0.0), (0.0, 5.0)]],
283 ])?;
284
285 let lengths = SpatialLength::try_new(lines)?.into_array();
286 let expected = PrimitiveArray::from_iter([9.0f64, 0.0, 5.0]).into_array();
287
288 assert_arrays_eq!(lengths, expected, &mut ctx);
289 Ok(())
290 }
291
292 #[test]
293 fn propagates_nullable_multilinestring_rows() -> VortexResult<()> {
294 let mut ctx = SESSION.create_execution_ctx();
295 let lines = MaskedArray::try_new(
296 multilinestring_column(vec![
297 vec![vec![(0.0, 0.0), (3.0, 4.0)]],
298 vec![vec![(0.0, 0.0), (1.0, 1.0)]],
299 vec![vec![(0.0, 0.0), (0.0, 5.0)]],
300 ])?,
301 Validity::from_iter([true, false, true]),
302 &mut ctx,
303 )?
304 .into_array();
305
306 let expected = PrimitiveArray::new(
307 vec![5.0, 0.0, 5.0],
308 Validity::from_iter([true, false, true]),
309 )
310 .into_array();
311 let lengths = SpatialLength::try_new(lines)?.into_array();
312
313 assert_arrays_eq!(lengths, expected, &mut ctx);
314 Ok(())
315 }
316
317 #[test]
318 fn constant_is_computed_once_and_remains_constant() -> VortexResult<()> {
319 let mut ctx = SESSION.create_execution_ctx();
320 let lines = line_constant(vec![(0.0, 0.0), (3.0, 4.0), (3.0, 8.0)], 3, &mut ctx)?;
321
322 let result = SpatialLength::try_new(lines)?
323 .into_array()
324 .execute::<Columnar>(&mut ctx)?;
325 let Columnar::Constant(lengths) = result else {
326 return Err(vortex_err!("length of a constant should remain constant"));
327 };
328 assert_eq!(lengths.len(), 3);
329 assert_eq!(f64::try_from(lengths.scalar())?, 9.0);
330 Ok(())
331 }
332
333 #[test]
334 fn null_constant_is_all_null() -> VortexResult<()> {
335 let mut ctx = SESSION.create_execution_ctx();
336 let dtype = linestring_column(vec![vec![]])?.dtype().as_nullable();
337 let lines = ConstantArray::new(Scalar::null(dtype), 2).into_array();
338
339 let result = SpatialLength::try_new(lines)?
340 .into_array()
341 .execute::<Columnar>(&mut ctx)?;
342 let Columnar::Constant(lengths) = result else {
343 return Err(vortex_err!(
344 "length of a null constant should remain constant"
345 ));
346 };
347 assert_eq!(lengths.len(), 2);
348 assert!(lengths.scalar().is_null());
349 Ok(())
350 }
351
352 #[test]
353 fn propagates_nullable_rows() -> VortexResult<()> {
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 &mut ctx,
363 )?
364 .into_array();
365
366 let expected = PrimitiveArray::new(
367 vec![5.0, 0.0, 4.0],
368 Validity::from_iter([true, false, true]),
369 )
370 .into_array();
371 let lengths = SpatialLength::try_new(lines)?.into_array();
372 assert_arrays_eq!(lengths, expected, &mut ctx);
373 Ok(())
374 }
375
376 #[test]
377 fn propagates_all_null_rows() -> VortexResult<()> {
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 &mut ctx,
386 )?
387 .into_array();
388 let expected =
389 PrimitiveArray::new(vec![0.0, 0.0], Validity::from_iter([false, false])).into_array();
390
391 let lengths = SpatialLength::try_new(lines)?.into_array();
392
393 assert_arrays_eq!(lengths, expected, &mut ctx);
394 Ok(())
395 }
396
397 #[test]
398 fn rejects_non_lineal_dtype() -> VortexResult<()> {
399 let point = point_column(vec![0.0], vec![0.0])?;
400 assert!(
401 SpatialLength
402 .return_dtype(&EmptyOptions, std::slice::from_ref(point.dtype()))
403 .is_err()
404 );
405 let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
406 assert!(
407 SpatialLength
408 .return_dtype(&EmptyOptions, &[primitive])
409 .is_err()
410 );
411 Ok(())
412 }
413}