Skip to main content

vortex_spatial/scalar_fn/
area.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! `ST_Area`: unsigned planar area of native geometries.
5
6use geo::Area;
7use vortex_array::ArrayRef;
8use vortex_array::arrays::ScalarFnArray;
9use vortex_array::dtype::DType;
10use vortex_array::scalar_fn::EmptyOptions;
11use vortex_array::scalar_fn::ScalarFnId;
12use vortex_array::scalar_fn::TypedScalarFnInstance;
13use vortex_array::scalar_fn::unstable::row::RowFn;
14use vortex_array::scalar_fn::unstable::row::RowVisitor;
15use vortex_error::VortexResult;
16use vortex_session::VortexSession;
17use vortex_session::registry::CachedId;
18
19use crate::scalar_fn::row::GeometryRow;
20
21/// Unsigned planar `ST_Area` of native geometries.
22///
23/// Points and line strings have zero area, polygons and multipolygons use their two-dimensional
24/// coordinates, and rectangles use width times height. Higher coordinate dimensions are ignored.
25#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
26pub struct SpatialArea;
27
28impl SpatialArea {
29    /// A lazy `ScalarFnArray` computing the per-row area of a native geometry operand.
30    pub fn try_new(array: ArrayRef) -> VortexResult<ScalarFnArray> {
31        ScalarFnArray::try_new(
32            TypedScalarFnInstance::new(SpatialArea, EmptyOptions).erased(),
33            vec![array],
34        )
35    }
36}
37
38impl RowFn for SpatialArea {
39    type Options = EmptyOptions;
40
41    const ARG_NAMES: &'static [&'static str] = &["geometry"];
42    const INFALLIBLE: bool = false;
43
44    fn id(&self) -> ScalarFnId {
45        static ID: CachedId = CachedId::new("vortex.st.area");
46        *ID
47    }
48
49    fn serialize(&self, _: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
50        Ok(Some(vec![]))
51    }
52
53    fn deserialize(&self, _: &[u8], _: &VortexSession) -> VortexResult<Self::Options> {
54        Ok(EmptyOptions)
55    }
56
57    fn dispatch<V: RowVisitor>(
58        &self,
59        _options: &Self::Options,
60        _args: &[DType],
61        visitor: V,
62    ) -> VortexResult<V::VisitResult> {
63        visitor.visit::<(GeometryRow,), f64>(|(geometry,)| geometry.unsigned_area())
64    }
65}
66
67#[cfg(test)]
68mod tests {
69    use std::sync::LazyLock;
70
71    use rstest::rstest;
72    use vortex_array::ArrayRef;
73    use vortex_array::IntoArray;
74    use vortex_array::VortexSessionExecute;
75    use vortex_array::arrays::PrimitiveArray;
76    use vortex_array::assert_arrays_eq;
77    use vortex_array::dtype::DType;
78    use vortex_array::dtype::Nullability;
79    use vortex_array::dtype::PType;
80    use vortex_array::scalar_fn::EmptyOptions;
81    use vortex_array::scalar_fn::ScalarFnVTable;
82    use vortex_array::validity::Validity;
83    use vortex_error::VortexResult;
84    use vortex_session::VortexSession;
85
86    use super::SpatialArea;
87    use crate::test_harness::linestring_column;
88    use crate::test_harness::multilinestring_column;
89    use crate::test_harness::multipoint_column;
90    use crate::test_harness::multipolygon_column;
91    use crate::test_harness::nullable_multipolygon_column;
92    use crate::test_harness::point_column;
93    use crate::test_harness::polygon_column;
94    use crate::test_harness::rect_column;
95
96    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
97
98    #[rstest]
99    #[case::point(point_column(vec![1.0], vec![2.0]), &[0.0])]
100    #[case::line_string(
101        linestring_column(vec![vec![(0.0, 0.0), (3.0, 4.0)]]),
102        &[0.0]
103    )]
104    #[case::multi_point(
105        multipoint_column(vec![vec![(0.0, 0.0), (1.0, 1.0)]]),
106        &[0.0]
107    )]
108    #[case::multi_line_string(
109        multilinestring_column(vec![vec![
110            vec![(0.0, 0.0), (1.0, 1.0)],
111            vec![(2.0, 2.0), (3.0, 3.0)],
112        ]]),
113        &[0.0]
114    )]
115    #[case::polygon(
116        polygon_column(vec![
117            vec![
118                vec![(0.0, 0.0), (4.0, 0.0), (4.0, 3.0), (0.0, 3.0), (0.0, 0.0)],
119                vec![(1.0, 1.0), (2.0, 1.0), (2.0, 2.0), (1.0, 2.0), (1.0, 1.0)],
120            ],
121            vec![],
122        ]),
123        &[11.0, 0.0]
124    )]
125    #[case::multi_polygon(
126        multipolygon_column(vec![vec![
127            vec![vec![
128                (0.0, 0.0),
129                (2.0, 0.0),
130                (2.0, 2.0),
131                (0.0, 2.0),
132                (0.0, 0.0),
133            ]],
134            vec![vec![
135                (3.0, 0.0),
136                (6.0, 0.0),
137                (6.0, 3.0),
138                (3.0, 3.0),
139                (3.0, 0.0),
140            ]],
141        ]]),
142        &[13.0]
143    )]
144    #[case::rect(rect_column(vec![(0.0, 0.0, 5.0, 3.0)]), &[15.0])]
145    fn measures_native_geometries(
146        #[case] geometry: VortexResult<ArrayRef>,
147        #[case] expected: &[f64],
148    ) -> VortexResult<()> {
149        let mut ctx = SESSION.create_execution_ctx();
150        let areas = SpatialArea::try_new(geometry?)?.into_array();
151        let expected = PrimitiveArray::from_iter(expected.iter().copied()).into_array();
152        assert_arrays_eq!(areas, expected, &mut ctx);
153        Ok(())
154    }
155
156    #[test]
157    fn propagates_nulls() -> VortexResult<()> {
158        let mut ctx = SESSION.create_execution_ctx();
159        let multipolygons = nullable_multipolygon_column(vec![
160            Some(vec![vec![vec![
161                (0.0, 0.0),
162                (2.0, 0.0),
163                (2.0, 2.0),
164                (0.0, 2.0),
165                (0.0, 0.0),
166            ]]]),
167            None,
168        ])?;
169        let areas = SpatialArea::try_new(multipolygons)?.into_array();
170        let expected =
171            PrimitiveArray::new(vec![4.0f64, 0.0], Validity::from_iter([true, false])).into_array();
172
173        assert_arrays_eq!(areas, expected, &mut ctx);
174        Ok(())
175    }
176
177    #[rstest]
178    #[case::none(0)]
179    #[case::two(2)]
180    fn rejects_wrong_arity(#[case] arity: usize) -> VortexResult<()> {
181        let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
182        assert!(
183            SpatialArea
184                .return_dtype(&EmptyOptions, &vec![dtype; arity])
185                .is_err()
186        );
187        Ok(())
188    }
189
190    #[test]
191    fn rejects_non_geometry_dtype() -> VortexResult<()> {
192        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
193        assert!(
194            SpatialArea
195                .return_dtype(&EmptyOptions, &[primitive])
196                .is_err()
197        );
198        Ok(())
199    }
200}