Skip to main content

vortex_spatial/scalar_fn/
distance.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! `ST_Distance`: planar (Euclidean) distance between two native geometries.
5
6use geo::Distance;
7use geo::Euclidean;
8use vortex_array::ArrayRef;
9use vortex_array::ExecutionCtx;
10use vortex_array::arrays::ScalarFnArray;
11use vortex_array::dtype::DType;
12use vortex_array::dtype::Nullability;
13use vortex_array::dtype::PType;
14use vortex_array::expr::Expression;
15use vortex_array::expr::union_child_validities;
16use vortex_array::scalar_fn::Arity;
17use vortex_array::scalar_fn::ChildName;
18use vortex_array::scalar_fn::EmptyOptions;
19use vortex_array::scalar_fn::ExecutionArgs;
20use vortex_array::scalar_fn::ScalarFnId;
21use vortex_array::scalar_fn::ScalarFnVTable;
22use vortex_array::scalar_fn::TypedScalarFnInstance;
23use vortex_error::VortexResult;
24use vortex_error::vortex_ensure;
25use vortex_session::VortexSession;
26use vortex_session::registry::CachedId;
27
28use crate::extension::is_native_geometry;
29use crate::scalar_fn::execute::execute_binary_geo_types;
30
31/// Validate the two native geometry operands accepted by `ST_Distance`.
32fn validate_distance_operands(dtypes: &[DType]) -> VortexResult<()> {
33    vortex_ensure!(
34        dtypes.len() == 2,
35        "spatial: distance requires exactly two geometry operands, got {}",
36        dtypes.len()
37    );
38    for dtype in dtypes {
39        vortex_ensure!(
40            is_native_geometry(dtype),
41            "spatial: distance operand {dtype} is not a native geometry type"
42        );
43    }
44    Ok(())
45}
46
47/// Planar (Euclidean) `ST_Distance` (no geodesic correction) between two native geometry
48/// operands, each a column or a constant literal.
49#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
50pub struct SpatialDistance;
51
52impl SpatialDistance {
53    /// A lazy `ScalarFnArray` computing the per-row distance between operands `a` and `b`; either may
54    /// be constant. The output length is taken from `a`.
55    pub fn try_new(a: ArrayRef, b: ArrayRef) -> VortexResult<ScalarFnArray> {
56        ScalarFnArray::try_new(
57            TypedScalarFnInstance::new(SpatialDistance, EmptyOptions).erased(),
58            vec![a, b],
59        )
60    }
61}
62
63impl ScalarFnVTable for SpatialDistance {
64    type Options = EmptyOptions;
65
66    fn id(&self) -> ScalarFnId {
67        static ID: CachedId = CachedId::new("vortex.st.distance");
68        *ID
69    }
70
71    fn serialize(&self, _: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
72        Ok(Some(vec![]))
73    }
74
75    fn deserialize(&self, _: &[u8], _: &VortexSession) -> VortexResult<Self::Options> {
76        Ok(EmptyOptions)
77    }
78
79    fn arity(&self, _: &Self::Options) -> Arity {
80        Arity::Exact(2)
81    }
82
83    fn child_name(&self, _: &Self::Options, child_idx: usize) -> ChildName {
84        match child_idx {
85            0 => ChildName::from("a"),
86            1 => ChildName::from("b"),
87            _ => unreachable!("distance has exactly two children"),
88        }
89    }
90
91    fn return_dtype(&self, _: &Self::Options, dtypes: &[DType]) -> VortexResult<DType> {
92        validate_distance_operands(dtypes)?;
93        let nullability = Nullability::from(dtypes.iter().any(DType::is_nullable));
94        Ok(DType::Primitive(PType::F64, nullability))
95    }
96
97    fn execute(
98        &self,
99        _: &Self::Options,
100        args: &dyn ExecutionArgs,
101        ctx: &mut ExecutionCtx,
102    ) -> VortexResult<ArrayRef> {
103        let a = args.get(0)?;
104        let b = args.get(1)?;
105        // Distance is a value, not a verdict: no bounding-rect test can decide it.
106        execute_binary_geo_types(&a, &b, |x, y| Euclidean.distance(x, y), None, ctx)
107    }
108
109    fn validity(
110        &self,
111        _: &Self::Options,
112        expression: &Expression,
113    ) -> VortexResult<Option<Expression>> {
114        union_child_validities(expression)
115    }
116
117    fn is_strict(&self, _: &Self::Options) -> bool {
118        true
119    }
120
121    fn is_infallible(&self, _: &Self::Options) -> bool {
122        true
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use vortex_array::ArrayRef;
129    use vortex_array::Canonical;
130    use vortex_array::ExecutionCtx;
131    use vortex_array::IntoArray;
132    use vortex_array::VortexSessionExecute;
133    use vortex_array::arrays::ConstantArray;
134    use vortex_array::arrays::PrimitiveArray;
135    use vortex_array::assert_arrays_eq;
136    use vortex_array::dtype::DType;
137    use vortex_array::dtype::Nullability;
138    use vortex_array::dtype::PType;
139    use vortex_array::scalar::Scalar;
140    use vortex_array::scalar_fn::EmptyOptions;
141    use vortex_array::scalar_fn::ScalarFnVTable;
142    use vortex_array::validity::Validity;
143    use vortex_error::VortexResult;
144
145    use super::SpatialDistance;
146    use crate::test_harness::nullable_point_column;
147    use crate::test_harness::point_column;
148    use crate::test_harness::polygon_column;
149
150    /// A constant `Point` column of length `len`, every row at `(x, y)`.
151    fn point_constant(
152        x: f64,
153        y: f64,
154        len: usize,
155        ctx: &mut ExecutionCtx,
156    ) -> VortexResult<ArrayRef> {
157        let single = point_column(vec![x], vec![y])?.execute_scalar(0, ctx)?;
158        Ok(ConstantArray::new(single, len).into_array())
159    }
160
161    /// Execute a `SpatialDistance` array and read back its per-row `f64` distances.
162    fn distances(distance: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Vec<f64>> {
163        Ok(distance
164            .execute::<Canonical>(ctx)?
165            .into_primitive()
166            .as_slice::<f64>()
167            .to_vec())
168    }
169
170    /// `SpatialDistance` returns the per-row distance between a point column and a constant query point
171    /// (3–4–5 triangles), computed via the external `geo` crate.
172    #[test]
173    fn distance_over_points() -> VortexResult<()> {
174        let session = vortex_array::array_session();
175        let mut ctx = session.create_execution_ctx();
176
177        let a = point_column(vec![0.0, 3.0, 0.0, 3.0], vec![0.0, 0.0, 4.0, 4.0])?;
178        let b = point_constant(0.0, 0.0, 4, &mut ctx)?;
179        let distance = SpatialDistance::try_new(a, b)?.into_array();
180
181        assert_eq!(distances(distance, &mut ctx)?, vec![0.0, 3.0, 4.0, 5.0]);
182        Ok(())
183    }
184
185    /// Column-to-column distance pairs corresponding rows of the two columns.
186    #[test]
187    fn distance_between_columns() -> VortexResult<()> {
188        let session = vortex_array::array_session();
189        let mut ctx = session.create_execution_ctx();
190
191        let a = point_column(vec![0.0, 1.0], vec![0.0, 1.0])?;
192        let b = point_column(vec![3.0, 1.0], vec![4.0, 1.0])?;
193        let distance = SpatialDistance::try_new(a, b)?.into_array();
194
195        assert_eq!(distances(distance, &mut ctx)?, vec![5.0, 0.0]);
196        Ok(())
197    }
198
199    /// Distance passes no bounding-rect rejection: a point far outside a constant polygon's
200    /// bounding rect still gets its true distance, alongside an inside point at distance zero.
201    #[test]
202    fn distance_to_constant_polygon_is_exact() -> VortexResult<()> {
203        let session = vortex_array::array_session();
204        let mut ctx = session.create_execution_ctx();
205
206        let ring = vec![(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0), (0.0, 0.0)];
207        let single = polygon_column(vec![vec![ring]])?.execute_scalar(0, &mut ctx)?;
208        let square = ConstantArray::new(single, 2).into_array();
209        let points = point_column(vec![7.0, 2.0], vec![2.0, 2.0])?;
210        let distance = SpatialDistance::try_new(points, square)?.into_array();
211
212        assert_eq!(distances(distance, &mut ctx)?, vec![3.0, 0.0]);
213        Ok(())
214    }
215
216    /// The constant query point may be either operand; distance is symmetric.
217    #[test]
218    fn distance_with_constant_first_operand() -> VortexResult<()> {
219        let session = vortex_array::array_session();
220        let mut ctx = session.create_execution_ctx();
221
222        let a = point_constant(0.0, 0.0, 4, &mut ctx)?;
223        let b = point_column(vec![0.0, 3.0, 0.0, 3.0], vec![0.0, 0.0, 4.0, 4.0])?;
224        let distance = SpatialDistance::try_new(a, b)?.into_array();
225
226        assert_eq!(distances(distance, &mut ctx)?, vec![0.0, 3.0, 4.0, 5.0]);
227        Ok(())
228    }
229
230    /// Two constant operands: every row has the same distance.
231    #[test]
232    fn distance_between_two_constants() -> VortexResult<()> {
233        let session = vortex_array::array_session();
234        let mut ctx = session.create_execution_ctx();
235
236        let a = point_constant(0.0, 0.0, 3, &mut ctx)?;
237        let b = point_constant(3.0, 4.0, 3, &mut ctx)?;
238        let distance = SpatialDistance::try_new(a, b)?.into_array();
239
240        assert_eq!(distances(distance, &mut ctx)?, vec![5.0, 5.0, 5.0]);
241        Ok(())
242    }
243
244    /// Output nullability mirrors the operands: nullable if any operand is nullable, otherwise
245    /// non-nullable.
246    #[test]
247    fn output_nullability_mirrors_operands() -> VortexResult<()> {
248        let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
249        let non_nullable =
250            SpatialDistance.return_dtype(&EmptyOptions, &[dtype.clone(), dtype.clone()])?;
251        assert!(!non_nullable.is_nullable());
252        let nullable =
253            SpatialDistance.return_dtype(&EmptyOptions, &[dtype.as_nullable(), dtype])?;
254        assert!(nullable.is_nullable());
255        Ok(())
256    }
257
258    /// A null row in a geometry operand yields a null result; valid rows are unaffected.
259    #[test]
260    fn distance_propagates_null_rows() -> VortexResult<()> {
261        let session = vortex_array::array_session();
262        let mut ctx = session.create_execution_ctx();
263
264        let a = nullable_point_column(vec![Some((0.0, 0.0)), None, Some((3.0, 4.0))])?;
265        let b = point_constant(0.0, 0.0, 3, &mut ctx)?;
266        let distance = SpatialDistance::try_new(a, b)?.into_array();
267
268        let expected = PrimitiveArray::new(
269            vec![0.0f64, 0.0, 5.0],
270            Validity::from_iter([true, false, true]),
271        )
272        .into_array();
273        assert_arrays_eq!(distance, expected, &mut ctx);
274        Ok(())
275    }
276
277    /// Both operands nullable: a row is null if either operand is null there.
278    #[test]
279    fn distance_propagates_column_pair_nulls() -> VortexResult<()> {
280        let session = vortex_array::array_session();
281        let mut ctx = session.create_execution_ctx();
282
283        let a = nullable_point_column(vec![Some((0.0, 0.0)), None, Some((0.0, 0.0))])?;
284        let b = nullable_point_column(vec![Some((3.0, 4.0)), Some((1.0, 1.0)), None])?;
285        let distance = SpatialDistance::try_new(a, b)?.into_array();
286
287        let expected = PrimitiveArray::new(
288            vec![5.0f64, 0.0, 0.0],
289            Validity::from_iter([true, false, false]),
290        )
291        .into_array();
292        assert_arrays_eq!(distance, expected, &mut ctx);
293        Ok(())
294    }
295
296    /// A constant-null operand produces an all-null output.
297    #[test]
298    fn distance_constant_null_is_all_null() -> VortexResult<()> {
299        let session = vortex_array::array_session();
300        let mut ctx = session.create_execution_ctx();
301
302        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().as_nullable();
303        let null_const = ConstantArray::new(Scalar::null(point_dtype), 3).into_array();
304        let b = point_column(vec![0.0, 3.0, 0.0], vec![0.0, 0.0, 4.0])?;
305        let distance = SpatialDistance::try_new(null_const, b)?.into_array();
306
307        let expected = PrimitiveArray::new(vec![0.0f64; 3], Validity::AllInvalid).into_array();
308        assert_arrays_eq!(distance, expected, &mut ctx);
309        Ok(())
310    }
311
312    /// An entirely-null geometry column yields an all-null output.
313    #[test]
314    fn distance_all_null_column_is_all_null() -> VortexResult<()> {
315        let session = vortex_array::array_session();
316        let mut ctx = session.create_execution_ctx();
317
318        let a = nullable_point_column(vec![None, None])?;
319        let b = point_constant(0.0, 0.0, 2, &mut ctx)?;
320        let distance = SpatialDistance::try_new(a, b)?.into_array();
321
322        let expected = PrimitiveArray::new(vec![0.0f64; 2], Validity::AllInvalid).into_array();
323        assert_arrays_eq!(distance, expected, &mut ctx);
324        Ok(())
325    }
326
327    /// Two nullable columns whose nulls never line up: the combined mask is empty, so the output
328    /// is all null.
329    #[test]
330    fn distance_column_pair_all_null() -> VortexResult<()> {
331        let session = vortex_array::array_session();
332        let mut ctx = session.create_execution_ctx();
333
334        let a = nullable_point_column(vec![Some((0.0, 0.0)), None])?;
335        let b = nullable_point_column(vec![None, Some((1.0, 1.0))])?;
336        let distance = SpatialDistance::try_new(a, b)?.into_array();
337
338        let expected = PrimitiveArray::new(vec![0.0f64; 2], Validity::AllInvalid).into_array();
339        assert_arrays_eq!(distance, expected, &mut ctx);
340        Ok(())
341    }
342
343    /// A zero-length non-nullable execution keeps the non-nullable result dtype: an empty
344    /// `AllTrue` mask has `true_count() == 0`, and must not be mistaken for all-null and widened
345    /// to nullable (which would trip the result-dtype assertion against `return_dtype`).
346    #[test]
347    fn distance_empty_non_nullable_keeps_dtype() -> VortexResult<()> {
348        let session = vortex_array::array_session();
349        let mut ctx = session.create_execution_ctx();
350
351        let a = point_column(vec![], vec![])?;
352        let b = point_column(vec![], vec![])?;
353        let result = SpatialDistance::try_new(a, b)?
354            .into_array()
355            .execute::<Canonical>(&mut ctx)?
356            .into_array();
357
358        assert!(!result.dtype().is_nullable());
359        assert_eq!(result.len(), 0);
360        Ok(())
361    }
362
363    /// A non-geometry operand dtype is rejected up front, before execution.
364    #[test]
365    fn non_geometry_operand_is_rejected() -> VortexResult<()> {
366        let spatial_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
367        let numeric = DType::Primitive(PType::I32, Nullability::NonNullable);
368        let result = SpatialDistance.return_dtype(&EmptyOptions, &[spatial_dtype, numeric]);
369        assert!(result.is_err());
370        Ok(())
371    }
372}