vortex_spatial/prune/mod.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Chunk pruning for spatial filters, using the per-chunk [`GeometryAabb`] axis-aligned
5//! bounding box (AABB).
6//!
7//! One module per predicate. To prune a new one: recover the geometry column and the constant
8//! (symmetric predicates can use `geometry_and_constant`), reduce the constant to its box with
9//! `query_aabb`, build the proof over `aabb_stat` from the box-relation builders (`min_dist_sq`,
10//! `max_dist_sq`), and register the rule in [`crate::initialize`]. No new statistic or
11//! file-format change is needed.
12
13mod distance;
14mod intersects;
15#[cfg(test)]
16mod test_harness;
17
18pub use distance::SpatialDistancePrune;
19use geo::BoundingRect;
20use geo::Rect as SpatialRect;
21pub use intersects::SpatialIntersectsPrune;
22use vortex_array::VortexSessionExecute;
23use vortex_array::aggregate_fn::AggregateFnVTableExt;
24use vortex_array::aggregate_fn::EmptyOptions;
25use vortex_array::expr::BoundExpression;
26use vortex_array::expr::bound::binary;
27use vortex_array::expr::bound::case_when;
28use vortex_array::expr::bound::checked_add;
29use vortex_array::expr::bound::ext_storage;
30use vortex_array::expr::bound::get_item;
31use vortex_array::expr::bound::gt;
32use vortex_array::expr::bound::gt_eq;
33use vortex_array::expr::bound::lit;
34use vortex_array::expr::bound::lt;
35use vortex_array::expr::bound::lt_eq;
36use vortex_array::scalar::Scalar;
37use vortex_array::scalar_fn::fns::literal::Literal;
38use vortex_array::scalar_fn::fns::operators::Operator;
39use vortex_array::stats::bound::stat;
40use vortex_array::stats::rewrite::StatsRewriteCtx;
41use vortex_error::VortexResult;
42
43use crate::aggregate_fn::GeometryAabb;
44use crate::extension::is_native_geometry;
45use crate::extension::single_geometry;
46
47/// Splits a symmetric two-operand spatial predicate into the scope-rooted geometry column and the
48/// constant operand's scalar.
49///
50/// `None` means the rule must decline: the expression doesn't have the `f(column, constant)`
51/// shape (in either operand order), or the column's dtype carries no [`GeometryAabb`] statistic.
52/// An asymmetric predicate (e.g. a future contains) must recover which operand is the column
53/// itself instead of calling this.
54fn geometry_and_constant<'a>(
55 expr: &'a BoundExpression,
56 ctx: &StatsRewriteCtx<'_>,
57) -> VortexResult<Option<(&'a BoundExpression, &'a Scalar)>> {
58 // The predicate is symmetric, so the column (scope root) and the constant may be on either
59 // side.
60 let (lhs, rhs) = (expr.child(0), expr.child(1));
61 let (geom, constant) = if lhs.is_root() {
62 (lhs, rhs)
63 } else if rhs.is_root() {
64 (rhs, lhs)
65 } else {
66 return Ok(None);
67 };
68
69 // A `GeometryAabb` stat reference only binds for dtypes it supports; anything else (e.g. a
70 // WKB column) must fall through to the scan.
71 if !is_native_geometry(&ctx.return_dtype(geom)?) {
72 return Ok(None);
73 }
74
75 Ok(constant.as_opt::<Literal>().map(|scalar| (geom, scalar)))
76}
77
78/// The 2D bounding box of a constant geometry of any type, or `None` for one without an extent
79/// (e.g. an empty geometry).
80///
81/// Prove claims against this box rather than the constant itself: the constant lies inside it,
82/// so whatever holds for the box holds for the geometry.
83fn query_aabb(
84 constant: &Scalar,
85 ctx: &StatsRewriteCtx<'_>,
86) -> VortexResult<Option<SpatialRect<f64>>> {
87 // A null geometry literal has no extent to prove against, so it can never prune.
88 if constant.is_null() {
89 return Ok(None);
90 }
91 // Decoding the constant into a concrete geometry runs through the compute stack, which needs
92 // an execution context.
93 let mut exec = ctx.session().create_execution_ctx();
94 Ok(single_geometry(constant, &mut exec)?.bounding_rect())
95}
96
97/// The chunk's AABB statistic, as the storage struct with `xmin`/`ymin`/`xmax`/`ymax` fields.
98///
99/// A chunk written without the statistic reads as null here; every proof built on top must let
100/// that null propagate to its root, where the zone map keeps the chunk.
101fn aabb_stat(geom: &BoundExpression) -> BoundExpression {
102 // `ext_storage` unwraps the native `geoarrow.box` stat value to its backing struct, so
103 // proofs can `get_item` the coordinate fields.
104 ext_storage(stat(geom.clone(), GeometryAabb.bind(EmptyOptions)))
105}
106
107/// Lower bound on every row's squared distance to the query AABB: zero when the boxes overlap or
108/// touch, positive iff they are strictly separated.
109///
110/// Prunes "near" predicates: `min_dist_sq > r^2` proves every row is farther than `r`.
111fn min_dist_sq(aabb: &BoundExpression, query: SpatialRect<f64>) -> BoundExpression {
112 let field = |name: &str| get_item(name, aabb.clone());
113 // Per axis: gap = max(0, q_lo - aabb_hi, aabb_lo - q_hi), positive only when the intervals
114 // are separated. The nearest two points of the boxes are one axis-gap apart per axis, so the
115 // squared distance is gap_x^2 + gap_y^2 (squared throughout to avoid a sqrt).
116 let gap = |q_lo: f64, q_hi: f64, lo: BoundExpression, hi: BoundExpression| {
117 maximum(
118 lit(0.0),
119 maximum(
120 binary(Operator::Sub, lit(q_lo), hi),
121 binary(Operator::Sub, lo, lit(q_hi)),
122 ),
123 )
124 };
125 let dx = gap(query.min().x, query.max().x, field("xmin"), field("xmax"));
126 let dy = gap(query.min().y, query.max().y, field("ymin"), field("ymax"));
127 checked_add(square(dx), square(dy))
128}
129
130/// Upper bound on every row's squared distance to the query AABB.
131///
132/// Prunes "far" predicates: `max_dist_sq < r^2` proves every row is within `r`.
133fn max_dist_sq(aabb: &BoundExpression, query: SpatialRect<f64>) -> BoundExpression {
134 let field = |name: &str| get_item(name, aabb.clone());
135 // Per axis: span = max(q_hi, aabb_hi) - min(q_lo, aabb_lo), the farthest two points of the
136 // boxes can be apart. The nullable AABB field is the second `maximum`/`minimum` argument so
137 // that `case_when`'s else branch carries the nullability - a missing stat propagates null.
138 let span = |q_lo: f64, q_hi: f64, lo: BoundExpression, hi: BoundExpression| {
139 binary(
140 Operator::Sub,
141 maximum(lit(q_hi), hi),
142 minimum(lit(q_lo), lo),
143 )
144 };
145 let dx = span(query.min().x, query.max().x, field("xmin"), field("xmax"));
146 let dy = span(query.min().y, query.max().y, field("ymin"), field("ymax"));
147 checked_add(square(dx), square(dy))
148}
149
150/// `e * e`.
151fn square(e: BoundExpression) -> BoundExpression {
152 binary(Operator::Mul, e.clone(), e)
153}
154
155/// `max(a, b)`.
156fn maximum(a: BoundExpression, b: BoundExpression) -> BoundExpression {
157 case_when(gt(a.clone(), b.clone()), a, b)
158}
159
160/// `min(a, b)`.
161fn minimum(a: BoundExpression, b: BoundExpression) -> BoundExpression {
162 case_when(lt(a.clone(), b.clone()), a, b)
163}