use geo::Contains;
use vortex_array::ArrayRef;
use vortex_array::arrays::ScalarFnArray;
use vortex_array::dtype::DType;
use vortex_array::scalar_fn::EmptyOptions;
use vortex_array::scalar_fn::ScalarFnId;
use vortex_array::scalar_fn::TypedScalarFnInstance;
use vortex_array::scalar_fn::unstable::row::RowFn;
use vortex_array::scalar_fn::unstable::row::RowVisitor;
use vortex_error::VortexResult;
use vortex_session::VortexSession;
use vortex_session::registry::CachedId;
use crate::scalar_fn::row::visit_binary_geo_predicate;
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct SpatialContains;
impl SpatialContains {
pub fn try_new(a: ArrayRef, b: ArrayRef) -> VortexResult<ScalarFnArray> {
ScalarFnArray::try_new(
TypedScalarFnInstance::new(SpatialContains, EmptyOptions).erased(),
vec![a, b],
)
}
}
impl RowFn for SpatialContains {
type Options = EmptyOptions;
const ARG_NAMES: &'static [&'static str] = &["a", "b"];
const INFALLIBLE: bool = false;
fn id(&self) -> ScalarFnId {
static ID: CachedId = CachedId::new("vortex.st.contains");
*ID
}
fn serialize(&self, _: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
Ok(Some(vec![]))
}
fn deserialize(&self, _: &[u8], _: &VortexSession) -> VortexResult<Self::Options> {
Ok(EmptyOptions)
}
fn dispatch<V: RowVisitor>(
&self,
_options: &Self::Options,
_args: &[DType],
visitor: V,
) -> VortexResult<V::VisitResult> {
visit_binary_geo_predicate(
visitor,
|a, b| a.contains(b),
|a, b| (!a.contains(b)).then_some(false),
)
}
}
#[cfg(test)]
mod tests {
use std::sync::LazyLock;
use geo_types::Geometry;
use geo_types::LineString;
use geo_types::Point;
use geo_types::Polygon;
use rstest::rstest;
use vortex_array::ArrayRef;
use vortex_array::Canonical;
use vortex_array::ExecutionCtx;
use vortex_array::IntoArray;
use vortex_array::VortexSessionExecute;
use vortex_array::arrays::BoolArray;
use vortex_array::arrays::ConstantArray;
use vortex_array::assert_arrays_eq;
use vortex_array::dtype::DType;
use vortex_array::dtype::Nullability;
use vortex_array::dtype::PType;
use vortex_array::scalar::Scalar;
use vortex_array::scalar_fn::EmptyOptions;
use vortex_array::scalar_fn::ScalarFnVTable;
use vortex_array::validity::Validity;
use vortex_buffer::BitBuffer;
use vortex_error::VortexResult;
use vortex_error::vortex_err;
use vortex_session::VortexSession;
use wkb::writer::WriteOptions;
use super::SpatialContains;
use crate::test_harness::linestring_column;
use crate::test_harness::nullable_point_column;
use crate::test_harness::point_column;
static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
fn rect_polygon(x0: f64, y0: f64, x1: f64, y1: f64) -> Polygon {
Polygon::new(
LineString::from(vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)]),
vec![],
)
}
fn geometry_constant(geometry: &Geometry, len: usize) -> VortexResult<ArrayRef> {
let mut buf = Vec::new();
wkb::writer::write_geometry(&mut buf, geometry, &WriteOptions::default())
.map_err(|e| vortex_err!("writing WKB failed: {e}"))?;
let session = VortexSession::empty();
let scalar = crate::extension::native_geometry_scalar_from_wkb(&buf, &session)?
.ok_or_else(|| vortex_err!("unsupported geometry type"))?;
Ok(ConstantArray::new(scalar, len).into_array())
}
fn materialize(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
Ok(array.execute::<Canonical>(ctx)?.into_array())
}
fn assert_contains(
a: ArrayRef,
b: ArrayRef,
expected: impl IntoIterator<Item = bool>,
) -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let contains = SpatialContains::try_new(a, b)?.into_array();
assert_arrays_eq!(contains, BoolArray::from_iter(expected), &mut ctx);
Ok(())
}
#[rstest]
#[case::nested(rect_polygon(1.0, 1.0, 3.0, 3.0), true)]
#[case::overlapping(rect_polygon(2.0, 2.0, 6.0, 6.0), false)]
#[case::disjoint(rect_polygon(20.0, 20.0, 24.0, 24.0), false)]
fn constant_vs_constant_polygons(
#[case] other: Polygon,
#[case] expected: bool,
) -> VortexResult<()> {
let container = geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 3)?;
let other = geometry_constant(&Geometry::Polygon(other), 3)?;
assert_contains(container, other, [expected; 3])
}
#[test]
fn overlapping_polygons_contain_neither_way() -> VortexResult<()> {
let a = geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 2)?;
let b = geometry_constant(&Geometry::Polygon(rect_polygon(2.0, 2.0, 6.0, 6.0)), 2)?;
assert_contains(a.clone(), b.clone(), [false; 2])?;
assert_contains(b, a, [false; 2])
}
#[test]
fn contains_is_asymmetric() -> VortexResult<()> {
let polygon = geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 2)?;
let point = geometry_constant(&Geometry::Point(Point::new(2.0, 2.0)), 2)?;
assert_contains(polygon.clone(), point.clone(), [true; 2])?;
assert_contains(point, polygon, [false; 2])
}
#[test]
fn constant_polygon_vs_point_column() -> VortexResult<()> {
let container = geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 3)?;
let points = point_column(vec![2.0, 10.0, 0.0], vec![2.0, 10.0, 2.0])?;
assert_contains(container, points, [true, false, false])
}
#[test]
fn polygon_column_vs_constant_point() -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let around = materialize(
geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 2)?,
&mut ctx,
)?;
let away = materialize(
geometry_constant(&Geometry::Polygon(rect_polygon(20.0, 20.0, 24.0, 24.0)), 2)?,
&mut ctx,
)?;
let point = geometry_constant(&Geometry::Point(Point::new(2.0, 2.0)), 2)?;
assert_contains(around, point.clone(), [true; 2])?;
assert_contains(away, point, [false; 2])
}
#[test]
fn constant_container_vs_row_rect_poking_outside() -> VortexResult<()> {
let container = geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 3)?;
let lines = linestring_column(vec![
vec![(1.0, 1.0), (3.0, 3.0)],
vec![(1.0, 1.0), (9.0, 1.0)],
vec![(5.0, 5.0), (9.0, 9.0)],
])?;
assert_contains(container, lines, [true, false, false])
}
#[test]
fn polygon_column_vs_point_column() -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let polygons = materialize(
geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 2)?,
&mut ctx,
)?;
let points = point_column(vec![2.0, 10.0], vec![2.0, 10.0])?;
assert_contains(polygons, points, [true, false])
}
#[test]
fn output_nullability_mirrors_operands() -> VortexResult<()> {
let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
let non_nullable =
SpatialContains.return_dtype(&EmptyOptions, &[dtype.clone(), dtype.clone()])?;
assert_eq!(non_nullable, DType::Bool(Nullability::NonNullable));
let nullable =
SpatialContains.return_dtype(&EmptyOptions, &[dtype.as_nullable(), dtype])?;
assert_eq!(nullable, DType::Bool(Nullability::Nullable));
Ok(())
}
#[test]
fn contains_propagates_null_rows() -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let container = geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 3)?;
let points = nullable_point_column(vec![Some((2.0, 2.0)), None, Some((10.0, 10.0))])?;
let contains = SpatialContains::try_new(container, points)?.into_array();
let expected = BoolArray::new(
BitBuffer::from_iter([true, false, false]),
Validity::from_iter([true, false, true]),
)
.into_array();
assert_arrays_eq!(contains, expected, &mut ctx);
Ok(())
}
#[test]
fn contains_constant_null_is_all_null() -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let point_dtype = point_column(vec![0.0], vec![0.0])?.dtype().as_nullable();
let null_const = ConstantArray::new(Scalar::null(point_dtype), 2).into_array();
let points = point_column(vec![2.0, 10.0], vec![2.0, 10.0])?;
let contains = SpatialContains::try_new(null_const, points)?.into_array();
let expected =
BoolArray::new(BitBuffer::from_iter([false, false]), Validity::AllInvalid).into_array();
assert_arrays_eq!(contains, expected, &mut ctx);
Ok(())
}
#[test]
fn contains_propagates_column_pair_nulls() -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let container = nullable_point_column(vec![
Some((1.0, 1.0)),
None,
Some((2.0, 2.0)),
Some((3.0, 3.0)),
])?;
let contained = nullable_point_column(vec![
Some((1.0, 1.0)),
Some((5.0, 5.0)),
None,
Some((4.0, 4.0)),
])?;
let contains = SpatialContains::try_new(container, contained)?.into_array();
let expected = BoolArray::new(
BitBuffer::from_iter([true, false, false, false]),
Validity::from_iter([true, false, false, true]),
)
.into_array();
assert_arrays_eq!(contains, expected, &mut ctx);
Ok(())
}
#[test]
fn contains_all_null_column_is_all_null() -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let container = geometry_constant(&Geometry::Polygon(rect_polygon(0.0, 0.0, 4.0, 4.0)), 2)?;
let points = nullable_point_column(vec![None, None])?;
let contains = SpatialContains::try_new(container, points)?.into_array();
let expected =
BoolArray::new(BitBuffer::from_iter([false, false]), Validity::AllInvalid).into_array();
assert_arrays_eq!(contains, expected, &mut ctx);
Ok(())
}
#[test]
fn contains_column_pair_all_null() -> VortexResult<()> {
let mut ctx = SESSION.create_execution_ctx();
let container = nullable_point_column(vec![Some((1.0, 1.0)), None])?;
let contained = nullable_point_column(vec![None, Some((2.0, 2.0))])?;
let contains = SpatialContains::try_new(container, contained)?.into_array();
let expected =
BoolArray::new(BitBuffer::from_iter([false, false]), Validity::AllInvalid).into_array();
assert_arrays_eq!(contains, expected, &mut ctx);
Ok(())
}
#[test]
fn non_geometry_operand_is_rejected() -> VortexResult<()> {
let spatial_dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
let numeric = DType::Primitive(PType::I32, Nullability::NonNullable);
let result = SpatialContains.return_dtype(&EmptyOptions, &[spatial_dtype, numeric]);
assert!(result.is_err());
Ok(())
}
}