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