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 std::sync::LazyLock;
75
76    use vortex_array::ArrayRef;
77    use vortex_array::Canonical;
78    use vortex_array::ExecutionCtx;
79    use vortex_array::IntoArray;
80    use vortex_array::VortexSessionExecute;
81    use vortex_array::arrays::ConstantArray;
82    use vortex_array::arrays::PrimitiveArray;
83    use vortex_array::assert_arrays_eq;
84    use vortex_array::dtype::DType;
85    use vortex_array::dtype::Nullability;
86    use vortex_array::dtype::PType;
87    use vortex_array::scalar::Scalar;
88    use vortex_array::scalar_fn::EmptyOptions;
89    use vortex_array::scalar_fn::ScalarFnVTable;
90    use vortex_array::validity::Validity;
91    use vortex_error::VortexResult;
92    use vortex_session::VortexSession;
93
94    use super::SpatialDistance;
95    use crate::test_harness::nullable_multipolygon_column;
96    use crate::test_harness::nullable_point_column;
97    use crate::test_harness::point_column;
98    use crate::test_harness::polygon_column;
99
100    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
101
102    /// A constant `Point` column of length `len`, every row at `(x, y)`.
103    fn point_constant(
104        x: f64,
105        y: f64,
106        len: usize,
107        ctx: &mut ExecutionCtx,
108    ) -> VortexResult<ArrayRef> {
109        let single = point_column(vec![x], vec![y])?.execute_scalar(0, ctx)?;
110        Ok(ConstantArray::new(single, len).into_array())
111    }
112
113    /// `SpatialDistance` returns the per-row distance between a point column and a constant query point
114    /// (3–4–5 triangles), computed via the external `geo` crate.
115    #[test]
116    fn distance_over_points() -> VortexResult<()> {
117        let mut ctx = SESSION.create_execution_ctx();
118
119        let a = point_column(vec![0.0, 3.0, 0.0, 3.0], vec![0.0, 0.0, 4.0, 4.0])?;
120        let b = point_constant(0.0, 0.0, 4, &mut ctx)?;
121        let distance = SpatialDistance::try_new(a, b)?.into_array();
122
123        assert_arrays_eq!(
124            distance,
125            PrimitiveArray::from_iter([0.0, 3.0, 4.0, 5.0]),
126            &mut ctx
127        );
128        Ok(())
129    }
130
131    /// Column-to-column distance pairs corresponding rows of the two columns.
132    #[test]
133    fn distance_between_columns() -> VortexResult<()> {
134        let mut ctx = SESSION.create_execution_ctx();
135
136        let a = point_column(vec![0.0, 1.0], vec![0.0, 1.0])?;
137        let b = point_column(vec![3.0, 1.0], vec![4.0, 1.0])?;
138        let distance = SpatialDistance::try_new(a, b)?.into_array();
139
140        assert_arrays_eq!(distance, PrimitiveArray::from_iter([5.0, 0.0]), &mut ctx);
141        Ok(())
142    }
143
144    /// Distance passes no bounding-rect rejection: a point far outside a constant polygon's
145    /// bounding rect still gets its true distance, alongside an inside point at distance zero.
146    #[test]
147    fn distance_to_constant_polygon_is_exact() -> VortexResult<()> {
148        let mut ctx = SESSION.create_execution_ctx();
149
150        let ring = vec![(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0), (0.0, 0.0)];
151        let single = polygon_column(vec![vec![ring]])?.execute_scalar(0, &mut ctx)?;
152        let square = ConstantArray::new(single, 2).into_array();
153        let points = point_column(vec![7.0, 2.0], vec![2.0, 2.0])?;
154        let distance = SpatialDistance::try_new(points, square)?.into_array();
155
156        assert_arrays_eq!(distance, PrimitiveArray::from_iter([3.0, 0.0]), &mut ctx);
157        Ok(())
158    }
159
160    /// The constant query point may be either operand; distance is symmetric.
161    #[test]
162    fn distance_with_constant_first_operand() -> VortexResult<()> {
163        let mut ctx = SESSION.create_execution_ctx();
164
165        let a = point_constant(0.0, 0.0, 4, &mut ctx)?;
166        let b = point_column(vec![0.0, 3.0, 0.0, 3.0], vec![0.0, 0.0, 4.0, 4.0])?;
167        let distance = SpatialDistance::try_new(a, b)?.into_array();
168
169        assert_arrays_eq!(
170            distance,
171            PrimitiveArray::from_iter([0.0, 3.0, 4.0, 5.0]),
172            &mut ctx
173        );
174        Ok(())
175    }
176
177    /// Two constant operands: every row has the same distance.
178    #[test]
179    fn distance_between_two_constants() -> VortexResult<()> {
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 mut ctx = SESSION.create_execution_ctx();
218
219        let a = nullable_point_column(vec![Some((0.0, 0.0)), None, Some((3.0, 4.0))])?;
220        let b = point_constant(0.0, 0.0, 3, &mut ctx)?;
221        let distance = SpatialDistance::try_new(a, b)?.into_array();
222
223        let expected = PrimitiveArray::new(
224            vec![0.0f64, 0.0, 5.0],
225            Validity::from_iter([true, false, true]),
226        )
227        .into_array();
228        assert_arrays_eq!(distance, expected, &mut ctx);
229        Ok(())
230    }
231
232    /// A nullable column of a list-storage geometry type (`MultiPolygon`): nulls propagate and
233    /// valid rows get exact distances, with the null row's storage never decoded.
234    #[test]
235    fn distance_propagates_nulls_for_multipolygon() -> VortexResult<()> {
236        let mut ctx = SESSION.create_execution_ctx();
237
238        let near = vec![vec![vec![
239            (0.0, 0.0),
240            (4.0, 0.0),
241            (4.0, 4.0),
242            (0.0, 4.0),
243            (0.0, 0.0),
244        ]]];
245        let far = vec![vec![vec![
246            (10.0, 6.0),
247            (14.0, 6.0),
248            (14.0, 10.0),
249            (10.0, 10.0),
250            (10.0, 6.0),
251        ]]];
252        let a = nullable_multipolygon_column(vec![Some(near), None, Some(far)])?;
253        let b = point_constant(7.0, 2.0, 3, &mut ctx)?;
254        let distance = SpatialDistance::try_new(a, b)?.into_array();
255
256        let expected = PrimitiveArray::new(
257            vec![3.0f64, 0.0, 5.0],
258            Validity::from_iter([true, false, true]),
259        )
260        .into_array();
261        assert_arrays_eq!(distance, expected, &mut ctx);
262        Ok(())
263    }
264
265    /// Both operands nullable: a row is null if either operand is null there.
266    #[test]
267    fn distance_propagates_column_pair_nulls() -> VortexResult<()> {
268        let mut ctx = SESSION.create_execution_ctx();
269
270        let a = nullable_point_column(vec![Some((0.0, 0.0)), None, Some((0.0, 0.0))])?;
271        let b = nullable_point_column(vec![Some((3.0, 4.0)), Some((1.0, 1.0)), None])?;
272        let distance = SpatialDistance::try_new(a, b)?.into_array();
273
274        let expected = PrimitiveArray::new(
275            vec![5.0f64, 0.0, 0.0],
276            Validity::from_iter([true, false, false]),
277        )
278        .into_array();
279        assert_arrays_eq!(distance, expected, &mut ctx);
280        Ok(())
281    }
282
283    /// A constant-null operand produces an all-null output.
284    #[test]
285    fn distance_constant_null_is_all_null() -> VortexResult<()> {
286        let mut ctx = SESSION.create_execution_ctx();
287
288        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().as_nullable();
289        let null_const = ConstantArray::new(Scalar::null(point_dtype), 3).into_array();
290        let b = point_column(vec![0.0, 3.0, 0.0], vec![0.0, 0.0, 4.0])?;
291        let distance = SpatialDistance::try_new(null_const, b)?.into_array();
292
293        let expected = PrimitiveArray::new(vec![0.0f64; 3], Validity::AllInvalid).into_array();
294        assert_arrays_eq!(distance, expected, &mut ctx);
295        Ok(())
296    }
297
298    /// An entirely-null geometry column yields an all-null output.
299    #[test]
300    fn distance_all_null_column_is_all_null() -> VortexResult<()> {
301        let mut ctx = SESSION.create_execution_ctx();
302
303        let a = nullable_point_column(vec![None, None])?;
304        let b = point_constant(0.0, 0.0, 2, &mut ctx)?;
305        let distance = SpatialDistance::try_new(a, b)?.into_array();
306
307        let expected = PrimitiveArray::new(vec![0.0f64; 2], Validity::AllInvalid).into_array();
308        assert_arrays_eq!(distance, expected, &mut ctx);
309        Ok(())
310    }
311
312    /// Two nullable columns whose nulls never line up: the combined mask is empty, so the output
313    /// is all null.
314    #[test]
315    fn distance_column_pair_all_null() -> VortexResult<()> {
316        let mut ctx = SESSION.create_execution_ctx();
317
318        let a = nullable_point_column(vec![Some((0.0, 0.0)), None])?;
319        let b = nullable_point_column(vec![None, Some((1.0, 1.0))])?;
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    /// A zero-length non-nullable execution keeps the non-nullable result dtype: an empty
328    /// `AllTrue` mask has `true_count() == 0`, and must not be mistaken for all-null and widened
329    /// to nullable (which would trip the result-dtype assertion against `return_dtype`).
330    #[test]
331    fn distance_empty_non_nullable_keeps_dtype() -> VortexResult<()> {
332        let mut ctx = SESSION.create_execution_ctx();
333
334        let a = point_column(vec![], vec![])?;
335        let b = point_column(vec![], vec![])?;
336        let result = SpatialDistance::try_new(a, b)?
337            .into_array()
338            .execute::<Canonical>(&mut ctx)?
339            .into_array();
340
341        assert!(!result.dtype().is_nullable());
342        assert_eq!(result.len(), 0);
343        Ok(())
344    }
345
346    /// A non-geometry operand dtype is rejected up front, before execution.
347    #[test]
348    fn non_geometry_operand_is_rejected() -> VortexResult<()> {
349        let spatial_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
350        let numeric = DType::Primitive(PType::I32, Nullability::NonNullable);
351        let result = SpatialDistance.return_dtype(&EmptyOptions, &[spatial_dtype, numeric]);
352        assert!(result.is_err());
353        Ok(())
354    }
355}