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