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_error::VortexResult;
10use vortex_expr::stats::rewrite::StatsRewriteRule;
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_error::VortexResult;
66    use vortex_expr::stats::rewrite::BoundExpressionPruneExt;
67    use vortex_expr::stats::rewrite::StatsRewriteRule;
68
69    use super::SpatialIntersectsPrune;
70    use crate::prune::test_harness::aabb_zone_map;
71    use crate::prune::test_harness::empty_zone_map;
72    use crate::scalar_fn::intersects::SpatialIntersects;
73    use crate::test_harness::point_column;
74    use crate::test_harness::spatial_session;
75
76    /// Run the intersects rule against `SpatialIntersects(root, point(1.0, 0.5))`, operands swapped
77    /// when `geom_first` is false.
78    fn falsify_intersects(geom_first: bool) -> VortexResult<Option<BoundExpression>> {
79        let session = spatial_session();
80        let mut ctx = session.create_execution_ctx();
81
82        let scope = point_column(vec![0.0], vec![0.0])?.dtype().clone();
83        let query = point_column(vec![1.0], vec![0.5])?.execute_scalar(0, &mut ctx)?;
84        let operands = if geom_first {
85            [root(), lit(query)]
86        } else {
87            [lit(query), root()]
88        };
89        let predicate = SpatialIntersects
90            .new_expr(EmptyOptions, operands)
91            .bind(&scope)?;
92        SpatialIntersectsPrune.falsify(&predicate, &session)
93    }
94
95    /// Intersects is symmetric: both operand orders produce a proof.
96    #[rstest]
97    #[case(true)]
98    #[case(false)]
99    fn falsifies_either_operand_order(#[case] geom_first: bool) -> VortexResult<()> {
100        let proof = falsify_intersects(geom_first)?.expect("intersection proof");
101        let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
102        let zones = aabb_zone_map(&dtype, &[[0.0, 0.0, 1.0, 1.0], [3.0, 0.0, 4.0, 1.0]])?;
103        assert_eq!(
104            zones
105                .prune(&proof, &spatial_session())?
106                .iter()
107                .collect::<Vec<_>>(),
108            [false, true]
109        );
110        Ok(())
111    }
112
113    /// A non-geometry scope is rejected while binding, before stats rewriting.
114    #[test]
115    fn unsupported_scope_is_not_pruned() -> VortexResult<()> {
116        let session = spatial_session();
117        let mut ctx = session.create_execution_ctx();
118
119        let scope = DType::Primitive(PType::F64, Nullability::NonNullable);
120        let query = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
121        let predicate = SpatialIntersects.new_expr(EmptyOptions, [root(), lit(query)]);
122        assert!(predicate.bind(&scope).is_err());
123        Ok(())
124    }
125
126    /// A null geometry literal (`ST_Intersects(geom, NULL)`) declines cleanly instead of erroring
127    /// in the stats rewrite: the all-null predicate can never prune.
128    #[test]
129    fn null_literal_is_not_pruned() -> VortexResult<()> {
130        let session = spatial_session();
131
132        let scope = point_column(vec![0.0], vec![0.0])?.dtype().clone();
133        let null_query = Scalar::null(scope.as_nullable());
134        let predicate = SpatialIntersects
135            .new_expr(EmptyOptions, [root(), lit(null_query)])
136            .bind(&scope)?;
137
138        assert!(
139            SpatialIntersectsPrune
140                .falsify(&predicate, &session)?
141                .is_none()
142        );
143        Ok(())
144    }
145
146    /// End-to-end: a zone strictly separated from the query is skipped; zones containing or merely
147    /// touching the query must scan, touching geometries intersect under OGC semantics.
148    #[test]
149    fn prunes_disjoint_keeps_touching_and_containing() -> VortexResult<()> {
150        let session = spatial_session();
151        let mut ctx = session.create_execution_ctx();
152
153        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
154        // Query point (1.0, 0.5): zone 0 contains it, zone 1 only touches it at `x == 1`, zone 2
155        // is strictly separated.
156        let zone_map = aabb_zone_map(
157            &point_dtype,
158            &[
159                [0.5, 0.0, 1.5, 1.0],
160                [-1.0, 0.0, 1.0, 1.0],
161                [3.0, 0.0, 4.0, 1.0],
162            ],
163        )?;
164
165        let query = point_column(vec![1.0], vec![0.5])?.execute_scalar(0, &mut ctx)?;
166        let predicate = SpatialIntersects.new_expr(EmptyOptions, [root(), lit(query)]);
167        let proof = predicate
168            .bind(&point_dtype)?
169            .falsify(&session)?
170            .expect("intersects filter should be falsifiable");
171
172        let mask = zone_map.prune(&proof, &session)?;
173        assert_eq!(mask.iter().collect::<Vec<bool>>(), vec![false, false, true]);
174        Ok(())
175    }
176
177    /// Backward compat: a zone map written without the `GeometryAabb` stat keeps every zone.
178    #[test]
179    fn missing_aabb_stat_keeps_all_zones() -> VortexResult<()> {
180        let session = spatial_session();
181        let mut ctx = session.create_execution_ctx();
182
183        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
184        let zone_map = empty_zone_map(&point_dtype)?;
185
186        let query = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
187        let proof = SpatialIntersects
188            .new_expr(EmptyOptions, [root(), lit(query)])
189            .bind(&point_dtype)?
190            .falsify(&session)?
191            .expect("intersects filter should be falsifiable");
192
193        let mask = zone_map.prune(&proof, &session)?;
194        assert_eq!(mask.iter().collect::<Vec<bool>>(), vec![false, false]);
195        Ok(())
196    }
197}