-
Notifications
You must be signed in to change notification settings - Fork 29
perf: ST_Buffer implementation using geo
#233
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
petern48
wants to merge
8
commits into
apache:main
Choose a base branch
from
petern48:st_buffer_geo
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
09bff9e
Fix builder capacity of st_centroid geo
petern48 91a0b7e
Implement st_buffer geo
petern48 aa4d704
Copy empty tests to old st_buffer geos
petern48 faff21d
Add test_st_buffer_empty to python tests
petern48 b841b0e
Add benches for geo
petern48 0046d5c
clippy: remove unwrap call
petern48 eace153
clean up
petern48 7e600eb
Move import
petern48 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,224 @@ | ||
| // Licensed to the Apache Software Foundation (ASF) under one | ||
| // or more contributor license agreements. See the NOTICE file | ||
| // distributed with this work for additional information | ||
| // regarding copyright ownership. The ASF licenses this file | ||
| // to you under the Apache License, Version 2.0 (the | ||
| // "License"); you may not use this file except in compliance | ||
| // with the License. You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, | ||
| // software distributed under the License is distributed on an | ||
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| // KIND, either express or implied. See the License for the | ||
| // specific language governing permissions and limitations | ||
| // under the License. | ||
|
|
||
| use std::sync::Arc; | ||
|
|
||
| use arrow_array::builder::BinaryBuilder; | ||
| use arrow_schema::DataType; | ||
| use datafusion_common::{error::Result, exec_err, DataFusionError}; | ||
| use datafusion_expr::ColumnarValue; | ||
| use geo::algorithm::buffer::{Buffer, BufferStyle}; | ||
| use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel}; | ||
| use sedona_functions::executor::WkbExecutor; | ||
| use sedona_geometry::wkb_factory::WKB_MIN_PROBABLE_BYTES; | ||
| use sedona_schema::{ | ||
| datatypes::{SedonaType, WKB_GEOMETRY}, | ||
| matchers::ArgMatcher, | ||
| }; | ||
| use wkb::{ | ||
| writer::{write_geometry, WriteOptions}, | ||
| Endianness, | ||
| }; | ||
|
|
||
| /// ST_Centroid() implementation using centroid extraction | ||
| pub fn st_buffer_impl() -> ScalarKernelRef { | ||
| Arc::new(STBuffer {}) | ||
| } | ||
|
|
||
| #[derive(Debug)] | ||
| struct STBuffer {} | ||
|
|
||
| impl SedonaScalarKernel for STBuffer { | ||
| fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> { | ||
| let matcher = ArgMatcher::new( | ||
| vec![ArgMatcher::is_geometry(), ArgMatcher::is_numeric()], | ||
| WKB_GEOMETRY, | ||
| ); | ||
|
|
||
| matcher.match_args(args) | ||
| } | ||
|
|
||
| fn invoke_batch( | ||
| &self, | ||
| arg_types: &[SedonaType], | ||
| args: &[ColumnarValue], | ||
| ) -> Result<ColumnarValue> { | ||
| // Extract the constant scalar value before looping over the input geometries | ||
| let params: Option<BufferStyle<f64>>; | ||
| let arg1 = args[1].cast_to(&DataType::Float64, None)?; | ||
| if let ColumnarValue::Scalar(scalar_arg) = &arg1 { | ||
| if scalar_arg.is_null() { | ||
| params = None; | ||
| } else { | ||
| let distance = f64::try_from(scalar_arg.clone())?; | ||
| params = Some(BufferStyle::new(distance)); | ||
| } | ||
| } else { | ||
| return exec_err!("Invalid distance: {:?}", args[1]); | ||
| } | ||
|
|
||
| // let executor = GeoTypesExecutor::new(arg_types, args); | ||
| let executor = WkbExecutor::new(arg_types, args); | ||
| let mut builder = BinaryBuilder::with_capacity( | ||
| executor.num_iterations(), | ||
| WKB_MIN_PROBABLE_BYTES * executor.num_iterations(), | ||
| ); | ||
| executor.execute_wkb_void(|maybe_wkb| { | ||
| match (maybe_wkb, params.clone()) { | ||
| (Some(wkb), Some(params)) => { | ||
| invoke_scalar(&wkb, params, &mut builder)?; | ||
| builder.append_value([]); | ||
| } | ||
| _ => builder.append_null(), | ||
| } | ||
|
|
||
| Ok(()) | ||
| })?; | ||
|
|
||
| executor.finish(Arc::new(builder.finish())) | ||
| } | ||
| } | ||
|
|
||
| use wkb::reader::Wkb; | ||
| fn invoke_scalar( | ||
| wkb: &Wkb, | ||
| params: BufferStyle<f64>, | ||
| writer: &mut impl std::io::Write, | ||
| ) -> Result<()> { | ||
| use crate::to_geo::item_to_geometry; | ||
| use geo_types::Polygon; | ||
| use sedona_geometry::is_empty::is_geometry_empty; | ||
|
|
||
| // PostGIS returns POLYGON EMPTY for all empty geometries | ||
| let is_empty = is_geometry_empty(wkb).map_err(|e| DataFusionError::External(Box::new(e)))?; | ||
| if is_empty { | ||
| let empty_polygon = Polygon::<f64>::empty(); | ||
| write_geometry( | ||
| writer, | ||
| &empty_polygon, | ||
| &WriteOptions { | ||
| endianness: Endianness::LittleEndian, | ||
| }, | ||
| ) | ||
| .map_err(|e| DataFusionError::External(Box::new(e)))?; | ||
| return Ok(()); | ||
| } | ||
|
|
||
| let geom = item_to_geometry(wkb)?; | ||
|
|
||
| let buffer = geom.buffer_with_style(params); | ||
|
|
||
| // Convert type to geo::Geometry | ||
| let geometry = geo::Geometry::MultiPolygon(buffer); | ||
|
|
||
| write_geometry( | ||
| writer, | ||
| &geometry, | ||
| &WriteOptions { | ||
| endianness: Endianness::LittleEndian, | ||
| }, | ||
| ) | ||
| .map_err(|e| DataFusionError::External(Box::new(e)))?; | ||
| Ok(()) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use arrow_array::ArrayRef; | ||
| use datafusion_common::ScalarValue; | ||
| use rstest::rstest; | ||
| use sedona_expr::scalar_udf::SedonaScalarUDF; | ||
| use sedona_schema::datatypes::{WKB_GEOMETRY, WKB_VIEW_GEOMETRY}; | ||
| use sedona_testing::compare::assert_array_equal; | ||
| use sedona_testing::create::create_array; | ||
| use sedona_testing::testers::ScalarUdfTester; | ||
|
|
||
| use super::*; | ||
|
|
||
| #[rstest] | ||
| fn udf(#[values(WKB_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) { | ||
| let udf = SedonaScalarUDF::from_kernel("st_buffer", st_buffer_impl()); | ||
| let tester = ScalarUdfTester::new( | ||
| udf.into(), | ||
| vec![sedona_type.clone(), SedonaType::Arrow(DataType::Float64)], | ||
| ); | ||
| tester.assert_return_type(WKB_GEOMETRY); | ||
|
|
||
| // Check the envelope of the buffers | ||
| let envelope_udf = sedona_functions::st_envelope::st_envelope_udf(); | ||
| let envelope_tester = ScalarUdfTester::new(envelope_udf.into(), vec![WKB_GEOMETRY]); | ||
|
|
||
| let buffer_result = tester.invoke_scalar_scalar("POINT (1 2)", 2.0).unwrap(); | ||
| let envelope_result = envelope_tester.invoke_scalar(buffer_result).unwrap(); | ||
| let expected_envelope = "POLYGON((-1 0, -1 4, 3 4, 3 0, -1 0))"; | ||
| tester.assert_scalar_result_equals(envelope_result, expected_envelope); | ||
|
|
||
| let result = tester | ||
| .invoke_scalar_scalar(ScalarValue::Null, ScalarValue::Null) | ||
| .unwrap(); | ||
| assert!(result.is_null()); | ||
|
|
||
| let input_wkt = vec![None, Some("POINT (0 0)")]; | ||
| let input_dist = 1; | ||
| let expected_envelope: ArrayRef = create_array( | ||
| &[None, Some("POLYGON((-1 -1, -1 1, 1 1, 1 -1, -1 -1))")], | ||
| &WKB_GEOMETRY, | ||
| ); | ||
| let buffer_result = tester | ||
| .invoke_wkb_array_scalar(input_wkt, input_dist) | ||
| .unwrap(); | ||
| let envelope_result = envelope_tester.invoke_array(buffer_result).unwrap(); | ||
| assert_array_equal(&envelope_result, &expected_envelope); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_empty_geometry() { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The test suite here is the same as the |
||
| let udf = SedonaScalarUDF::from_kernel("st_buffer", st_buffer_impl()); | ||
| let tester = ScalarUdfTester::new( | ||
| udf.into(), | ||
| vec![WKB_GEOMETRY, SedonaType::Arrow(DataType::Float64)], | ||
| ); | ||
|
|
||
| let input_wkt = vec![ | ||
| Some("POINT EMPTY"), | ||
| Some("LINESTRING EMPTY"), | ||
| Some("POLYGON EMPTY"), | ||
| Some("MULTIPOINT EMPTY"), | ||
| Some("MULTILINESTRING EMPTY"), | ||
| Some("MULTIPOLYGON EMPTY"), | ||
| Some("GEOMETRYCOLLECTION EMPTY"), | ||
| ]; | ||
| let input_dist = 2; | ||
|
|
||
| let buffer_result = tester | ||
| .invoke_wkb_array_scalar(input_wkt, input_dist) | ||
| .unwrap(); | ||
| let expected: ArrayRef = create_array( | ||
| &[ | ||
| Some("POLYGON EMPTY"), | ||
| Some("POLYGON EMPTY"), | ||
| Some("POLYGON EMPTY"), | ||
| Some("POLYGON EMPTY"), | ||
| Some("POLYGON EMPTY"), | ||
| Some("POLYGON EMPTY"), | ||
| Some("POLYGON EMPTY"), | ||
| ], | ||
| &WKB_GEOMETRY, | ||
| ); | ||
| assert_array_equal(&buffer_result, &expected); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I was running into an error here with
POINT EMPTYsincegeoapparently doesn't support it.sedona-db/rust/sedona-geo/src/to_geo.rs
Lines 62 to 66 in 3d75664
My current workaround is to use
WKBExecutorhere instead ofGeoTypesExecutorand use our nativeis_geometry_emptycheck.Wondering if there's a better way we can handle empty points in our item_to_geometry() method. The docstring for
geo's try_to_point() function we are in there says returningNonerepresents an empty point. Though returningNoneis not a safe option, so I can't think of anything better than this workaround atm.