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