diff --git a/vortex-geo/Cargo.toml b/vortex-geo/Cargo.toml index 1a1001b688a..7bd80eafb10 100644 --- a/vortex-geo/Cargo.toml +++ b/vortex-geo/Cargo.toml @@ -66,5 +66,9 @@ harness = false name = "length" harness = false +[[bench]] +name = "area" +harness = false + [lints] workspace = true diff --git a/vortex-geo/benches/area.rs b/vortex-geo/benches/area.rs new file mode 100644 index 00000000000..38b1bc138e2 --- /dev/null +++ b/vortex-geo/benches/area.rs @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Microbenchmarks for native `ST_Area` over polygons and multipolygons. +//! +//! The cases separate the costs of vertex traversal, interior rings, nested polygons, and strict +//! null propagation. They execute through the scalar function and materialize the `f64` result. +//! +//! Run with `cargo bench -p vortex-geo --bench area`. + +#![expect(clippy::unwrap_used)] + +use std::sync::LazyLock; + +use divan::Bencher; +use divan::counter::ItemsCount; +use mimalloc::MiMalloc; +use vortex_array::ArrayRef; +use vortex_array::Canonical; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::MaskedArray; +use vortex_array::validity::Validity; +use vortex_geo::scalar_fn::area::GeoArea; +use vortex_geo::test_harness::geo_session; +use vortex_geo::test_harness::multipolygon_column; +use vortex_geo::test_harness::polygon_column; +use vortex_session::VortexSession; + +// Scalar function execution allocates its output inside the timed region, so use the vendored +// allocator instead of measuring glibc differences between CodSpeed runner images. +#[global_allocator] +static GLOBAL: MiMalloc = MiMalloc; + +static SESSION: LazyLock = LazyLock::new(geo_session); + +const ROWS: usize = 512; + +fn main() { + divan::main(); +} + +/// A closed square ring centered at `(cx, cy)`. +fn square(cx: f64, cy: f64, radius: f64) -> Vec<(f64, f64)> { + vec![ + (cx - radius, cy - radius), + (cx + radius, cy - radius), + (cx + radius, cy + radius), + (cx - radius, cy + radius), + (cx - radius, cy - radius), + ] +} + +fn simple_polygons() -> ArrayRef { + polygon_column( + (0..ROWS) + .map(|row| vec![square(row as f64, row as f64, 10.0)]) + .collect(), + ) + .unwrap() +} + +fn polygons_with_holes() -> ArrayRef { + polygon_column( + (0..ROWS) + .map(|row| { + let center = row as f64; + vec![ + square(center, center, 10.0), + square(center - 4.0, center, 1.0), + square(center + 4.0, center, 1.0), + ] + }) + .collect(), + ) + .unwrap() +} + +fn multipolygons() -> ArrayRef { + multipolygon_column( + (0..ROWS) + .map(|row| { + let center = row as f64; + vec![ + vec![square(center - 12.0, center, 5.0)], + vec![square(center, center, 5.0)], + vec![square(center + 12.0, center, 5.0)], + ] + }) + .collect(), + ) + .unwrap() +} + +fn areas(geometry: &ArrayRef, ctx: &mut ExecutionCtx) -> ArrayRef { + GeoArea::try_new_array(geometry.clone()) + .unwrap() + .into_array() + .execute::(ctx) + .unwrap() + .into_array() +} + +fn bench_area(bencher: Bencher, geometry: ArrayRef) { + let mut ctx = SESSION.create_execution_ctx(); + bencher + .counter(ItemsCount::new(ROWS)) + .bench_local(|| areas(&geometry, &mut ctx)); +} + +#[divan::bench] +fn simple_polygon(bencher: Bencher) { + bench_area(bencher, simple_polygons()); +} + +#[divan::bench] +fn polygon_with_holes(bencher: Bencher) { + bench_area(bencher, polygons_with_holes()); +} + +#[divan::bench] +fn multipolygon(bencher: Bencher) { + bench_area(bencher, multipolygons()); +} + +#[divan::bench] +fn nullable_polygon(bencher: Bencher) { + let geometry = MaskedArray::try_new( + simple_polygons(), + Validity::from_iter((0..ROWS).map(|row| !row.is_multiple_of(8))), + ) + .unwrap() + .into_array(); + bench_area(bencher, geometry); +} diff --git a/vortex-geo/src/lib.rs b/vortex-geo/src/lib.rs index 88c54d3da1a..71d09c54c2b 100644 --- a/vortex-geo/src/lib.rs +++ b/vortex-geo/src/lib.rs @@ -21,6 +21,7 @@ use crate::extension::Rect; use crate::extension::WellKnownBinary; use crate::prune::GeoDistancePrune; use crate::prune::GeoIntersectsPrune; +use crate::scalar_fn::area::GeoArea; use crate::scalar_fn::contains::GeoContains; use crate::scalar_fn::distance::GeoDistance; use crate::scalar_fn::envelope::GeoEnvelope; @@ -66,6 +67,7 @@ pub fn initialize(session: &VortexSession) { session.arrow().register_importer(Arc::new(Rect)); // Register the geometry scalar functions. + session.scalar_fns().register(GeoArea); session.scalar_fns().register(GeoEnvelope); session.scalar_fns().register(GeoContains); session.scalar_fns().register(GeoDistance); diff --git a/vortex-geo/src/scalar_fn/area.rs b/vortex-geo/src/scalar_fn/area.rs new file mode 100644 index 00000000000..ba2cff58b2a --- /dev/null +++ b/vortex-geo/src/scalar_fn/area.rs @@ -0,0 +1,246 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! `ST_Area`: unsigned planar area of native geometries. + +use geo::Area; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::arrays::ScalarFnArray; +use vortex_array::dtype::DType; +use vortex_array::dtype::PType; +use vortex_array::expr::Expression; +use vortex_array::expr::union_child_validities; +use vortex_array::scalar_fn::Arity; +use vortex_array::scalar_fn::ChildName; +use vortex_array::scalar_fn::EmptyOptions; +use vortex_array::scalar_fn::ExecutionArgs; +use vortex_array::scalar_fn::ScalarFnId; +use vortex_array::scalar_fn::ScalarFnVTable; +use vortex_array::scalar_fn::TypedScalarFnInstance; +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; + +use crate::extension::is_native_geometry; +use crate::scalar_fn::execute::execute_unary_geo_types; + +/// Validate the native geometry operand accepted by `ST_Area`. +fn validate_area_operand(dtypes: &[DType]) -> VortexResult<()> { + vortex_ensure!( + dtypes.len() == 1, + "geo: area requires exactly one geometry operand, got {}", + dtypes.len() + ); + vortex_ensure!( + is_native_geometry(&dtypes[0]), + "geo: area operand {} is not a native geometry", + dtypes[0] + ); + Ok(()) +} + +/// Unsigned planar `ST_Area` of native geometries. +/// +/// Points and line strings have zero area, polygons and multipolygons use their two-dimensional +/// coordinates, and rectangles use width times height. Higher coordinate dimensions are ignored. +#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)] +pub struct GeoArea; + +impl GeoArea { + /// A lazy `ScalarFnArray` computing the per-row area of a native geometry operand. + pub fn try_new_array(array: ArrayRef) -> VortexResult { + ScalarFnArray::try_new( + TypedScalarFnInstance::new(GeoArea, EmptyOptions).erased(), + vec![array], + ) + } +} + +impl ScalarFnVTable for GeoArea { + type Options = EmptyOptions; + + fn id(&self) -> ScalarFnId { + static ID: CachedId = CachedId::new("vortex.geo.area"); + *ID + } + + fn serialize(&self, _: &Self::Options) -> VortexResult>> { + Ok(Some(vec![])) + } + + fn deserialize(&self, _: &[u8], _: &VortexSession) -> VortexResult { + Ok(EmptyOptions) + } + + fn arity(&self, _: &Self::Options) -> Arity { + Arity::Exact(1) + } + + fn child_name(&self, _: &Self::Options, child_idx: usize) -> ChildName { + match child_idx { + 0 => ChildName::from("geometry"), + _ => unreachable!("area has exactly one child"), + } + } + + fn return_dtype(&self, _: &Self::Options, dtypes: &[DType]) -> VortexResult { + validate_area_operand(dtypes)?; + Ok(DType::Primitive(PType::F64, dtypes[0].nullability())) + } + + fn execute( + &self, + _: &Self::Options, + args: &dyn ExecutionArgs, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + let array = args.get(0)?; + execute_unary_geo_types(&array, Area::unsigned_area, ctx) + } + + fn validity( + &self, + _: &Self::Options, + expression: &Expression, + ) -> VortexResult> { + union_child_validities(expression) + } + + fn is_strict(&self, _: &Self::Options) -> bool { + true + } + + fn is_fallible(&self, _: &Self::Options) -> bool { + false + } +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + use vortex_array::ArrayRef; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::arrays::PrimitiveArray; + 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_fn::EmptyOptions; + use vortex_array::scalar_fn::ScalarFnVTable; + use vortex_array::validity::Validity; + use vortex_error::VortexResult; + + use super::GeoArea; + use crate::test_harness::linestring_column; + use crate::test_harness::multilinestring_column; + use crate::test_harness::multipoint_column; + use crate::test_harness::multipolygon_column; + use crate::test_harness::nullable_multipolygon_column; + use crate::test_harness::point_column; + use crate::test_harness::polygon_column; + use crate::test_harness::rect_column; + + #[rstest] + #[case::point(point_column(vec![1.0], vec![2.0]), &[0.0])] + #[case::line_string( + linestring_column(vec![vec![(0.0, 0.0), (3.0, 4.0)]]), + &[0.0] + )] + #[case::multi_point( + multipoint_column(vec![vec![(0.0, 0.0), (1.0, 1.0)]]), + &[0.0] + )] + #[case::multi_line_string( + multilinestring_column(vec![vec![ + vec![(0.0, 0.0), (1.0, 1.0)], + vec![(2.0, 2.0), (3.0, 3.0)], + ]]), + &[0.0] + )] + #[case::polygon( + polygon_column(vec![ + vec![ + vec![(0.0, 0.0), (4.0, 0.0), (4.0, 3.0), (0.0, 3.0), (0.0, 0.0)], + vec![(1.0, 1.0), (2.0, 1.0), (2.0, 2.0), (1.0, 2.0), (1.0, 1.0)], + ], + vec![], + ]), + &[11.0, 0.0] + )] + #[case::multi_polygon( + multipolygon_column(vec![vec![ + vec![vec![ + (0.0, 0.0), + (2.0, 0.0), + (2.0, 2.0), + (0.0, 2.0), + (0.0, 0.0), + ]], + vec![vec![ + (3.0, 0.0), + (6.0, 0.0), + (6.0, 3.0), + (3.0, 3.0), + (3.0, 0.0), + ]], + ]]), + &[13.0] + )] + #[case::rect(rect_column(vec![(0.0, 0.0, 5.0, 3.0)]), &[15.0])] + fn measures_native_geometries( + #[case] geometry: VortexResult, + #[case] expected: &[f64], + ) -> VortexResult<()> { + let session = vortex_array::array_session(); + let mut ctx = session.create_execution_ctx(); + let areas = GeoArea::try_new_array(geometry?)?.into_array(); + let expected = PrimitiveArray::from_iter(expected.iter().copied()).into_array(); + assert_arrays_eq!(areas, expected, &mut ctx); + Ok(()) + } + + #[test] + fn propagates_nulls() -> VortexResult<()> { + let session = vortex_array::array_session(); + let mut ctx = session.create_execution_ctx(); + let multipolygons = nullable_multipolygon_column(vec![ + Some(vec![vec![vec![ + (0.0, 0.0), + (2.0, 0.0), + (2.0, 2.0), + (0.0, 2.0), + (0.0, 0.0), + ]]]), + None, + ])?; + let areas = GeoArea::try_new_array(multipolygons)?.into_array(); + let expected = + PrimitiveArray::new(vec![4.0f64, 0.0], Validity::from_iter([true, false])).into_array(); + + assert_arrays_eq!(areas, expected, &mut ctx); + Ok(()) + } + + #[rstest] + #[case::none(0)] + #[case::two(2)] + fn rejects_wrong_arity(#[case] arity: usize) -> VortexResult<()> { + let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone(); + assert!( + GeoArea + .return_dtype(&EmptyOptions, &vec![dtype; arity]) + .is_err() + ); + Ok(()) + } + + #[test] + fn rejects_non_geometry_dtype() -> VortexResult<()> { + let primitive = DType::Primitive(PType::F64, Nullability::NonNullable); + assert!(GeoArea.return_dtype(&EmptyOptions, &[primitive]).is_err()); + Ok(()) + } +} diff --git a/vortex-geo/src/scalar_fn/mod.rs b/vortex-geo/src/scalar_fn/mod.rs index 5e25f0e3774..4e318bc77e7 100644 --- a/vortex-geo/src/scalar_fn/mod.rs +++ b/vortex-geo/src/scalar_fn/mod.rs @@ -3,6 +3,7 @@ //! Geometry scalar functions over the native geometry extension types. +pub mod area; pub mod contains; pub mod distance; pub mod envelope;