Skip to main content

vortex_spatial/prune/
intersects.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! `ST_Intersects(geom, const)` pruning.
5
6use vortex_array::expr::BoundExpression;
7use vortex_array::scalar_fn::ScalarFnId;
8use vortex_array::scalar_fn::ScalarFnVTable;
9use vortex_array::stats::rewrite::StatsRewriteRule;
10use vortex_error::VortexResult;
11use vortex_session::VortexSession;
12
13use super::aabb_stat;
14use super::geometry_and_constant;
15use super::gt;
16use super::lit;
17use super::min_dist_sq;
18use super::query_aabb;
19use crate::scalar_fn::intersects::SpatialIntersects;
20
21/// Prunes chunks for `ST_Intersects(geom, const)` filters: a chunk whose box is strictly
22/// separated from the constant's bounding box cannot contain an intersecting row.
23///
24/// Only the positive form prunes. `NOT ST_Intersects` cannot: it would need every row to provably
25/// intersect the constant, and box overlap never proves geometry intersection.
26#[derive(Debug)]
27pub struct SpatialIntersectsPrune;
28
29impl StatsRewriteRule for SpatialIntersectsPrune {
30    fn scalar_fn_id(&self) -> ScalarFnId {
31        // Unlike the distance rule, the boolean predicate is itself the expression root.
32        SpatialIntersects.id()
33    }
34
35    fn falsify(
36        &self,
37        expr: &BoundExpression,
38        session: &VortexSession,
39    ) -> VortexResult<Option<BoundExpression>> {
40        let Some((geom, constant)) = geometry_and_constant(expr)? else {
41            return Ok(None);
42        };
43        let Some(query) = query_aabb(constant, session)? else {
44            return Ok(None);
45        };
46        // Disjoint iff the minimum box-to-box distance is positive. Strictly (`gt`, not `gt_eq`):
47        // boxes that merely touch must scan, since touching geometries do intersect.
48        Ok(Some(gt(min_dist_sq(&aabb_stat(geom), query), lit(0.0))))
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use rstest::rstest;
55    use vortex_array::VortexSessionExecute;
56    use vortex_array::dtype::DType;
57    use vortex_array::dtype::Nullability;
58    use vortex_array::dtype::PType;
59    use vortex_array::expr::BoundExpression;
60    use vortex_array::expr::lit;
61    use vortex_array::expr::root;
62    use vortex_array::scalar::Scalar;
63    use vortex_array::scalar_fn::EmptyOptions;
64    use vortex_array::scalar_fn::ScalarFnVTableExt;
65    use vortex_array::stats::rewrite::StatsRewriteRule;
66    use vortex_error::VortexResult;
67
68    use super::SpatialIntersectsPrune;
69    use crate::prune::test_harness::aabb_zone_map;
70    use crate::prune::test_harness::empty_zone_map;
71    use crate::scalar_fn::intersects::SpatialIntersects;
72    use crate::test_harness::point_column;
73    use crate::test_harness::spatial_session;
74
75    /// Run the intersects rule against `SpatialIntersects(root, point(1.0, 0.5))`, operands swapped
76    /// when `geom_first` is false.
77    fn falsify_intersects(geom_first: bool) -> VortexResult<Option<BoundExpression>> {
78        let session = spatial_session();
79        let mut ctx = session.create_execution_ctx();
80
81        let scope = point_column(vec![0.0], vec![0.0])?.dtype().clone();
82        let query = point_column(vec![1.0], vec![0.5])?.execute_scalar(0, &mut ctx)?;
83        let operands = if geom_first {
84            [root(), lit(query)]
85        } else {
86            [lit(query), root()]
87        };
88        let predicate = SpatialIntersects
89            .new_expr(EmptyOptions, operands)
90            .bind(&scope)?;
91        SpatialIntersectsPrune.falsify(&predicate, &session)
92    }
93
94    /// Intersects is symmetric: both operand orders produce a proof.
95    #[rstest]
96    #[case(true)]
97    #[case(false)]
98    fn falsifies_either_operand_order(#[case] geom_first: bool) -> VortexResult<()> {
99        let proof = falsify_intersects(geom_first)?.expect("intersection proof");
100        let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
101        let zones = aabb_zone_map(&dtype, &[[0.0, 0.0, 1.0, 1.0], [3.0, 0.0, 4.0, 1.0]])?;
102        assert_eq!(
103            zones
104                .prune(&proof, &spatial_session())?
105                .iter()
106                .collect::<Vec<_>>(),
107            [false, true]
108        );
109        Ok(())
110    }
111
112    /// A non-geometry scope is rejected while binding, before stats rewriting.
113    #[test]
114    fn unsupported_scope_is_not_pruned() -> VortexResult<()> {
115        let session = spatial_session();
116        let mut ctx = session.create_execution_ctx();
117
118        let scope = DType::Primitive(PType::F64, Nullability::NonNullable);
119        let query = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
120        let predicate = SpatialIntersects.new_expr(EmptyOptions, [root(), lit(query)]);
121        assert!(predicate.bind(&scope).is_err());
122        Ok(())
123    }
124
125    /// A null geometry literal (`ST_Intersects(geom, NULL)`) declines cleanly instead of erroring
126    /// in the stats rewrite: the all-null predicate can never prune.
127    #[test]
128    fn null_literal_is_not_pruned() -> VortexResult<()> {
129        let session = spatial_session();
130
131        let scope = point_column(vec![0.0], vec![0.0])?.dtype().clone();
132        let null_query = Scalar::null(scope.as_nullable());
133        let predicate = SpatialIntersects
134            .new_expr(EmptyOptions, [root(), lit(null_query)])
135            .bind(&scope)?;
136
137        assert!(
138            SpatialIntersectsPrune
139                .falsify(&predicate, &session)?
140                .is_none()
141        );
142        Ok(())
143    }
144
145    /// End-to-end: a zone strictly separated from the query is skipped; zones containing or merely
146    /// touching the query must scan, touching geometries intersect under OGC semantics.
147    #[test]
148    fn prunes_disjoint_keeps_touching_and_containing() -> VortexResult<()> {
149        let session = spatial_session();
150        let mut ctx = session.create_execution_ctx();
151
152        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
153        // Query point (1.0, 0.5): zone 0 contains it, zone 1 only touches it at `x == 1`, zone 2
154        // is strictly separated.
155        let zone_map = aabb_zone_map(
156            &point_dtype,
157            &[
158                [0.5, 0.0, 1.5, 1.0],
159                [-1.0, 0.0, 1.0, 1.0],
160                [3.0, 0.0, 4.0, 1.0],
161            ],
162        )?;
163
164        let query = point_column(vec![1.0], vec![0.5])?.execute_scalar(0, &mut ctx)?;
165        let predicate = SpatialIntersects.new_expr(EmptyOptions, [root(), lit(query)]);
166        let proof = predicate
167            .bind(&point_dtype)?
168            .falsify(&session)?
169            .expect("intersects filter should be falsifiable");
170
171        let mask = zone_map.prune(&proof, &session)?;
172        assert_eq!(mask.iter().collect::<Vec<bool>>(), vec![false, false, true]);
173        Ok(())
174    }
175
176    /// Backward compat: a zone map written without the `GeometryAabb` stat keeps every zone.
177    #[test]
178    fn missing_aabb_stat_keeps_all_zones() -> VortexResult<()> {
179        let session = spatial_session();
180        let mut ctx = session.create_execution_ctx();
181
182        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
183        let zone_map = empty_zone_map(&point_dtype)?;
184
185        let query = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
186        let proof = SpatialIntersects
187            .new_expr(EmptyOptions, [root(), lit(query)])
188            .bind(&point_dtype)?
189            .falsify(&session)?
190            .expect("intersects filter should be falsifiable");
191
192        let mask = zone_map.prune(&proof, &session)?;
193        assert_eq!(mask.iter().collect::<Vec<bool>>(), vec![false, false]);
194        Ok(())
195    }
196}