Skip to main content

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_error::VortexResult;
40use vortex_expr::stats::bound::stat;
41use vortex_session::VortexSession;
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(
55    expr: &BoundExpression,
56) -> VortexResult<Option<(&BoundExpression, &Scalar)>> {
57    // The predicate is symmetric, so the column (scope root) and the constant may be on either
58    // side.
59    let (lhs, rhs) = (expr.child(0), expr.child(1));
60    let (geom, constant) = if lhs.is_root() {
61        (lhs, rhs)
62    } else if rhs.is_root() {
63        (rhs, lhs)
64    } else {
65        return Ok(None);
66    };
67
68    // A `GeometryAabb` stat reference only binds for dtypes it supports; anything else (e.g. a
69    // WKB column) must fall through to the scan.
70    if !is_native_geometry(geom.dtype()) {
71        return Ok(None);
72    }
73
74    Ok(constant.as_opt::<Literal>().map(|scalar| (geom, scalar)))
75}
76
77/// The 2D bounding box of a constant geometry of any type, or `None` for one without an extent
78/// (e.g. an empty geometry).
79///
80/// Prove claims against this box rather than the constant itself: the constant lies inside it,
81/// so whatever holds for the box holds for the geometry.
82fn query_aabb(
83    constant: &Scalar,
84    session: &VortexSession,
85) -> VortexResult<Option<SpatialRect<f64>>> {
86    // A null geometry literal has no extent to prove against, so it can never prune.
87    if constant.is_null() {
88        return Ok(None);
89    }
90    // Decoding the constant into a concrete geometry runs through the compute stack, which needs
91    // an execution context.
92    let mut exec = session.create_execution_ctx();
93    Ok(single_geometry(constant, &mut exec)?.bounding_rect())
94}
95
96/// The chunk's AABB statistic, as the storage struct with `xmin`/`ymin`/`xmax`/`ymax` fields.
97///
98/// A chunk written without the statistic reads as null here; every proof built on top must let
99/// that null propagate to its root, where the zone map keeps the chunk.
100fn aabb_stat(geom: &BoundExpression) -> BoundExpression {
101    // `ext_storage` unwraps the native `geoarrow.box` stat value to its backing struct, so
102    // proofs can `get_item` the coordinate fields.
103    ext_storage(stat(geom.clone(), GeometryAabb.bind(EmptyOptions)))
104}
105
106/// Lower bound on every row's squared distance to the query AABB: zero when the boxes overlap or
107/// touch, positive iff they are strictly separated.
108///
109/// Prunes "near" predicates: `min_dist_sq > r^2` proves every row is farther than `r`.
110fn min_dist_sq(aabb: &BoundExpression, query: SpatialRect<f64>) -> BoundExpression {
111    let field = |name: &str| get_item(name, aabb.clone());
112    // Per axis: gap = max(0, q_lo - aabb_hi, aabb_lo - q_hi), positive only when the intervals
113    // are separated. The nearest two points of the boxes are one axis-gap apart per axis, so the
114    // squared distance is gap_x^2 + gap_y^2 (squared throughout to avoid a sqrt).
115    let gap = |q_lo: f64, q_hi: f64, lo: BoundExpression, hi: BoundExpression| {
116        maximum(
117            lit(0.0),
118            maximum(
119                binary(Operator::Sub, lit(q_lo), hi),
120                binary(Operator::Sub, lo, lit(q_hi)),
121            ),
122        )
123    };
124    let dx = gap(query.min().x, query.max().x, field("xmin"), field("xmax"));
125    let dy = gap(query.min().y, query.max().y, field("ymin"), field("ymax"));
126    checked_add(square(dx), square(dy))
127}
128
129/// Upper bound on every row's squared distance to the query AABB.
130///
131/// Prunes "far" predicates: `max_dist_sq < r^2` proves every row is within `r`.
132fn max_dist_sq(aabb: &BoundExpression, query: SpatialRect<f64>) -> BoundExpression {
133    let field = |name: &str| get_item(name, aabb.clone());
134    // Per axis: span = max(q_hi, aabb_hi) - min(q_lo, aabb_lo), the farthest two points of the
135    // boxes can be apart. The nullable AABB field is the second `maximum`/`minimum` argument so
136    // that `case_when`'s else branch carries the nullability - a missing stat propagates null.
137    let span = |q_lo: f64, q_hi: f64, lo: BoundExpression, hi: BoundExpression| {
138        binary(
139            Operator::Sub,
140            maximum(lit(q_hi), hi),
141            minimum(lit(q_lo), lo),
142        )
143    };
144    let dx = span(query.min().x, query.max().x, field("xmin"), field("xmax"));
145    let dy = span(query.min().y, query.max().y, field("ymin"), field("ymax"));
146    checked_add(square(dx), square(dy))
147}
148
149/// `e * e`.
150fn square(e: BoundExpression) -> BoundExpression {
151    binary(Operator::Mul, e.clone(), e)
152}
153
154/// `max(a, b)`.
155fn maximum(a: BoundExpression, b: BoundExpression) -> BoundExpression {
156    case_when(gt(a.clone(), b.clone()), a, b)
157}
158
159/// `min(a, b)`.
160fn minimum(a: BoundExpression, b: BoundExpression) -> BoundExpression {
161    case_when(lt(a.clone(), b.clone()), a, b)
162}