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::StatsRewriteCtx;
10use vortex_array::stats::rewrite::StatsRewriteRule;
11use vortex_error::VortexResult;
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        ctx: &StatsRewriteCtx<'_>,
39    ) -> VortexResult<Option<BoundExpression>> {
40        let Some((geom, constant)) = geometry_and_constant(expr, ctx)? else {
41            return Ok(None);
42        };
43        let Some(query) = query_aabb(constant, ctx)? 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::StatsRewriteCtx;
66    use vortex_array::stats::rewrite::StatsRewriteRule;
67    use vortex_error::VortexResult;
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, &StatsRewriteCtx::new(&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        assert!(falsify_intersects(geom_first)?.is_some());
101        Ok(())
102    }
103
104    /// A non-geometry scope is rejected while binding, before stats rewriting.
105    #[test]
106    fn unsupported_scope_is_not_pruned() -> VortexResult<()> {
107        let session = spatial_session();
108        let mut ctx = session.create_execution_ctx();
109
110        let scope = DType::Primitive(PType::F64, Nullability::NonNullable);
111        let query = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
112        let predicate = SpatialIntersects.new_expr(EmptyOptions, [root(), lit(query)]);
113        assert!(predicate.bind(&scope).is_err());
114        Ok(())
115    }
116
117    /// A null geometry literal (`ST_Intersects(geom, NULL)`) declines cleanly instead of erroring
118    /// in the stats rewrite: the all-null predicate can never prune.
119    #[test]
120    fn null_literal_is_not_pruned() -> VortexResult<()> {
121        let session = spatial_session();
122
123        let scope = point_column(vec![0.0], vec![0.0])?.dtype().clone();
124        let null_query = Scalar::null(scope.as_nullable());
125        let predicate = SpatialIntersects
126            .new_expr(EmptyOptions, [root(), lit(null_query)])
127            .bind(&scope)?;
128
129        let ctx = StatsRewriteCtx::new(&session);
130        assert!(SpatialIntersectsPrune.falsify(&predicate, &ctx)?.is_none());
131        Ok(())
132    }
133
134    /// End-to-end: a zone strictly separated from the query is skipped; zones containing or merely
135    /// touching the query must scan, touching geometries intersect under OGC semantics.
136    #[test]
137    fn prunes_disjoint_keeps_touching_and_containing() -> VortexResult<()> {
138        let session = spatial_session();
139        let mut ctx = session.create_execution_ctx();
140
141        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
142        // Query point (1.0, 0.5): zone 0 contains it, zone 1 only touches it at `x == 1`, zone 2
143        // is strictly separated.
144        let zone_map = aabb_zone_map(
145            &point_dtype,
146            &[
147                [0.5, 0.0, 1.5, 1.0],
148                [-1.0, 0.0, 1.0, 1.0],
149                [3.0, 0.0, 4.0, 1.0],
150            ],
151        )?;
152
153        let query = point_column(vec![1.0], vec![0.5])?.execute_scalar(0, &mut ctx)?;
154        let predicate = SpatialIntersects.new_expr(EmptyOptions, [root(), lit(query)]);
155        let proof = predicate
156            .bind(&point_dtype)?
157            .falsify(&session)?
158            .expect("intersects filter should be falsifiable");
159
160        let mask = zone_map.prune(&proof, &session)?;
161        assert_eq!(mask.iter().collect::<Vec<bool>>(), vec![false, false, true]);
162        Ok(())
163    }
164
165    /// Backward compat: a zone map written without the `GeometryAabb` stat keeps every zone.
166    #[test]
167    fn missing_aabb_stat_keeps_all_zones() -> VortexResult<()> {
168        let session = spatial_session();
169        let mut ctx = session.create_execution_ctx();
170
171        let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
172        let zone_map = empty_zone_map(&point_dtype)?;
173
174        let query = point_column(vec![0.0], vec![0.0])?.execute_scalar(0, &mut ctx)?;
175        let proof = SpatialIntersects
176            .new_expr(EmptyOptions, [root(), lit(query)])
177            .bind(&point_dtype)?
178            .falsify(&session)?
179            .expect("intersects filter should be falsifiable");
180
181        let mask = zone_map.prune(&proof, &session)?;
182        assert_eq!(mask.iter().collect::<Vec<bool>>(), vec![false, false]);
183        Ok(())
184    }
185}