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::ExecutionCtx;
9use vortex_array::arrays::ScalarFnArray;
10use vortex_array::dtype::DType;
11use vortex_array::dtype::PType;
12use vortex_array::expr::Expression;
13use vortex_array::expr::union_child_validities;
14use vortex_array::scalar_fn::Arity;
15use vortex_array::scalar_fn::ChildName;
16use vortex_array::scalar_fn::EmptyOptions;
17use vortex_array::scalar_fn::ExecutionArgs;
18use vortex_array::scalar_fn::ScalarFnId;
19use vortex_array::scalar_fn::ScalarFnVTable;
20use vortex_array::scalar_fn::TypedScalarFnInstance;
21use vortex_error::VortexResult;
22use vortex_error::vortex_ensure;
23use vortex_session::VortexSession;
24use vortex_session::registry::CachedId;
25
26use crate::extension::is_native_geometry;
27use crate::scalar_fn::execute::execute_unary_geo_types;
28
29/// Validate the native geometry operand accepted by `ST_Area`.
30fn validate_area_operand(dtypes: &[DType]) -> VortexResult<()> {
31    vortex_ensure!(
32        dtypes.len() == 1,
33        "spatial: area requires exactly one geometry operand, got {}",
34        dtypes.len()
35    );
36    vortex_ensure!(
37        is_native_geometry(&dtypes[0]),
38        "spatial: area operand {} is not a native geometry",
39        dtypes[0]
40    );
41    Ok(())
42}
43
44/// Unsigned planar `ST_Area` of native geometries.
45///
46/// Points and line strings have zero area, polygons and multipolygons use their two-dimensional
47/// coordinates, and rectangles use width times height. Higher coordinate dimensions are ignored.
48#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
49pub struct SpatialArea;
50
51impl SpatialArea {
52    /// A lazy `ScalarFnArray` computing the per-row area of a native geometry operand.
53    pub fn try_new(array: ArrayRef) -> VortexResult<ScalarFnArray> {
54        ScalarFnArray::try_new(
55            TypedScalarFnInstance::new(SpatialArea, EmptyOptions).erased(),
56            vec![array],
57        )
58    }
59}
60
61impl ScalarFnVTable for SpatialArea {
62    type Options = EmptyOptions;
63
64    fn id(&self) -> ScalarFnId {
65        static ID: CachedId = CachedId::new("vortex.st.area");
66        *ID
67    }
68
69    fn serialize(&self, _: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
70        Ok(Some(vec![]))
71    }
72
73    fn deserialize(&self, _: &[u8], _: &VortexSession) -> VortexResult<Self::Options> {
74        Ok(EmptyOptions)
75    }
76
77    fn arity(&self, _: &Self::Options) -> Arity {
78        Arity::Exact(1)
79    }
80
81    fn child_name(&self, _: &Self::Options, child_idx: usize) -> ChildName {
82        match child_idx {
83            0 => ChildName::from("geometry"),
84            _ => unreachable!("area has exactly one child"),
85        }
86    }
87
88    fn return_dtype(&self, _: &Self::Options, dtypes: &[DType]) -> VortexResult<DType> {
89        validate_area_operand(dtypes)?;
90        Ok(DType::Primitive(PType::F64, dtypes[0].nullability()))
91    }
92
93    fn execute(
94        &self,
95        _: &Self::Options,
96        args: &dyn ExecutionArgs,
97        ctx: &mut ExecutionCtx,
98    ) -> VortexResult<ArrayRef> {
99        let array = args.get(0)?;
100        execute_unary_geo_types(&array, Area::unsigned_area, ctx)
101    }
102
103    fn validity(
104        &self,
105        _: &Self::Options,
106        expression: &Expression,
107    ) -> VortexResult<Option<Expression>> {
108        union_child_validities(expression)
109    }
110
111    fn is_strict(&self, _: &Self::Options) -> bool {
112        true
113    }
114
115    fn is_infallible(&self, _: &Self::Options) -> bool {
116        true
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use rstest::rstest;
123    use vortex_array::ArrayRef;
124    use vortex_array::IntoArray;
125    use vortex_array::VortexSessionExecute;
126    use vortex_array::arrays::PrimitiveArray;
127    use vortex_array::assert_arrays_eq;
128    use vortex_array::dtype::DType;
129    use vortex_array::dtype::Nullability;
130    use vortex_array::dtype::PType;
131    use vortex_array::scalar_fn::EmptyOptions;
132    use vortex_array::scalar_fn::ScalarFnVTable;
133    use vortex_array::validity::Validity;
134    use vortex_error::VortexResult;
135
136    use super::SpatialArea;
137    use crate::test_harness::linestring_column;
138    use crate::test_harness::multilinestring_column;
139    use crate::test_harness::multipoint_column;
140    use crate::test_harness::multipolygon_column;
141    use crate::test_harness::nullable_multipolygon_column;
142    use crate::test_harness::point_column;
143    use crate::test_harness::polygon_column;
144    use crate::test_harness::rect_column;
145
146    #[rstest]
147    #[case::point(point_column(vec![1.0], vec![2.0]), &[0.0])]
148    #[case::line_string(
149        linestring_column(vec![vec![(0.0, 0.0), (3.0, 4.0)]]),
150        &[0.0]
151    )]
152    #[case::multi_point(
153        multipoint_column(vec![vec![(0.0, 0.0), (1.0, 1.0)]]),
154        &[0.0]
155    )]
156    #[case::multi_line_string(
157        multilinestring_column(vec![vec![
158            vec![(0.0, 0.0), (1.0, 1.0)],
159            vec![(2.0, 2.0), (3.0, 3.0)],
160        ]]),
161        &[0.0]
162    )]
163    #[case::polygon(
164        polygon_column(vec![
165            vec![
166                vec![(0.0, 0.0), (4.0, 0.0), (4.0, 3.0), (0.0, 3.0), (0.0, 0.0)],
167                vec![(1.0, 1.0), (2.0, 1.0), (2.0, 2.0), (1.0, 2.0), (1.0, 1.0)],
168            ],
169            vec![],
170        ]),
171        &[11.0, 0.0]
172    )]
173    #[case::multi_polygon(
174        multipolygon_column(vec![vec![
175            vec![vec![
176                (0.0, 0.0),
177                (2.0, 0.0),
178                (2.0, 2.0),
179                (0.0, 2.0),
180                (0.0, 0.0),
181            ]],
182            vec![vec![
183                (3.0, 0.0),
184                (6.0, 0.0),
185                (6.0, 3.0),
186                (3.0, 3.0),
187                (3.0, 0.0),
188            ]],
189        ]]),
190        &[13.0]
191    )]
192    #[case::rect(rect_column(vec![(0.0, 0.0, 5.0, 3.0)]), &[15.0])]
193    fn measures_native_geometries(
194        #[case] geometry: VortexResult<ArrayRef>,
195        #[case] expected: &[f64],
196    ) -> VortexResult<()> {
197        let session = vortex_array::array_session();
198        let mut ctx = session.create_execution_ctx();
199        let areas = SpatialArea::try_new(geometry?)?.into_array();
200        let expected = PrimitiveArray::from_iter(expected.iter().copied()).into_array();
201        assert_arrays_eq!(areas, expected, &mut ctx);
202        Ok(())
203    }
204
205    #[test]
206    fn propagates_nulls() -> VortexResult<()> {
207        let session = vortex_array::array_session();
208        let mut ctx = session.create_execution_ctx();
209        let multipolygons = nullable_multipolygon_column(vec![
210            Some(vec![vec![vec![
211                (0.0, 0.0),
212                (2.0, 0.0),
213                (2.0, 2.0),
214                (0.0, 2.0),
215                (0.0, 0.0),
216            ]]]),
217            None,
218        ])?;
219        let areas = SpatialArea::try_new(multipolygons)?.into_array();
220        let expected =
221            PrimitiveArray::new(vec![4.0f64, 0.0], Validity::from_iter([true, false])).into_array();
222
223        assert_arrays_eq!(areas, expected, &mut ctx);
224        Ok(())
225    }
226
227    #[rstest]
228    #[case::none(0)]
229    #[case::two(2)]
230    fn rejects_wrong_arity(#[case] arity: usize) -> VortexResult<()> {
231        let dtype = point_column(vec![0.0], vec![0.0])?.dtype().clone();
232        assert!(
233            SpatialArea
234                .return_dtype(&EmptyOptions, &vec![dtype; arity])
235                .is_err()
236        );
237        Ok(())
238    }
239
240    #[test]
241    fn rejects_non_geometry_dtype() -> VortexResult<()> {
242        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
243        assert!(
244            SpatialArea
245                .return_dtype(&EmptyOptions, &[primitive])
246                .is_err()
247        );
248        Ok(())
249    }
250}