Skip to main content

vortex_spatial/prune/
distance.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! `ST_Distance(geom, const) <op> radius` pruning.
5
6use geo::Rect as SpatialRect;
7use vortex_array::scalar_fn::ScalarFnId;
8use vortex_array::scalar_fn::ScalarFnVTable;
9use vortex_array::scalar_fn::builtin::compare::Compare;
10use vortex_array::scalar_fn::builtin::literal::Literal;
11use vortex_array::scalar_fn::builtin::operators::CompareOperator;
12use vortex_error::VortexResult;
13use vortex_expr::BoundExpression;
14use vortex_expr::stats::rewrite::StatsRewriteRule;
15use vortex_session::VortexSession;
16
17use super::aabb_stat;
18use super::geometry_and_constant;
19use super::gt;
20use super::gt_eq;
21use super::lit;
22use super::lt;
23use super::lt_eq;
24use super::max_dist_sq;
25use super::min_dist_sq;
26use super::query_aabb;
27use crate::scalar_fn::distance::SpatialDistance;
28
29/// Prunes chunks for `ST_Distance(geom, const) <op> r` filters.
30///
31/// All four comparisons prune: `<= r` / `< r` skip a chunk whose box is wholly beyond `r` (box
32/// min-distance); `>= r` / `> r` skip one wholly within `r` (box max-distance). `==` / `!=` don't
33/// prune.
34#[derive(Debug)]
35pub struct SpatialDistancePrune;
36
37impl StatsRewriteRule for SpatialDistancePrune {
38    fn scalar_fn_id(&self) -> ScalarFnId {
39        // The predicate root is the comparison, not `SpatialDistance`, so key on `Compare`.
40        Compare.id()
41    }
42
43    fn falsify(
44        &self,
45        expr: &BoundExpression,
46        session: &VortexSession,
47    ) -> VortexResult<Option<BoundExpression>> {
48        // Only the ordered comparisons prune today. `== r` could prune in the future (a chunk is
49        // provably empty when `r` lies outside its box's [min, max] distance interval), it's just
50        // not implemented. `!= r` cannot: pruning would need every row's distance to equal `r`,
51        // which an AABB can't prove.
52        let op = *expr.as_::<Compare>();
53        if !matches!(
54            op,
55            CompareOperator::Lte | CompareOperator::Lt | CompareOperator::Gte | CompareOperator::Gt
56        ) {
57            return Ok(None);
58        }
59
60        // The left operand must be `SpatialDistance(geom, const)`; the right, the radius literal.
61        let distance = expr.child(0);
62        if distance.as_opt::<SpatialDistance>().is_none() {
63            return Ok(None);
64        }
65        let Some(radius) = expr.child(1).as_opt::<Literal>() else {
66            return Ok(None);
67        };
68        // Casts any primitive radius (filters arrive uncoerced, so integer literals are
69        // legitimate); a null or non-primitive (e.g. extension-typed) literal has no value to
70        // reason about, decline and scan, never error.
71        let Ok(radius) = f64::try_from(radius) else {
72            return Ok(None);
73        };
74        // A NaN radius has no sound proof: `distance <op> NaN` is not a total order, so the chunk
75        // must be scanned, not pruned.
76        if radius.is_nan() {
77            return Ok(None);
78        }
79
80        let Some((geom, constant)) = geometry_and_constant(distance)? else {
81            return Ok(None);
82        };
83        let Some(query) = query_aabb(constant, session)? else {
84            return Ok(None);
85        };
86        Ok(distance_prune_proof(geom, query, op, radius))
87    }
88}
89
90/// Build the prune proof for `ST_Distance(geom, const) <op> radius`, or `None` when this
91/// operator/radius cannot prune. The box-to-box distance bounds every row's true distance for any
92/// geometry types: `<=` / `<` prune a chunk whose box is wholly beyond `radius` (min
93/// box-distance); `>=` / `>` prune one wholly within it (max box-distance).
94///
95/// A distance is always `>= 0`, which decides the degenerate radii up front.
96fn distance_prune_proof(
97    geom: &BoundExpression,
98    query: SpatialRect<f64>,
99    op: CompareOperator,
100    radius: f64,
101) -> Option<BoundExpression> {
102    // A distance is always non-negative, so degenerate radii resolve without touching the box.
103    match op {
104        // `<= r` / `< r` with a negative radius (or zero, for `<`) match nothing: prune every chunk.
105        CompareOperator::Lte if radius < 0.0 => return Some(lit(true)),
106        CompareOperator::Lt if radius <= 0.0 => return Some(lit(true)),
107        // `>= r` / `> r` with a negative radius (or zero, for `>=`) match all rows: never prune.
108        CompareOperator::Gte if radius <= 0.0 => return None,
109        CompareOperator::Gt if radius < 0.0 => return None,
110        _ => {}
111    }
112    // Compared squared to avoid a `sqrt`; all operands are `>= 0`.
113    let aabb = aabb_stat(geom);
114    let r2 = lit(radius * radius);
115    Some(match op {
116        // Beyond the threshold: even the nearest the box can be exceeds `r`.
117        CompareOperator::Lte => gt(min_dist_sq(&aabb, query), r2),
118        CompareOperator::Lt => gt_eq(min_dist_sq(&aabb, query), r2),
119        // Within the threshold: even the farthest the box can be is below `r`.
120        CompareOperator::Gte => lt(max_dist_sq(&aabb, query), r2),
121        CompareOperator::Gt => lt_eq(max_dist_sq(&aabb, query), r2),
122        _ => return None,
123    })
124}
125
126#[cfg(test)]
127mod tests {
128    use rstest::rstest;
129    use vortex_array::VortexSessionExecute;
130    use vortex_array::dtype::DType;
131    use vortex_array::dtype::Nullability;
132    use vortex_array::dtype::PType;
133    use vortex_array::scalar::Scalar;
134    use vortex_array::scalar_fn::EmptyOptions;
135    use vortex_array::scalar_fn::builtin::compare::Compare;
136    use vortex_array::scalar_fn::builtin::operators::CompareOperator;
137    use vortex_error::VortexResult;
138    use vortex_expr::BoundExpression;
139    use vortex_expr::ScalarFnExprExt;
140    use vortex_expr::gt_eq;
141    use vortex_expr::lit;
142    use vortex_expr::lt_eq;
143    use vortex_expr::root;
144    use vortex_expr::stats::rewrite::BoundExpressionPruneExt;
145    use vortex_expr::stats::rewrite::StatsRewriteRule;
146
147    use super::SpatialDistancePrune;
148    use crate::prune::test_harness::aabb_zone_map;
149    use crate::prune::test_harness::empty_zone_map;
150    use crate::scalar_fn::distance::SpatialDistance;
151    use crate::test_harness::point_column;
152    use crate::test_harness::spatial_session;
153
154    /// Run the rule against `SpatialDistance(root, origin) <operator> radius`, operands swapped when
155    /// `geom_first` is false. The radius is any literal scalar, matching the uncoerced filter
156    /// expressions the rule sees in production.
157    fn falsify_distance(
158        operator: CompareOperator,
159        geom_first: bool,
160        radius: impl Into<Scalar>,
161    ) -> VortexResult<Option<BoundExpression>> {
162        let session = spatial_session();
163        let mut ctx = session.create_execution_ctx();
164
165        let scope = point_column(vec![0.0], vec![0.0])?.dtype().clone();
166        let origin = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
167        let operands = if geom_first {
168            [root(), lit(origin)]
169        } else {
170            [lit(origin), root()]
171        };
172        let distance = SpatialDistance.new_expr(EmptyOptions, operands);
173        let predicate = Compare
174            .new_expr(operator, [distance, lit(radius.into())])
175            .bind(&scope)?;
176
177        SpatialDistancePrune.falsify(&predicate, &session)
178    }
179
180    /// A null geometry literal (`ST_Distance(geom, NULL) <= r`) declines cleanly instead of
181    /// erroring in the stats rewrite: the all-null predicate can never prune.
182    #[test]
183    fn null_literal_is_not_pruned() -> VortexResult<()> {
184        let session = spatial_session();
185
186        let scope = point_column(vec![0.0], vec![0.0])?.dtype().clone();
187        let null_query = Scalar::null(scope.as_nullable());
188        let distance = SpatialDistance.new_expr(EmptyOptions, [root(), lit(null_query)]);
189        let predicate = Compare
190            .new_expr(CompareOperator::Lte, [distance, lit(0.5f64)])
191            .bind(&scope)?;
192
193        assert!(
194            SpatialDistancePrune
195                .falsify(&predicate, &session)?
196                .is_none()
197        );
198        Ok(())
199    }
200
201    /// All four distance comparisons prune (`<=`/`<` via min-distance, `>=`/`>` via max-distance);
202    /// `==`/`!=` are left to the scan.
203    #[rstest]
204    #[case(CompareOperator::Lte, Some([false, false, true]))]
205    #[case(CompareOperator::Lt, Some([false, true, true]))]
206    #[case(CompareOperator::Gt, Some([true, true, false]))]
207    #[case(CompareOperator::Gte, Some([true, false, false]))]
208    #[case(CompareOperator::Eq, None)]
209    #[case(CompareOperator::NotEq, None)]
210    fn prunes_distance_comparisons(
211        #[case] operator: CompareOperator,
212        #[case] expected: Option<[bool; 3]>,
213    ) -> VortexResult<()> {
214        let proof = falsify_distance(operator, true, 0.5)?;
215        assert_eq!(proof.is_some(), expected.is_some());
216        if let Some(expected) = expected {
217            let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
218            let zones = aabb_zone_map(
219                &dtype,
220                &[
221                    [0.0, 0.0, 0.0, 0.0],
222                    [0.5, 0.0, 0.5, 0.0],
223                    [1.0, 0.0, 1.0, 0.0],
224                ],
225            )?;
226            let mask = zones.prune(&proof.unwrap(), &spatial_session())?;
227            assert_eq!(mask.iter().collect::<Vec<_>>(), expected);
228        }
229        Ok(())
230    }
231
232    /// Distance is symmetric: both operand orders produce a proof.
233    #[rstest]
234    #[case(true)]
235    #[case(false)]
236    fn falsifies_either_operand_order(#[case] geom_first: bool) -> VortexResult<()> {
237        let proof =
238            falsify_distance(CompareOperator::Lte, geom_first, 0.5)?.expect("distance proof");
239        let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
240        let zones = aabb_zone_map(&dtype, &[[0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 1.0, 0.0]])?;
241        assert_eq!(
242            zones
243                .prune(&proof, &spatial_session())?
244                .iter()
245                .collect::<Vec<_>>(),
246            [false, true]
247        );
248        Ok(())
249    }
250
251    /// A NaN radius must not prune - the scan's total-order compare treats `dist <= NaN` as true.
252    #[test]
253    fn nan_radius_never_prunes() -> VortexResult<()> {
254        assert!(falsify_distance(CompareOperator::Lte, true, f64::NAN)?.is_none());
255        Ok(())
256    }
257
258    /// A negative radius prunes every zone - vacuously sound: `distance <= r < 0` matches no row.
259    #[test]
260    fn negative_radius_prunes_vacuously() -> VortexResult<()> {
261        let proof =
262            falsify_distance(CompareOperator::Lte, true, -0.5)?.expect("negative-radius proof");
263        let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
264        let zones = aabb_zone_map(&dtype, &[[0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 1.0, 0.0]])?;
265        assert_eq!(
266            zones
267                .prune(&proof, &spatial_session())?
268                .iter()
269                .collect::<Vec<_>>(),
270            [true, true]
271        );
272        Ok(())
273    }
274
275    /// An uncoerced integer radius is rejected while binding the comparison.
276    #[test]
277    fn uncoerced_integer_radius_fails_to_bind() -> VortexResult<()> {
278        assert!(falsify_distance(CompareOperator::Lte, true, 10i64).is_err());
279        Ok(())
280    }
281
282    /// A null radius has no value to reason about; the rule declines and the chunk is scanned.
283    #[test]
284    fn null_radius_never_prunes() -> VortexResult<()> {
285        let radius = Scalar::null(DType::Primitive(PType::F64, Nullability::Nullable));
286        assert!(falsify_distance(CompareOperator::Lte, true, radius)?.is_none());
287        Ok(())
288    }
289
290    /// A geometry scalar is not a numeric radius, so the comparison fails while binding.
291    #[test]
292    fn test_extension_radius_fails_binding() -> VortexResult<()> {
293        let session = spatial_session();
294        let mut ctx = session.create_execution_ctx();
295
296        let geometry = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
297        let scope = geometry.dtype().clone();
298        let distance = SpatialDistance.new_expr(EmptyOptions, [root(), lit(geometry.clone())]);
299        let predicate = Compare.new_expr(CompareOperator::Lte, [distance, lit(geometry)]);
300        let error = predicate
301            .bind(&scope)
302            .expect_err("a geometry scalar cannot be compared with a numeric distance");
303        assert!(
304            error
305                .to_string()
306                .contains("Comparison requires equal dtypes ignoring nullability")
307        );
308
309        Ok(())
310    }
311
312    /// A non-geometry scope is rejected while binding, before stats rewriting.
313    #[test]
314    fn unsupported_scope_is_not_pruned() -> VortexResult<()> {
315        let session = spatial_session();
316        let mut ctx = session.create_execution_ctx();
317
318        let scope = DType::Primitive(PType::F64, Nullability::NonNullable);
319        let origin = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
320        let distance = SpatialDistance.new_expr(EmptyOptions, [root(), lit(origin)]);
321        let predicate = lt_eq(distance, lit(0.5f64));
322        assert!(predicate.bind(&scope).is_err());
323        Ok(())
324    }
325
326    /// A comparison that does not wrap `SpatialDistance` is left untouched.
327    #[test]
328    fn ignores_non_distance_comparison() -> VortexResult<()> {
329        let session = spatial_session();
330        let scope = point_column(vec![0.0], vec![0.0])?.dtype().clone();
331
332        let predicate = lt_eq(lit(1.0f64), lit(2.0f64)).bind(&scope)?;
333        assert!(
334            SpatialDistancePrune
335                .falsify(&predicate, &session)?
336                .is_none()
337        );
338        Ok(())
339    }
340
341    /// End-to-end over a hand-built zone map: the far chunk is skipped, the near one kept.
342    #[test]
343    fn prunes_far_chunk_keeps_near() -> VortexResult<()> {
344        let session = spatial_session();
345        let mut ctx = session.create_execution_ctx();
346
347        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
348        // Chunk 0 near the origin (0,0..1,1), chunk 1 far away (100,100..101,101).
349        let zone_map = aabb_zone_map(
350            &point_dtype,
351            &[[0.0, 0.0, 1.0, 1.0], [100.0, 100.0, 101.0, 101.0]],
352        )?;
353
354        let origin = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
355        let distance = SpatialDistance.new_expr(EmptyOptions, [root(), lit(origin)]);
356        let predicate = lt_eq(distance, lit(0.5f64));
357        let proof = predicate
358            .bind(&point_dtype)?
359            .falsify(&session)?
360            .expect("distance filter should be falsifiable");
361
362        // `true` means the zone is pruned: chunk 0 (near origin) is kept, chunk 1 (far) is skipped.
363        let mask = zone_map.prune(&proof, &session)?;
364        assert_eq!(mask.iter().collect::<Vec<bool>>(), vec![false, true]);
365        Ok(())
366    }
367
368    /// The true-distance prune skips a chunk that is *diagonally* farther than `r`, even though
369    /// neither axis alone exceeds `r`, the case a per-axis box-overlap test would wrongly keep.
370    #[test]
371    fn prunes_diagonally_distant_chunk() -> VortexResult<()> {
372        let session = spatial_session();
373        let mut ctx = session.create_execution_ctx();
374
375        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
376        // One chunk, AABB (0.8,0.8)..(0.9,0.9): each axis is only 0.8 from the origin (<= r = 1), but
377        // the near corner is sqrt(0.8^2 + 0.8^2) ~= 1.13 away (> 1), so no point in the box is within 1.
378        let zone_map = aabb_zone_map(&point_dtype, &[[0.8, 0.8, 0.9, 0.9]])?;
379
380        let origin = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
381        let distance = SpatialDistance.new_expr(EmptyOptions, [root(), lit(origin)]);
382        let predicate = lt_eq(distance, lit(1.0f64));
383        let proof = predicate
384            .bind(&point_dtype)?
385            .falsify(&session)?
386            .expect("distance filter should be falsifiable");
387
388        assert_eq!(
389            zone_map
390                .prune(&proof, &session)?
391                .iter()
392                .collect::<Vec<bool>>(),
393            vec![true],
394        );
395        Ok(())
396    }
397
398    /// A `>= r` filter prunes a chunk lying wholly *within* `r` (every row nearer than `r`, so none
399    /// satisfy `>= r`) via the box max-distance, while a chunk beyond `r` is kept.
400    #[test]
401    fn prunes_within_chunk_for_far_filter() -> VortexResult<()> {
402        let session = spatial_session();
403        let mut ctx = session.create_execution_ctx();
404
405        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
406        // Chunk 0 (AABB 0,0..0.5,0.5, farthest corner ~= 0.707) is entirely within 2 of the origin;
407        // chunk 1 (100,100..101,101) is entirely beyond it.
408        let zone_map = aabb_zone_map(
409            &point_dtype,
410            &[[0.0, 0.0, 0.5, 0.5], [100.0, 100.0, 101.0, 101.0]],
411        )?;
412
413        let origin = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
414        let distance = SpatialDistance.new_expr(EmptyOptions, [root(), lit(origin)]);
415        let proof = gt_eq(distance, lit(2.0f64))
416            .bind(&point_dtype)?
417            .falsify(&session)?
418            .expect("distance filter should be falsifiable");
419
420        // Chunk 0 (within 2) is pruned for `>= 2`; chunk 1 (beyond 2) is kept.
421        let mask = zone_map.prune(&proof, &session)?;
422        assert_eq!(mask.iter().collect::<Vec<bool>>(), vec![true, false]);
423        Ok(())
424    }
425
426    #[test]
427    fn missing_aabb_stat_keeps_all_zones() -> VortexResult<()> {
428        let session = spatial_session();
429        let mut ctx = session.create_execution_ctx();
430
431        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
432        let zone_map = empty_zone_map(&point_dtype)?;
433
434        let origin = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
435        let distance = SpatialDistance.new_expr(EmptyOptions, [root(), lit(origin)]);
436        let proof = lt_eq(distance, lit(0.5f64))
437            .bind(&point_dtype)?
438            .falsify(&session)?
439            .expect("distance filter should be falsifiable");
440
441        let mask = zone_map.prune(&proof, &session)?;
442        assert_eq!(mask.iter().collect::<Vec<bool>>(), vec![false, false]);
443        Ok(())
444    }
445}