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    /// Execute a `SpatialDistance` array and read back its per-row `f64` distances.
109    fn distances(distance: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Vec<f64>> {
110        Ok(distance
111            .execute::<Canonical>(ctx)?
112            .into_primitive()
113            .as_slice::<f64>()
114            .to_vec())
115    }
116
117    /// `SpatialDistance` returns the per-row distance between a point column and a constant query point
118    /// (3–4–5 triangles), computed via the external `geo` crate.
119    #[test]
120    fn distance_over_points() -> VortexResult<()> {
121        let session = vortex_array::array_session();
122        let mut ctx = session.create_execution_ctx();
123
124        let a = point_column(vec![0.0, 3.0, 0.0, 3.0], vec![0.0, 0.0, 4.0, 4.0])?;
125        let b = point_constant(0.0, 0.0, 4, &mut ctx)?;
126        let distance = SpatialDistance::try_new(a, b)?.into_array();
127
128        assert_eq!(distances(distance, &mut ctx)?, vec![0.0, 3.0, 4.0, 5.0]);
129        Ok(())
130    }
131
132    /// Column-to-column distance pairs corresponding rows of the two columns.
133    #[test]
134    fn distance_between_columns() -> VortexResult<()> {
135        let session = vortex_array::array_session();
136        let mut ctx = session.create_execution_ctx();
137
138        let a = point_column(vec![0.0, 1.0], vec![0.0, 1.0])?;
139        let b = point_column(vec![3.0, 1.0], vec![4.0, 1.0])?;
140        let distance = SpatialDistance::try_new(a, b)?.into_array();
141
142        assert_eq!(distances(distance, &mut ctx)?, vec![5.0, 0.0]);
143        Ok(())
144    }
145
146    /// Distance passes no bounding-rect rejection: a point far outside a constant polygon's
147    /// bounding rect still gets its true distance, alongside an inside point at distance zero.
148    #[test]
149    fn distance_to_constant_polygon_is_exact() -> VortexResult<()> {
150        let session = vortex_array::array_session();
151        let mut ctx = session.create_execution_ctx();
152
153        let ring = vec![(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0), (0.0, 0.0)];
154        let single = polygon_column(vec![vec![ring]])?.execute_scalar(0, &mut ctx)?;
155        let square = ConstantArray::new(single, 2).into_array();
156        let points = point_column(vec![7.0, 2.0], vec![2.0, 2.0])?;
157        let distance = SpatialDistance::try_new(points, square)?.into_array();
158
159        assert_eq!(distances(distance, &mut ctx)?, vec![3.0, 0.0]);
160        Ok(())
161    }
162
163    /// The constant query point may be either operand; distance is symmetric.
164    #[test]
165    fn distance_with_constant_first_operand() -> VortexResult<()> {
166        let session = vortex_array::array_session();
167        let mut ctx = session.create_execution_ctx();
168
169        let a = point_constant(0.0, 0.0, 4, &mut ctx)?;
170        let b = point_column(vec![0.0, 3.0, 0.0, 3.0], vec![0.0, 0.0, 4.0, 4.0])?;
171        let distance = SpatialDistance::try_new(a, b)?.into_array();
172
173        assert_eq!(distances(distance, &mut ctx)?, vec![0.0, 3.0, 4.0, 5.0]);
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 session = vortex_array::array_session();
181        let mut ctx = session.create_execution_ctx();
182
183        let a = point_constant(0.0, 0.0, 3, &mut ctx)?;
184        let b = point_constant(3.0, 4.0, 3, &mut ctx)?;
185        let distance = SpatialDistance::try_new(a, b)?.into_array();
186
187        assert_eq!(distances(distance, &mut ctx)?, vec![5.0, 5.0, 5.0]);
188        Ok(())
189    }
190
191    /// Output nullability mirrors the operands: nullable if any operand is nullable, otherwise
192    /// non-nullable.
193    #[test]
194    fn output_nullability_mirrors_operands() -> VortexResult<()> {
195        let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
196        let non_nullable =
197            SpatialDistance.return_dtype(&EmptyOptions, &[dtype.clone(), dtype.clone()])?;
198        assert!(!non_nullable.is_nullable());
199        let nullable =
200            SpatialDistance.return_dtype(&EmptyOptions, &[dtype.as_nullable(), dtype])?;
201        assert!(nullable.is_nullable());
202        Ok(())
203    }
204
205    /// A null row in a geometry operand yields a null result; valid rows are unaffected.
206    #[test]
207    fn distance_propagates_null_rows() -> VortexResult<()> {
208        let session = vortex_array::array_session();
209        let mut ctx = session.create_execution_ctx();
210
211        let a = nullable_point_column(vec![Some((0.0, 0.0)), None, Some((3.0, 4.0))])?;
212        let b = point_constant(0.0, 0.0, 3, &mut ctx)?;
213        let distance = SpatialDistance::try_new(a, b)?.into_array();
214
215        let expected = PrimitiveArray::new(
216            vec![0.0f64, 0.0, 5.0],
217            Validity::from_iter([true, false, true]),
218        )
219        .into_array();
220        assert_arrays_eq!(distance, expected, &mut ctx);
221        Ok(())
222    }
223
224    /// A nullable column of a list-storage geometry type (`MultiPolygon`): nulls propagate and
225    /// valid rows get exact distances, with the null row's storage never decoded.
226    #[test]
227    fn distance_propagates_nulls_for_multipolygon() -> VortexResult<()> {
228        let session = vortex_array::array_session();
229        let mut ctx = session.create_execution_ctx();
230
231        let near = vec![vec![vec![
232            (0.0, 0.0),
233            (4.0, 0.0),
234            (4.0, 4.0),
235            (0.0, 4.0),
236            (0.0, 0.0),
237        ]]];
238        let far = vec![vec![vec![
239            (10.0, 6.0),
240            (14.0, 6.0),
241            (14.0, 10.0),
242            (10.0, 10.0),
243            (10.0, 6.0),
244        ]]];
245        let a = nullable_multipolygon_column(vec![Some(near), None, Some(far)])?;
246        let b = point_constant(7.0, 2.0, 3, &mut ctx)?;
247        let distance = SpatialDistance::try_new(a, b)?.into_array();
248
249        let expected = PrimitiveArray::new(
250            vec![3.0f64, 0.0, 5.0],
251            Validity::from_iter([true, false, true]),
252        )
253        .into_array();
254        assert_arrays_eq!(distance, expected, &mut ctx);
255        Ok(())
256    }
257
258    /// Both operands nullable: a row is null if either operand is null there.
259    #[test]
260    fn distance_propagates_column_pair_nulls() -> 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((0.0, 0.0))])?;
265        let b = nullable_point_column(vec![Some((3.0, 4.0)), Some((1.0, 1.0)), None])?;
266        let distance = SpatialDistance::try_new(a, b)?.into_array();
267
268        let expected = PrimitiveArray::new(
269            vec![5.0f64, 0.0, 0.0],
270            Validity::from_iter([true, false, false]),
271        )
272        .into_array();
273        assert_arrays_eq!(distance, expected, &mut ctx);
274        Ok(())
275    }
276
277    /// A constant-null operand produces an all-null output.
278    #[test]
279    fn distance_constant_null_is_all_null() -> VortexResult<()> {
280        let session = vortex_array::array_session();
281        let mut ctx = session.create_execution_ctx();
282
283        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().as_nullable();
284        let null_const = ConstantArray::new(Scalar::null(point_dtype), 3).into_array();
285        let b = point_column(vec![0.0, 3.0, 0.0], vec![0.0, 0.0, 4.0])?;
286        let distance = SpatialDistance::try_new(null_const, b)?.into_array();
287
288        let expected = PrimitiveArray::new(vec![0.0f64; 3], Validity::AllInvalid).into_array();
289        assert_arrays_eq!(distance, expected, &mut ctx);
290        Ok(())
291    }
292
293    /// An entirely-null geometry column yields an all-null output.
294    #[test]
295    fn distance_all_null_column_is_all_null() -> VortexResult<()> {
296        let session = vortex_array::array_session();
297        let mut ctx = session.create_execution_ctx();
298
299        let a = nullable_point_column(vec![None, None])?;
300        let b = point_constant(0.0, 0.0, 2, &mut ctx)?;
301        let distance = SpatialDistance::try_new(a, b)?.into_array();
302
303        let expected = PrimitiveArray::new(vec![0.0f64; 2], Validity::AllInvalid).into_array();
304        assert_arrays_eq!(distance, expected, &mut ctx);
305        Ok(())
306    }
307
308    /// Two nullable columns whose nulls never line up: the combined mask is empty, so the output
309    /// is all null.
310    #[test]
311    fn distance_column_pair_all_null() -> VortexResult<()> {
312        let session = vortex_array::array_session();
313        let mut ctx = session.create_execution_ctx();
314
315        let a = nullable_point_column(vec![Some((0.0, 0.0)), None])?;
316        let b = nullable_point_column(vec![None, Some((1.0, 1.0))])?;
317        let distance = SpatialDistance::try_new(a, b)?.into_array();
318
319        let expected = PrimitiveArray::new(vec![0.0f64; 2], Validity::AllInvalid).into_array();
320        assert_arrays_eq!(distance, expected, &mut ctx);
321        Ok(())
322    }
323
324    /// A zero-length non-nullable execution keeps the non-nullable result dtype: an empty
325    /// `AllTrue` mask has `true_count() == 0`, and must not be mistaken for all-null and widened
326    /// to nullable (which would trip the result-dtype assertion against `return_dtype`).
327    #[test]
328    fn distance_empty_non_nullable_keeps_dtype() -> VortexResult<()> {
329        let session = vortex_array::array_session();
330        let mut ctx = session.create_execution_ctx();
331
332        let a = point_column(vec![], vec![])?;
333        let b = point_column(vec![], vec![])?;
334        let result = SpatialDistance::try_new(a, b)?
335            .into_array()
336            .execute::<Canonical>(&mut ctx)?
337            .into_array();
338
339        assert!(!result.dtype().is_nullable());
340        assert_eq!(result.len(), 0);
341        Ok(())
342    }
343
344    /// A non-geometry operand dtype is rejected up front, before execution.
345    #[test]
346    fn non_geometry_operand_is_rejected() -> VortexResult<()> {
347        let spatial_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
348        let numeric = DType::Primitive(PType::I32, Nullability::NonNullable);
349        let result = SpatialDistance.return_dtype(&EmptyOptions, &[spatial_dtype, numeric]);
350        assert!(result.is_err());
351        Ok(())
352    }
353}