You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@sedona.apache.org by "Abeeujah (via GitHub)" <gi...@apache.org> on 2025/12/09 11:55:22 UTC

[PR] ST_ConcaveHull Implementation [sedona-db]

Abeeujah opened a new pull request, #431:
URL: https://github.com/apache/sedona-db/pull/431

   This has been deeper than I expected, particularly the WKB generated after the `Concavity` has been done, It tends to produce geometrically identical `Polygon` as PostGIS, but the Polygon generated starts at a different point from the Postgis version.
   
   First I tried with `rust-geo` It worked perfectly on some geometries, but was a bit rotated on other geometries, also, it tend to be more aggressive than Postgis; i.e truncating some points in the hull generated.
   
   Secondly I tried `geos` using `geo-sys` it worked for other geometries, but provided Geometrically Identical WKBs but Geometries starting at different points.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(c/sedona-geos): ST_ConcaveHull Implementation [sedona-db]

Posted by "Abeeujah (via GitHub)" <gi...@apache.org>.
Abeeujah commented on PR #431:
URL: https://github.com/apache/sedona-db/pull/431#issuecomment-3647306898

   > If we'd like to keep this implementation in the PR (which I think is great!), we need one test for every branch you have in the implementation (which here would be one for every geometry type plus the empty point). Testing all the empties is probably a good thing to do, too.
   
   It was panic-ing for Empty Points, Empty Points in Multi-Points and a GeometryCollection, I didn't exactly have a fix for it, and didn't want it getting in the way. 
   
   > I see you removed the geo-based implementation...happy to review if you're ever in the mood to re-add!
   
   Would open up another PR for the geo-based implementation.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] ST_ConcaveHull Implementation [sedona-db]

Posted by "Abeeujah (via GitHub)" <gi...@apache.org>.
Abeeujah commented on code in PR #431:
URL: https://github.com/apache/sedona-db/pull/431#discussion_r2611282698


##########
c/sedona-geos/src/st_concavehull.rs:
##########
@@ -0,0 +1,237 @@
+// 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::cast::{as_boolean_array, as_float64_array};
+use datafusion_common::error::Result;
+use datafusion_common::{DataFusionError, ScalarValue};
+use datafusion_expr::ColumnarValue;
+use geos::Geom;
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_geometry::wkb_factory::WKB_MIN_PROBABLE_BYTES;
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+
+use crate::executor::GeosExecutor;
+
+/// ST_ConcaveHull() implementation using the geos crate
+pub fn st_concave_hull_impl() -> ScalarKernelRef {
+    Arc::new(STConcaveHull {})
+}
+
+#[derive(Debug)]
+struct STConcaveHull {}
+
+impl SedonaScalarKernel for STConcaveHull {
+    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> {
+        invoke_batch_impl(arg_types, args)
+    }
+}
+
+fn invoke_batch_impl(arg_types: &[SedonaType], args: &[ColumnarValue]) -> Result<ColumnarValue> {
+    let executor = GeosExecutor::new(arg_types, args);
+    let mut builder = BinaryBuilder::with_capacity(
+        executor.num_iterations(),
+        WKB_MIN_PROBABLE_BYTES * executor.num_iterations(),
+    );
+
+    let pct_convex_val = args[1]
+        .cast_to(&DataType::Float64, None)?
+        .to_array(executor.num_iterations())?;
+    let pct_convex_array = as_float64_array(&pct_convex_val)?;
+    let mut pct_convex_iter = pct_convex_array.iter();
+
+    let allow_holes_val = args
+        .get(2)
+        .unwrap_or(&ColumnarValue::Scalar(ScalarValue::Boolean(Some(false))))
+        .cast_to(&DataType::Boolean, None)?
+        .to_array(executor.num_iterations())?;
+    let allow_holes_array = as_boolean_array(&allow_holes_val)?;
+    let mut allow_holes_iter = allow_holes_array.iter();
+
+    executor.execute_wkb_void(|maybe_wkb| {
+        match (
+            maybe_wkb,
+            pct_convex_iter.next().unwrap(),
+            allow_holes_iter.next().unwrap(),
+        ) {
+            (Some(wkb), Some(pct_convex), Some(allow_holes)) => {
+                invoke_scalar(&wkb, pct_convex, allow_holes, &mut builder)?;
+                builder.append_value([]);
+            }
+            _ => builder.append_null(),
+        }
+        Ok(())
+    })?;
+
+    executor.finish(Arc::new(builder.finish()))
+}
+
+fn invoke_scalar(
+    geos_geom: &geos::Geometry,
+    pct_convex: f64,
+    allow_holes: bool,
+    writer: &mut impl std::io::Write,
+) -> Result<()> {
+    let input_wkb = geos_geom
+        .to_wkb()
+        .map_err(|e| DataFusionError::Execution(format!("Failed to convert to WKB: {e}")))?;
+    let wkb_bytes: &[u8] = input_wkb.as_ref();
+
+    let result_wkb = concave_hull_via_geos_sys(wkb_bytes, pct_convex, allow_holes)?;
+
+    writer.write_all(&result_wkb)?;
+    Ok(())
+}
+
+fn concave_hull_via_geos_sys(input_wkb: &[u8], ratio: f64, allow_holes: bool) -> Result<Vec<u8>> {
+    unsafe {
+        let ctx = geos_sys::GEOS_init_r();
+        if ctx.is_null() {
+            return Err(DataFusionError::Execution(
+                "Failed to initialize GEOS context".to_string(),
+            ));
+        }

Review Comment:
   I'll update `geos` and remove the extra `geo-sys` dependency I was using.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] ST_ConcaveHull Implementation [sedona-db]

Posted by "Abeeujah (via GitHub)" <gi...@apache.org>.
Abeeujah commented on code in PR #431:
URL: https://github.com/apache/sedona-db/pull/431#discussion_r2611275685


##########
rust/sedona-geo/src/st_concavehull.rs:
##########
@@ -0,0 +1,270 @@
+// 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.
+
+#![allow(dead_code)]
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_common::ScalarValue;
+use datafusion_common::{
+    cast::{as_boolean_array, as_float64_array},
+    DataFusionError,
+};
+use datafusion_expr::ColumnarValue;
+use geo::{ConcaveHull, CoordsIter};
+use geo_traits::{GeometryCollectionTrait, GeometryTrait, PointTrait};
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_geometry::wkb_factory::{
+    write_wkb_coord_trait, write_wkb_empty_point, write_wkb_point_header, WKB_MIN_PROBABLE_BYTES,
+};
+use sedona_schema::datatypes::SedonaType;
+use sedona_schema::{datatypes::WKB_GEOMETRY, matchers::ArgMatcher};
+use wkb::writer::WriteOptions;
+
+use crate::to_geo::GeoTypesExecutor;
+
+/// ST_ConcaveHull implementation using [ConcaveHull]
+pub fn st_concavehull_impl() -> ScalarKernelRef {
+    Arc::new(STConcaveHull {})
+}
+
+#[derive(Debug)]
+struct STConcaveHull {}
+
+impl SedonaScalarKernel for STConcaveHull {
+    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> {
+        invoke_batch_impl(arg_types, args)
+    }
+}
+
+fn invoke_batch_impl(arg_types: &[SedonaType], args: &[ColumnarValue]) -> Result<ColumnarValue> {
+    let executor = GeoTypesExecutor::new(arg_types, args);
+    let mut builder = BinaryBuilder::with_capacity(
+        executor.num_iterations(),
+        WKB_MIN_PROBABLE_BYTES * executor.num_iterations(),
+    );
+
+    // Extract Args
+    let pct_convex_val = args[1]
+        .cast_to(&arrow_schema::DataType::Float64, None)?
+        .to_array(executor.num_iterations())?;
+    let pct_convex_array = as_float64_array(&pct_convex_val)?;
+    let mut pct_convex_iter = pct_convex_array.iter();
+
+    let allow_holes_val = args
+        .get(2)
+        .unwrap_or(&ColumnarValue::Scalar(ScalarValue::Boolean(Some(false))))
+        .cast_to(&arrow_schema::DataType::Boolean, None)?
+        .to_array(executor.num_iterations())?;
+    let allow_holes_array = as_boolean_array(&allow_holes_val)?;
+    let mut allow_holes_iter = allow_holes_array.iter();
+
+    executor.execute_wkb_void(|maybe_wkb| {
+        match (
+            maybe_wkb,
+            pct_convex_iter.next().unwrap(),
+            allow_holes_iter.next().unwrap(),
+        ) {
+            (Some(wkb), Some(pct_convex), Some(allow_holes)) => {
+                invoke_scalar(&wkb, pct_convex, allow_holes, &mut builder)?;
+                builder.append_value([]);
+            }
+            _ => builder.append_null(),
+        }
+
+        Ok(())
+    })?;
+
+    executor.finish(Arc::new(builder.finish()))
+}
+
+fn invoke_scalar(
+    geom: &geo_types::Geometry<f64>,
+    pct_convex: f64,
+    _allow_holes: bool,
+    writer: &mut impl std::io::Write,
+) -> Result<()> {
+    let dims = geom.dim();
+    match geom.as_type() {
+        geo_traits::GeometryType::Point(pt) => {
+            if pt.coord().is_some() {
+                write_wkb_point_header(writer, dims)
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+                write_wkb_coord_trait(writer, &pt.coord().unwrap())
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+            } else {
+                write_wkb_empty_point(writer, dims)
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+            }
+        }
+
+        geo_traits::GeometryType::MultiPoint(mpt) => {
+            let hull = mpt.concave_hull(pct_convex);
+            write_concave_hull(writer, hull)?;
+        }
+
+        geo_traits::GeometryType::LineString(ls) => {
+            let hull = ls.concave_hull(pct_convex);
+            write_concave_hull(writer, hull)?;
+        }
+
+        geo_traits::GeometryType::Polygon(pgn) => {
+            let hull = pgn.concave_hull(pct_convex);
+            write_concave_hull(writer, hull)?;
+        }
+
+        geo_traits::GeometryType::MultiLineString(mls) => {
+            let hull = mls.concave_hull(pct_convex);
+            write_concave_hull(writer, hull)?;
+        }
+
+        geo_traits::GeometryType::MultiPolygon(mpgn) => {
+            let hull = mpgn.concave_hull(pct_convex);
+            write_concave_hull(writer, hull)?;
+        }
+
+        geo_traits::GeometryType::GeometryCollection(gcn) => {
+            let coords: Vec<geo_types::Coord> = gcn
+                .geometries()
+                .flat_map(|geom| geom.coords_iter())
+                .collect();
+
+            let multi_point = geo_types::MultiPoint::new(
+                coords.into_iter().map(geo_types::Point::from).collect(),
+            );
+
+            let hull = multi_point.concave_hull(pct_convex);
+            write_concave_hull(writer, hull)?;
+        }
+
+        _ => {
+            return Err(DataFusionError::Execution(
+                "Unsupported geometry type for concave hull".to_string(),
+            ))
+        }
+    }
+
+    Ok(())
+}
+
+fn write_concave_hull<W: std::io::Write>(
+    writer: &mut W,
+    hull: impl GeometryTrait<T = f64>,
+) -> Result<()> {
+    wkb::writer::write_geometry(
+        writer,
+        &hull,
+        &WriteOptions {
+            endianness: wkb::Endianness::LittleEndian,
+        },
+    )
+    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+    Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+    use arrow_schema::DataType;
+    use rstest::rstest;
+    use sedona_expr::scalar_udf::SedonaScalarUDF;
+    use sedona_schema::datatypes::SedonaType;
+    use sedona_schema::datatypes::WKB_VIEW_GEOMETRY;
+    use sedona_testing::compare::assert_scalar_equal_wkb_geometry_topologically;
+    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_concavehull", st_concavehull_impl());
+        let tester = ScalarUdfTester::new(
+            udf.into(),
+            vec![sedona_type.clone(), SedonaType::Arrow(DataType::Float64)],
+        );
+        assert_eq!(tester.return_type().unwrap(), WKB_GEOMETRY);
+
+        let result = tester
+            .invoke_scalar_scalar("LINESTRING (50 50, 150 150, 150 50)", 0.1)
+            .unwrap();
+        assert_scalar_equal_wkb_geometry_topologically(
+            &result,
+            Some("POLYGON ((50 50, 150 150, 150 50, 50 50))"),
+        );

Review Comment:
   Would do that!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] ST_ConcaveHull Implementation [sedona-db]

Posted by "Abeeujah (via GitHub)" <gi...@apache.org>.
Abeeujah commented on code in PR #431:
URL: https://github.com/apache/sedona-db/pull/431#discussion_r2611279784


##########
rust/sedona-geo/src/lib.rs:
##########
@@ -18,6 +18,7 @@ pub mod centroid;
 pub mod register;
 mod st_area;
 mod st_centroid;
+mod st_concavehull;

Review Comment:
   Yeah, didn't deep this at the time, I only unregistered the function as it was taking precedence over the other `geos` implementation, would remove the clippy rule, and fix this.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] ST_ConcaveHull Implementation [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot commented on code in PR #431:
URL: https://github.com/apache/sedona-db/pull/431#discussion_r2611380504


##########
c/sedona-geos/src/st_concavehull.rs:
##########
@@ -0,0 +1,237 @@
+// 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::cast::{as_boolean_array, as_float64_array};
+use datafusion_common::error::Result;
+use datafusion_common::{DataFusionError, ScalarValue};
+use datafusion_expr::ColumnarValue;
+use geos::Geom;
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_geometry::wkb_factory::WKB_MIN_PROBABLE_BYTES;
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+
+use crate::executor::GeosExecutor;
+
+/// ST_ConcaveHull() implementation using the geos crate
+pub fn st_concave_hull_impl() -> ScalarKernelRef {
+    Arc::new(STConcaveHull {})
+}
+
+#[derive(Debug)]
+struct STConcaveHull {}
+
+impl SedonaScalarKernel for STConcaveHull {
+    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> {
+        invoke_batch_impl(arg_types, args)
+    }
+}
+
+fn invoke_batch_impl(arg_types: &[SedonaType], args: &[ColumnarValue]) -> Result<ColumnarValue> {
+    let executor = GeosExecutor::new(arg_types, args);
+    let mut builder = BinaryBuilder::with_capacity(
+        executor.num_iterations(),
+        WKB_MIN_PROBABLE_BYTES * executor.num_iterations(),
+    );
+
+    let pct_convex_val = args[1]
+        .cast_to(&DataType::Float64, None)?
+        .to_array(executor.num_iterations())?;
+    let pct_convex_array = as_float64_array(&pct_convex_val)?;
+    let mut pct_convex_iter = pct_convex_array.iter();
+
+    let allow_holes_val = args
+        .get(2)
+        .unwrap_or(&ColumnarValue::Scalar(ScalarValue::Boolean(Some(false))))
+        .cast_to(&DataType::Boolean, None)?
+        .to_array(executor.num_iterations())?;
+    let allow_holes_array = as_boolean_array(&allow_holes_val)?;
+    let mut allow_holes_iter = allow_holes_array.iter();
+
+    executor.execute_wkb_void(|maybe_wkb| {
+        match (
+            maybe_wkb,
+            pct_convex_iter.next().unwrap(),
+            allow_holes_iter.next().unwrap(),
+        ) {
+            (Some(wkb), Some(pct_convex), Some(allow_holes)) => {
+                invoke_scalar(&wkb, pct_convex, allow_holes, &mut builder)?;
+                builder.append_value([]);
+            }
+            _ => builder.append_null(),
+        }
+        Ok(())
+    })?;
+
+    executor.finish(Arc::new(builder.finish()))
+}
+
+fn invoke_scalar(
+    geos_geom: &geos::Geometry,
+    pct_convex: f64,
+    allow_holes: bool,
+    writer: &mut impl std::io::Write,
+) -> Result<()> {
+    let input_wkb = geos_geom
+        .to_wkb()
+        .map_err(|e| DataFusionError::Execution(format!("Failed to convert to WKB: {e}")))?;
+    let wkb_bytes: &[u8] = input_wkb.as_ref();
+
+    let result_wkb = concave_hull_via_geos_sys(wkb_bytes, pct_convex, allow_holes)?;
+
+    writer.write_all(&result_wkb)?;
+    Ok(())
+}
+
+fn concave_hull_via_geos_sys(input_wkb: &[u8], ratio: f64, allow_holes: bool) -> Result<Vec<u8>> {
+    unsafe {
+        let ctx = geos_sys::GEOS_init_r();
+        if ctx.is_null() {
+            return Err(DataFusionError::Execution(
+                "Failed to initialize GEOS context".to_string(),
+            ));
+        }

Review Comment:
   I'm happy to review all the changes in this PR or in two PRs, whichever is easier for you!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] ST_ConcaveHull Implementation [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot commented on code in PR #431:
URL: https://github.com/apache/sedona-db/pull/431#discussion_r2611201252


##########
rust/sedona-geo/src/st_concavehull.rs:
##########
@@ -0,0 +1,270 @@
+// 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.
+
+#![allow(dead_code)]
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_common::ScalarValue;
+use datafusion_common::{
+    cast::{as_boolean_array, as_float64_array},
+    DataFusionError,
+};
+use datafusion_expr::ColumnarValue;
+use geo::{ConcaveHull, CoordsIter};
+use geo_traits::{GeometryCollectionTrait, GeometryTrait, PointTrait};
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_geometry::wkb_factory::{
+    write_wkb_coord_trait, write_wkb_empty_point, write_wkb_point_header, WKB_MIN_PROBABLE_BYTES,
+};
+use sedona_schema::datatypes::SedonaType;
+use sedona_schema::{datatypes::WKB_GEOMETRY, matchers::ArgMatcher};
+use wkb::writer::WriteOptions;
+
+use crate::to_geo::GeoTypesExecutor;
+
+/// ST_ConcaveHull implementation using [ConcaveHull]
+pub fn st_concavehull_impl() -> ScalarKernelRef {
+    Arc::new(STConcaveHull {})
+}
+
+#[derive(Debug)]
+struct STConcaveHull {}
+
+impl SedonaScalarKernel for STConcaveHull {
+    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> {
+        invoke_batch_impl(arg_types, args)
+    }
+}
+
+fn invoke_batch_impl(arg_types: &[SedonaType], args: &[ColumnarValue]) -> Result<ColumnarValue> {
+    let executor = GeoTypesExecutor::new(arg_types, args);
+    let mut builder = BinaryBuilder::with_capacity(
+        executor.num_iterations(),
+        WKB_MIN_PROBABLE_BYTES * executor.num_iterations(),
+    );
+
+    // Extract Args
+    let pct_convex_val = args[1]
+        .cast_to(&arrow_schema::DataType::Float64, None)?
+        .to_array(executor.num_iterations())?;
+    let pct_convex_array = as_float64_array(&pct_convex_val)?;
+    let mut pct_convex_iter = pct_convex_array.iter();
+
+    let allow_holes_val = args
+        .get(2)
+        .unwrap_or(&ColumnarValue::Scalar(ScalarValue::Boolean(Some(false))))
+        .cast_to(&arrow_schema::DataType::Boolean, None)?
+        .to_array(executor.num_iterations())?;
+    let allow_holes_array = as_boolean_array(&allow_holes_val)?;
+    let mut allow_holes_iter = allow_holes_array.iter();
+
+    executor.execute_wkb_void(|maybe_wkb| {
+        match (
+            maybe_wkb,
+            pct_convex_iter.next().unwrap(),
+            allow_holes_iter.next().unwrap(),
+        ) {
+            (Some(wkb), Some(pct_convex), Some(allow_holes)) => {
+                invoke_scalar(&wkb, pct_convex, allow_holes, &mut builder)?;
+                builder.append_value([]);
+            }
+            _ => builder.append_null(),
+        }
+
+        Ok(())
+    })?;
+
+    executor.finish(Arc::new(builder.finish()))
+}
+
+fn invoke_scalar(
+    geom: &geo_types::Geometry<f64>,
+    pct_convex: f64,
+    _allow_holes: bool,
+    writer: &mut impl std::io::Write,
+) -> Result<()> {
+    let dims = geom.dim();
+    match geom.as_type() {
+        geo_traits::GeometryType::Point(pt) => {
+            if pt.coord().is_some() {
+                write_wkb_point_header(writer, dims)
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+                write_wkb_coord_trait(writer, &pt.coord().unwrap())
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+            } else {
+                write_wkb_empty_point(writer, dims)
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+            }
+        }
+
+        geo_traits::GeometryType::MultiPoint(mpt) => {
+            let hull = mpt.concave_hull(pct_convex);
+            write_concave_hull(writer, hull)?;
+        }
+
+        geo_traits::GeometryType::LineString(ls) => {
+            let hull = ls.concave_hull(pct_convex);
+            write_concave_hull(writer, hull)?;
+        }
+
+        geo_traits::GeometryType::Polygon(pgn) => {
+            let hull = pgn.concave_hull(pct_convex);
+            write_concave_hull(writer, hull)?;
+        }
+
+        geo_traits::GeometryType::MultiLineString(mls) => {
+            let hull = mls.concave_hull(pct_convex);
+            write_concave_hull(writer, hull)?;
+        }
+
+        geo_traits::GeometryType::MultiPolygon(mpgn) => {
+            let hull = mpgn.concave_hull(pct_convex);
+            write_concave_hull(writer, hull)?;
+        }
+
+        geo_traits::GeometryType::GeometryCollection(gcn) => {
+            let coords: Vec<geo_types::Coord> = gcn
+                .geometries()
+                .flat_map(|geom| geom.coords_iter())
+                .collect();
+
+            let multi_point = geo_types::MultiPoint::new(
+                coords.into_iter().map(geo_types::Point::from).collect(),
+            );
+
+            let hull = multi_point.concave_hull(pct_convex);
+            write_concave_hull(writer, hull)?;
+        }
+
+        _ => {
+            return Err(DataFusionError::Execution(
+                "Unsupported geometry type for concave hull".to_string(),
+            ))
+        }
+    }
+
+    Ok(())
+}
+
+fn write_concave_hull<W: std::io::Write>(
+    writer: &mut W,
+    hull: impl GeometryTrait<T = f64>,
+) -> Result<()> {
+    wkb::writer::write_geometry(
+        writer,
+        &hull,
+        &WriteOptions {
+            endianness: wkb::Endianness::LittleEndian,
+        },
+    )
+    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+    Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+    use arrow_schema::DataType;
+    use rstest::rstest;
+    use sedona_expr::scalar_udf::SedonaScalarUDF;
+    use sedona_schema::datatypes::SedonaType;
+    use sedona_schema::datatypes::WKB_VIEW_GEOMETRY;
+    use sedona_testing::compare::assert_scalar_equal_wkb_geometry_topologically;
+    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_concavehull", st_concavehull_impl());
+        let tester = ScalarUdfTester::new(
+            udf.into(),
+            vec![sedona_type.clone(), SedonaType::Arrow(DataType::Float64)],
+        );
+        assert_eq!(tester.return_type().unwrap(), WKB_GEOMETRY);
+
+        let result = tester
+            .invoke_scalar_scalar("LINESTRING (50 50, 150 150, 150 50)", 0.1)
+            .unwrap();
+        assert_scalar_equal_wkb_geometry_topologically(
+            &result,
+            Some("POLYGON ((50 50, 150 150, 150 50, 50 50))"),
+        );

Review Comment:
   If we'd like to keep this implementation in the PR (which I think is great!), we need one test for every branch you have in the implementation (which here would be one for every geometry type plus the empty point). Testing all the empties is probably a good thing to do, too.



##########
Cargo.toml:
##########
@@ -97,6 +97,7 @@ libmimalloc-sys = { version = "0.1", default-features = false }
 once_cell = "1.20"
 
 geos = { version = "10.0.0", features = ["geo", "v3_10_0"] }
+geos-sys = { version = "2.0.6", features = ["v3_11_0"] }

Review Comment:
   Ok I see...the concave hull feature was added in GEOS 3.11. The version of GEOS in Ubuntu 24.04 is 3.12 and so this shouldn't be a problem. If it is we could add some opt-in feature for various geos versions.



##########
rust/sedona-geo/src/lib.rs:
##########
@@ -18,6 +18,7 @@ pub mod centroid;
 pub mod register;
 mod st_area;
 mod st_centroid;
+mod st_concavehull;

Review Comment:
   ```suggestion
   pub mod st_concavehull;
   ```
   
   (then you can remove the allow dead code in that module and interested parties can manually register this implementation if they want to try it)



##########
c/sedona-geos/src/st_concavehull.rs:
##########
@@ -0,0 +1,237 @@
+// 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::cast::{as_boolean_array, as_float64_array};
+use datafusion_common::error::Result;
+use datafusion_common::{DataFusionError, ScalarValue};
+use datafusion_expr::ColumnarValue;
+use geos::Geom;
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_geometry::wkb_factory::WKB_MIN_PROBABLE_BYTES;
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+
+use crate::executor::GeosExecutor;
+
+/// ST_ConcaveHull() implementation using the geos crate
+pub fn st_concave_hull_impl() -> ScalarKernelRef {
+    Arc::new(STConcaveHull {})
+}
+
+#[derive(Debug)]
+struct STConcaveHull {}
+
+impl SedonaScalarKernel for STConcaveHull {

Review Comment:
   Ok I take this back...feel free to add both of these as long as they're tested, which they mostly are! (I'll leave a suggestion below about how to avoid the allow(dead_code).)



##########
c/sedona-geos/src/st_concavehull.rs:
##########
@@ -0,0 +1,237 @@
+// 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::cast::{as_boolean_array, as_float64_array};
+use datafusion_common::error::Result;
+use datafusion_common::{DataFusionError, ScalarValue};
+use datafusion_expr::ColumnarValue;
+use geos::Geom;
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_geometry::wkb_factory::WKB_MIN_PROBABLE_BYTES;
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+
+use crate::executor::GeosExecutor;
+
+/// ST_ConcaveHull() implementation using the geos crate
+pub fn st_concave_hull_impl() -> ScalarKernelRef {
+    Arc::new(STConcaveHull {})
+}
+
+#[derive(Debug)]
+struct STConcaveHull {}
+
+impl SedonaScalarKernel for STConcaveHull {
+    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> {
+        invoke_batch_impl(arg_types, args)
+    }
+}
+
+fn invoke_batch_impl(arg_types: &[SedonaType], args: &[ColumnarValue]) -> Result<ColumnarValue> {
+    let executor = GeosExecutor::new(arg_types, args);
+    let mut builder = BinaryBuilder::with_capacity(
+        executor.num_iterations(),
+        WKB_MIN_PROBABLE_BYTES * executor.num_iterations(),
+    );
+
+    let pct_convex_val = args[1]
+        .cast_to(&DataType::Float64, None)?
+        .to_array(executor.num_iterations())?;
+    let pct_convex_array = as_float64_array(&pct_convex_val)?;
+    let mut pct_convex_iter = pct_convex_array.iter();
+
+    let allow_holes_val = args
+        .get(2)
+        .unwrap_or(&ColumnarValue::Scalar(ScalarValue::Boolean(Some(false))))
+        .cast_to(&DataType::Boolean, None)?
+        .to_array(executor.num_iterations())?;
+    let allow_holes_array = as_boolean_array(&allow_holes_val)?;
+    let mut allow_holes_iter = allow_holes_array.iter();
+
+    executor.execute_wkb_void(|maybe_wkb| {
+        match (
+            maybe_wkb,
+            pct_convex_iter.next().unwrap(),
+            allow_holes_iter.next().unwrap(),
+        ) {
+            (Some(wkb), Some(pct_convex), Some(allow_holes)) => {
+                invoke_scalar(&wkb, pct_convex, allow_holes, &mut builder)?;
+                builder.append_value([]);
+            }
+            _ => builder.append_null(),
+        }
+        Ok(())
+    })?;
+
+    executor.finish(Arc::new(builder.finish()))
+}
+
+fn invoke_scalar(
+    geos_geom: &geos::Geometry,
+    pct_convex: f64,
+    allow_holes: bool,
+    writer: &mut impl std::io::Write,
+) -> Result<()> {
+    let input_wkb = geos_geom
+        .to_wkb()
+        .map_err(|e| DataFusionError::Execution(format!("Failed to convert to WKB: {e}")))?;
+    let wkb_bytes: &[u8] = input_wkb.as_ref();
+
+    let result_wkb = concave_hull_via_geos_sys(wkb_bytes, pct_convex, allow_holes)?;
+
+    writer.write_all(&result_wkb)?;
+    Ok(())
+}
+
+fn concave_hull_via_geos_sys(input_wkb: &[u8], ratio: f64, allow_holes: bool) -> Result<Vec<u8>> {
+    unsafe {
+        let ctx = geos_sys::GEOS_init_r();
+        if ctx.is_null() {
+            return Err(DataFusionError::Execution(
+                "Failed to initialize GEOS context".to_string(),
+            ));
+        }

Review Comment:
   It looks like this has been added upstream:
   
   https://github.com/georust/geos/blob/47afbad2483e489911ddb456417808340e9342c3/src/geometry.rs#L2443-L2454
   
   I asked on the GeoRust discord about the possibility of a release...I think it's likely we can help with one before our next release. In the meantime, you could update our dependency in Cargo.toml to a Git dependency and use that function directly.



##########
rust/sedona-geo/src/st_concavehull.rs:
##########
@@ -0,0 +1,270 @@
+// 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.
+
+#![allow(dead_code)]
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_common::ScalarValue;
+use datafusion_common::{
+    cast::{as_boolean_array, as_float64_array},
+    DataFusionError,
+};
+use datafusion_expr::ColumnarValue;
+use geo::{ConcaveHull, CoordsIter};
+use geo_traits::{GeometryCollectionTrait, GeometryTrait, PointTrait};
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_geometry::wkb_factory::{
+    write_wkb_coord_trait, write_wkb_empty_point, write_wkb_point_header, WKB_MIN_PROBABLE_BYTES,
+};
+use sedona_schema::datatypes::SedonaType;
+use sedona_schema::{datatypes::WKB_GEOMETRY, matchers::ArgMatcher};
+use wkb::writer::WriteOptions;
+
+use crate::to_geo::GeoTypesExecutor;
+
+/// ST_ConcaveHull implementation using [ConcaveHull]
+pub fn st_concavehull_impl() -> ScalarKernelRef {
+    Arc::new(STConcaveHull {})
+}
+
+#[derive(Debug)]
+struct STConcaveHull {}
+
+impl SedonaScalarKernel for STConcaveHull {
+    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> {
+        invoke_batch_impl(arg_types, args)
+    }

Review Comment:
   I'm not sure we need this wrapper function here (Maybe just inline `invoke_batch_impl()` here?)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] ST_ConcaveHull Implementation [sedona-db]

Posted by "Abeeujah (via GitHub)" <gi...@apache.org>.
Abeeujah commented on code in PR #431:
URL: https://github.com/apache/sedona-db/pull/431#discussion_r2606243052


##########
rust/sedona-geo/src/st_concavehull.rs:
##########
@@ -0,0 +1,231 @@
+// 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.
+
+#![allow(dead_code)]
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_common::ScalarValue;
+use datafusion_common::{
+    cast::{as_boolean_array, as_float64_array},
+    DataFusionError,
+};
+use datafusion_expr::ColumnarValue;
+use geo::{ConcaveHull, CoordsIter};
+use geo_traits::{Dimensions, GeometryCollectionTrait, GeometryTrait, LineStringTrait, PointTrait};
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_geometry::wkb_factory::{
+    write_wkb_coord_trait, write_wkb_empty_point, write_wkb_point_header, write_wkb_polygon_header,
+    write_wkb_polygon_ring_header, WKB_MIN_PROBABLE_BYTES,
+};
+use sedona_schema::datatypes::SedonaType;
+use sedona_schema::{datatypes::WKB_GEOMETRY, matchers::ArgMatcher};
+
+use crate::to_geo::GeoTypesExecutor;
+
+/// ST_ConcaveHull implementation using [ConcaveHull]
+pub fn st_concavehull_impl() -> ScalarKernelRef {
+    Arc::new(STConcaveHull {})
+}
+
+#[derive(Debug)]
+struct STConcaveHull {}
+
+impl SedonaScalarKernel for STConcaveHull {
+    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> {
+        invoke_batch_impl(arg_types, args)
+    }
+}
+
+fn invoke_batch_impl(arg_types: &[SedonaType], args: &[ColumnarValue]) -> Result<ColumnarValue> {
+    let executor = GeoTypesExecutor::new(arg_types, args);
+    let mut builder = BinaryBuilder::with_capacity(
+        executor.num_iterations(),
+        WKB_MIN_PROBABLE_BYTES * executor.num_iterations(),
+    );
+
+    // Extract Args
+    let pct_convex_val = args[1]
+        .cast_to(&arrow_schema::DataType::Float64, None)?
+        .to_array(executor.num_iterations())?;
+    let pct_convex_array = as_float64_array(&pct_convex_val)?;
+    let mut pct_convex_iter = pct_convex_array.iter();
+
+    let allow_holes_val = args
+        .get(2)
+        .unwrap_or(&ColumnarValue::Scalar(ScalarValue::Boolean(Some(false))))
+        .cast_to(&arrow_schema::DataType::Boolean, None)?
+        .to_array(executor.num_iterations())?;
+    let allow_holes_array = as_boolean_array(&allow_holes_val)?;
+    let mut allow_holes_iter = allow_holes_array.iter();
+
+    executor.execute_wkb_void(|maybe_wkb| {
+        match (
+            maybe_wkb,
+            pct_convex_iter.next().unwrap(),
+            allow_holes_iter.next().unwrap(),
+        ) {
+            (Some(wkb), Some(pct_convex), Some(allow_holes)) => {
+                invoke_scalar(&wkb, pct_convex, allow_holes, &mut builder)?;
+                builder.append_value([]);
+            }
+            _ => builder.append_null(),
+        }
+
+        Ok(())
+    })?;
+
+    executor.finish(Arc::new(builder.finish()))
+}
+
+fn invoke_scalar(
+    geom: &geo_types::Geometry<f64>,
+    pct_convex: f64,
+    _allow_holes: bool,
+    writer: &mut impl std::io::Write,
+) -> Result<()> {
+    let dims = geom.dim();
+    match geom.as_type() {
+        geo_traits::GeometryType::Point(pt) => {
+            if pt.coord().is_some() {
+                write_wkb_point_header(writer, dims)
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+                write_wkb_coord_trait(writer, &pt.coord().unwrap())
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+            } else {
+                write_wkb_empty_point(writer, dims)
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+            }
+        }
+
+        geo_traits::GeometryType::MultiPoint(mpt) => {
+            let hull = mpt.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::LineString(ls) => {
+            let hull = ls.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::Polygon(pgn) => {
+            let hull = pgn.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::MultiLineString(mls) => {
+            let hull = mls.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::MultiPolygon(mpgn) => {
+            let hull = mpgn.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::GeometryCollection(gcn) => {
+            let coords: Vec<geo_types::Coord> = gcn
+                .geometries()
+                .flat_map(|geom| geom.coords_iter())
+                .collect();
+
+            let multi_point = geo_types::MultiPoint::new(
+                coords.into_iter().map(geo_types::Point::from).collect(),
+            );
+
+            let hull = multi_point.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        _ => {
+            return Err(DataFusionError::Execution(
+                "Unsupported geometry type for concave hull".to_string(),
+            ))
+        }
+    }
+
+    Ok(())
+}
+
+fn write_concave_hull<W: std::io::Write>(
+    writer: &mut W,
+    dims: Dimensions,
+    hull: geo_types::Polygon,
+) -> Result<()> {
+    write_wkb_polygon_header(writer, dims, hull.num_rings())
+        .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+    write_concave_ring(writer, hull.exterior())?;
+    for interior in hull.interiors() {
+        write_concave_ring(writer, interior)?
+    }
+    Ok(())
+}

Review Comment:
   Using this gets it right, thank you for recommending!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(c/sedona-geos): ST_ConcaveHull Implementation [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot merged PR #431:
URL: https://github.com/apache/sedona-db/pull/431


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] ST_ConcaveHull Implementation [sedona-db]

Posted by "Abeeujah (via GitHub)" <gi...@apache.org>.
Abeeujah commented on code in PR #431:
URL: https://github.com/apache/sedona-db/pull/431#discussion_r2611362452


##########
c/sedona-geos/src/st_concavehull.rs:
##########
@@ -0,0 +1,237 @@
+// 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::cast::{as_boolean_array, as_float64_array};
+use datafusion_common::error::Result;
+use datafusion_common::{DataFusionError, ScalarValue};
+use datafusion_expr::ColumnarValue;
+use geos::Geom;
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_geometry::wkb_factory::WKB_MIN_PROBABLE_BYTES;
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+
+use crate::executor::GeosExecutor;
+
+/// ST_ConcaveHull() implementation using the geos crate
+pub fn st_concave_hull_impl() -> ScalarKernelRef {
+    Arc::new(STConcaveHull {})
+}
+
+#[derive(Debug)]
+struct STConcaveHull {}
+
+impl SedonaScalarKernel for STConcaveHull {
+    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> {
+        invoke_batch_impl(arg_types, args)
+    }
+}
+
+fn invoke_batch_impl(arg_types: &[SedonaType], args: &[ColumnarValue]) -> Result<ColumnarValue> {
+    let executor = GeosExecutor::new(arg_types, args);
+    let mut builder = BinaryBuilder::with_capacity(
+        executor.num_iterations(),
+        WKB_MIN_PROBABLE_BYTES * executor.num_iterations(),
+    );
+
+    let pct_convex_val = args[1]
+        .cast_to(&DataType::Float64, None)?
+        .to_array(executor.num_iterations())?;
+    let pct_convex_array = as_float64_array(&pct_convex_val)?;
+    let mut pct_convex_iter = pct_convex_array.iter();
+
+    let allow_holes_val = args
+        .get(2)
+        .unwrap_or(&ColumnarValue::Scalar(ScalarValue::Boolean(Some(false))))
+        .cast_to(&DataType::Boolean, None)?
+        .to_array(executor.num_iterations())?;
+    let allow_holes_array = as_boolean_array(&allow_holes_val)?;
+    let mut allow_holes_iter = allow_holes_array.iter();
+
+    executor.execute_wkb_void(|maybe_wkb| {
+        match (
+            maybe_wkb,
+            pct_convex_iter.next().unwrap(),
+            allow_holes_iter.next().unwrap(),
+        ) {
+            (Some(wkb), Some(pct_convex), Some(allow_holes)) => {
+                invoke_scalar(&wkb, pct_convex, allow_holes, &mut builder)?;
+                builder.append_value([]);
+            }
+            _ => builder.append_null(),
+        }
+        Ok(())
+    })?;
+
+    executor.finish(Arc::new(builder.finish()))
+}
+
+fn invoke_scalar(
+    geos_geom: &geos::Geometry,
+    pct_convex: f64,
+    allow_holes: bool,
+    writer: &mut impl std::io::Write,
+) -> Result<()> {
+    let input_wkb = geos_geom
+        .to_wkb()
+        .map_err(|e| DataFusionError::Execution(format!("Failed to convert to WKB: {e}")))?;
+    let wkb_bytes: &[u8] = input_wkb.as_ref();
+
+    let result_wkb = concave_hull_via_geos_sys(wkb_bytes, pct_convex, allow_holes)?;
+
+    writer.write_all(&result_wkb)?;
+    Ok(())
+}
+
+fn concave_hull_via_geos_sys(input_wkb: &[u8], ratio: f64, allow_holes: bool) -> Result<Vec<u8>> {
+    unsafe {
+        let ctx = geos_sys::GEOS_init_r();
+        if ctx.is_null() {
+            return Err(DataFusionError::Execution(
+                "Failed to initialize GEOS context".to_string(),
+            ));
+        }

Review Comment:
   Upgrading to this version, and lots of errors, about 40 errors in 10 files, I could fix them all, but I don't think that would be good for this PR, would probably convert it to a two stage job, update to feature `3.11.0` and then implement `ST_ConcaveHull` using geos.
   
   Would finish the `geo` version instead in this PR, unless you would be cool with reviewing all the changes in this one PR.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] ST_ConcaveHull Implementation [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot commented on code in PR #431:
URL: https://github.com/apache/sedona-db/pull/431#discussion_r2604348650


##########
rust/sedona-geo/src/st_concavehull.rs:
##########
@@ -0,0 +1,231 @@
+// 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.
+
+#![allow(dead_code)]
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_common::ScalarValue;
+use datafusion_common::{
+    cast::{as_boolean_array, as_float64_array},
+    DataFusionError,
+};
+use datafusion_expr::ColumnarValue;
+use geo::{ConcaveHull, CoordsIter};
+use geo_traits::{Dimensions, GeometryCollectionTrait, GeometryTrait, LineStringTrait, PointTrait};
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_geometry::wkb_factory::{
+    write_wkb_coord_trait, write_wkb_empty_point, write_wkb_point_header, write_wkb_polygon_header,
+    write_wkb_polygon_ring_header, WKB_MIN_PROBABLE_BYTES,
+};
+use sedona_schema::datatypes::SedonaType;
+use sedona_schema::{datatypes::WKB_GEOMETRY, matchers::ArgMatcher};
+
+use crate::to_geo::GeoTypesExecutor;
+
+/// ST_ConcaveHull implementation using [ConcaveHull]
+pub fn st_concavehull_impl() -> ScalarKernelRef {
+    Arc::new(STConcaveHull {})
+}
+
+#[derive(Debug)]
+struct STConcaveHull {}
+
+impl SedonaScalarKernel for STConcaveHull {
+    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> {
+        invoke_batch_impl(arg_types, args)
+    }
+}
+
+fn invoke_batch_impl(arg_types: &[SedonaType], args: &[ColumnarValue]) -> Result<ColumnarValue> {
+    let executor = GeoTypesExecutor::new(arg_types, args);
+    let mut builder = BinaryBuilder::with_capacity(
+        executor.num_iterations(),
+        WKB_MIN_PROBABLE_BYTES * executor.num_iterations(),
+    );
+
+    // Extract Args
+    let pct_convex_val = args[1]
+        .cast_to(&arrow_schema::DataType::Float64, None)?
+        .to_array(executor.num_iterations())?;
+    let pct_convex_array = as_float64_array(&pct_convex_val)?;
+    let mut pct_convex_iter = pct_convex_array.iter();
+
+    let allow_holes_val = args
+        .get(2)
+        .unwrap_or(&ColumnarValue::Scalar(ScalarValue::Boolean(Some(false))))
+        .cast_to(&arrow_schema::DataType::Boolean, None)?
+        .to_array(executor.num_iterations())?;
+    let allow_holes_array = as_boolean_array(&allow_holes_val)?;
+    let mut allow_holes_iter = allow_holes_array.iter();
+
+    executor.execute_wkb_void(|maybe_wkb| {
+        match (
+            maybe_wkb,
+            pct_convex_iter.next().unwrap(),
+            allow_holes_iter.next().unwrap(),
+        ) {
+            (Some(wkb), Some(pct_convex), Some(allow_holes)) => {
+                invoke_scalar(&wkb, pct_convex, allow_holes, &mut builder)?;
+                builder.append_value([]);
+            }
+            _ => builder.append_null(),
+        }
+
+        Ok(())
+    })?;
+
+    executor.finish(Arc::new(builder.finish()))
+}
+
+fn invoke_scalar(
+    geom: &geo_types::Geometry<f64>,
+    pct_convex: f64,
+    _allow_holes: bool,
+    writer: &mut impl std::io::Write,
+) -> Result<()> {
+    let dims = geom.dim();
+    match geom.as_type() {
+        geo_traits::GeometryType::Point(pt) => {
+            if pt.coord().is_some() {
+                write_wkb_point_header(writer, dims)
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+                write_wkb_coord_trait(writer, &pt.coord().unwrap())
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+            } else {
+                write_wkb_empty_point(writer, dims)
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+            }
+        }
+
+        geo_traits::GeometryType::MultiPoint(mpt) => {
+            let hull = mpt.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::LineString(ls) => {
+            let hull = ls.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::Polygon(pgn) => {
+            let hull = pgn.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::MultiLineString(mls) => {
+            let hull = mls.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::MultiPolygon(mpgn) => {
+            let hull = mpgn.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::GeometryCollection(gcn) => {
+            let coords: Vec<geo_types::Coord> = gcn
+                .geometries()
+                .flat_map(|geom| geom.coords_iter())
+                .collect();
+
+            let multi_point = geo_types::MultiPoint::new(
+                coords.into_iter().map(geo_types::Point::from).collect(),
+            );
+
+            let hull = multi_point.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        _ => {
+            return Err(DataFusionError::Execution(
+                "Unsupported geometry type for concave hull".to_string(),
+            ))
+        }
+    }
+
+    Ok(())
+}
+
+fn write_concave_hull<W: std::io::Write>(
+    writer: &mut W,
+    dims: Dimensions,
+    hull: geo_types::Polygon,
+) -> Result<()> {
+    write_wkb_polygon_header(writer, dims, hull.num_rings())
+        .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+    write_concave_ring(writer, hull.exterior())?;
+    for interior in hull.interiors() {
+        write_concave_ring(writer, interior)?
+    }
+    Ok(())
+}

Review Comment:
   I think you may be able to just use `wkb::writer::write_wkb()` here? I don't think you need to reverse the order of the output ring. 



##########
Cargo.toml:
##########
@@ -97,6 +97,7 @@ libmimalloc-sys = { version = "0.1", default-features = false }
 once_cell = "1.20"
 
 geos = { version = "10.0.0", features = ["geo", "v3_10_0"] }
+geos-sys = { version = "2.0.6", features = ["v3_11_0"] }

Review Comment:
   See my general note here...I think we can avoid this!



##########
rust/sedona-geo/src/st_concavehull.rs:
##########
@@ -0,0 +1,231 @@
+// 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.
+
+#![allow(dead_code)]
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_common::ScalarValue;
+use datafusion_common::{
+    cast::{as_boolean_array, as_float64_array},
+    DataFusionError,
+};
+use datafusion_expr::ColumnarValue;
+use geo::{ConcaveHull, CoordsIter};
+use geo_traits::{Dimensions, GeometryCollectionTrait, GeometryTrait, LineStringTrait, PointTrait};
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_geometry::wkb_factory::{
+    write_wkb_coord_trait, write_wkb_empty_point, write_wkb_point_header, write_wkb_polygon_header,
+    write_wkb_polygon_ring_header, WKB_MIN_PROBABLE_BYTES,
+};
+use sedona_schema::datatypes::SedonaType;
+use sedona_schema::{datatypes::WKB_GEOMETRY, matchers::ArgMatcher};
+
+use crate::to_geo::GeoTypesExecutor;
+
+/// ST_ConcaveHull implementation using [ConcaveHull]
+pub fn st_concavehull_impl() -> ScalarKernelRef {
+    Arc::new(STConcaveHull {})
+}
+
+#[derive(Debug)]
+struct STConcaveHull {}
+
+impl SedonaScalarKernel for STConcaveHull {
+    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> {
+        invoke_batch_impl(arg_types, args)
+    }
+}
+
+fn invoke_batch_impl(arg_types: &[SedonaType], args: &[ColumnarValue]) -> Result<ColumnarValue> {
+    let executor = GeoTypesExecutor::new(arg_types, args);
+    let mut builder = BinaryBuilder::with_capacity(
+        executor.num_iterations(),
+        WKB_MIN_PROBABLE_BYTES * executor.num_iterations(),
+    );
+
+    // Extract Args
+    let pct_convex_val = args[1]
+        .cast_to(&arrow_schema::DataType::Float64, None)?
+        .to_array(executor.num_iterations())?;
+    let pct_convex_array = as_float64_array(&pct_convex_val)?;
+    let mut pct_convex_iter = pct_convex_array.iter();
+
+    let allow_holes_val = args
+        .get(2)
+        .unwrap_or(&ColumnarValue::Scalar(ScalarValue::Boolean(Some(false))))
+        .cast_to(&arrow_schema::DataType::Boolean, None)?
+        .to_array(executor.num_iterations())?;
+    let allow_holes_array = as_boolean_array(&allow_holes_val)?;
+    let mut allow_holes_iter = allow_holes_array.iter();
+
+    executor.execute_wkb_void(|maybe_wkb| {
+        match (
+            maybe_wkb,
+            pct_convex_iter.next().unwrap(),
+            allow_holes_iter.next().unwrap(),
+        ) {
+            (Some(wkb), Some(pct_convex), Some(allow_holes)) => {
+                invoke_scalar(&wkb, pct_convex, allow_holes, &mut builder)?;
+                builder.append_value([]);
+            }
+            _ => builder.append_null(),
+        }
+
+        Ok(())
+    })?;
+
+    executor.finish(Arc::new(builder.finish()))
+}
+
+fn invoke_scalar(
+    geom: &geo_types::Geometry<f64>,
+    pct_convex: f64,
+    _allow_holes: bool,
+    writer: &mut impl std::io::Write,
+) -> Result<()> {
+    let dims = geom.dim();
+    match geom.as_type() {
+        geo_traits::GeometryType::Point(pt) => {
+            if pt.coord().is_some() {
+                write_wkb_point_header(writer, dims)
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+                write_wkb_coord_trait(writer, &pt.coord().unwrap())
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+            } else {
+                write_wkb_empty_point(writer, dims)
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+            }
+        }
+
+        geo_traits::GeometryType::MultiPoint(mpt) => {
+            let hull = mpt.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::LineString(ls) => {
+            let hull = ls.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::Polygon(pgn) => {
+            let hull = pgn.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::MultiLineString(mls) => {
+            let hull = mls.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::MultiPolygon(mpgn) => {
+            let hull = mpgn.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::GeometryCollection(gcn) => {
+            let coords: Vec<geo_types::Coord> = gcn
+                .geometries()
+                .flat_map(|geom| geom.coords_iter())
+                .collect();
+
+            let multi_point = geo_types::MultiPoint::new(
+                coords.into_iter().map(geo_types::Point::from).collect(),
+            );
+
+            let hull = multi_point.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        _ => {
+            return Err(DataFusionError::Execution(
+                "Unsupported geometry type for concave hull".to_string(),
+            ))
+        }
+    }
+
+    Ok(())
+}
+
+fn write_concave_hull<W: std::io::Write>(
+    writer: &mut W,
+    dims: Dimensions,
+    hull: geo_types::Polygon,
+) -> Result<()> {
+    write_wkb_polygon_header(writer, dims, hull.num_rings())
+        .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+    write_concave_ring(writer, hull.exterior())?;
+    for interior in hull.interiors() {
+        write_concave_ring(writer, interior)?
+    }
+    Ok(())
+}
+
+fn write_concave_ring(
+    writer: &mut impl std::io::Write,
+    ring: impl LineStringTrait<T = f64>,
+) -> Result<()> {
+    write_wkb_polygon_ring_header(writer, ring.num_coords())
+        .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+    ring.coords().rev().try_for_each(|coord| {
+        write_wkb_coord_trait(writer, &coord).map_err(|e| DataFusionError::Execution(e.to_string()))
+    })
+}
+
+#[cfg(test)]
+mod tests {
+    use arrow_schema::DataType;
+    use rstest::rstest;
+    use sedona_expr::scalar_udf::SedonaScalarUDF;
+    use sedona_schema::datatypes::SedonaType;
+    use sedona_schema::datatypes::WKB_VIEW_GEOMETRY;
+    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_concavehull", st_concavehull_impl());
+        let tester = ScalarUdfTester::new(
+            udf.into(),
+            vec![sedona_type.clone(), SedonaType::Arrow(DataType::Float64)],
+        );
+        assert_eq!(tester.return_type().unwrap(), WKB_GEOMETRY);
+
+        let result = tester
+            .invoke_scalar_scalar(
+                "GEOMETRYCOLLECTION (MULTIPOINT((1 1), (3 3)), POINT(5 6), LINESTRING(4 5, 5 6))",
+                0.1,
+            )
+            .unwrap();
+        tester.assert_scalar_result_equals(result, "POLYGON ((3 3, 1 1, 4 5, 5 6, 3 3))");

Review Comment:
   I think what you want here is to compare the result "topologically" (i.e., a rust version of ST_Equals(actual, expected):
   
   https://github.com/apache/sedona-db/blob/9115c194b013d30bb21ade974642229387b9a5b9/rust/sedona-testing/src/compare.rs#L256-L288



##########
c/sedona-geos/src/st_concavehull.rs:
##########
@@ -0,0 +1,237 @@
+// 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::cast::{as_boolean_array, as_float64_array};
+use datafusion_common::error::Result;
+use datafusion_common::{DataFusionError, ScalarValue};
+use datafusion_expr::ColumnarValue;
+use geos::Geom;
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_geometry::wkb_factory::WKB_MIN_PROBABLE_BYTES;
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+
+use crate::executor::GeosExecutor;
+
+/// ST_ConcaveHull() implementation using the geos crate
+pub fn st_concave_hull_impl() -> ScalarKernelRef {
+    Arc::new(STConcaveHull {})
+}
+
+#[derive(Debug)]
+struct STConcaveHull {}
+
+impl SedonaScalarKernel for STConcaveHull {

Review Comment:
   For the purposes of this PR I think just adding one kernel makes sense (whichever one is faster!)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] ST_ConcaveHull Implementation [sedona-db]

Posted by "Abeeujah (via GitHub)" <gi...@apache.org>.
Abeeujah commented on code in PR #431:
URL: https://github.com/apache/sedona-db/pull/431#discussion_r2606265975


##########
rust/sedona-geo/src/st_concavehull.rs:
##########
@@ -0,0 +1,231 @@
+// 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.
+
+#![allow(dead_code)]
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_common::ScalarValue;
+use datafusion_common::{
+    cast::{as_boolean_array, as_float64_array},
+    DataFusionError,
+};
+use datafusion_expr::ColumnarValue;
+use geo::{ConcaveHull, CoordsIter};
+use geo_traits::{Dimensions, GeometryCollectionTrait, GeometryTrait, LineStringTrait, PointTrait};
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_geometry::wkb_factory::{
+    write_wkb_coord_trait, write_wkb_empty_point, write_wkb_point_header, write_wkb_polygon_header,
+    write_wkb_polygon_ring_header, WKB_MIN_PROBABLE_BYTES,
+};
+use sedona_schema::datatypes::SedonaType;
+use sedona_schema::{datatypes::WKB_GEOMETRY, matchers::ArgMatcher};
+
+use crate::to_geo::GeoTypesExecutor;
+
+/// ST_ConcaveHull implementation using [ConcaveHull]
+pub fn st_concavehull_impl() -> ScalarKernelRef {
+    Arc::new(STConcaveHull {})
+}
+
+#[derive(Debug)]
+struct STConcaveHull {}
+
+impl SedonaScalarKernel for STConcaveHull {
+    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> {
+        invoke_batch_impl(arg_types, args)
+    }
+}
+
+fn invoke_batch_impl(arg_types: &[SedonaType], args: &[ColumnarValue]) -> Result<ColumnarValue> {
+    let executor = GeoTypesExecutor::new(arg_types, args);
+    let mut builder = BinaryBuilder::with_capacity(
+        executor.num_iterations(),
+        WKB_MIN_PROBABLE_BYTES * executor.num_iterations(),
+    );
+
+    // Extract Args
+    let pct_convex_val = args[1]
+        .cast_to(&arrow_schema::DataType::Float64, None)?
+        .to_array(executor.num_iterations())?;
+    let pct_convex_array = as_float64_array(&pct_convex_val)?;
+    let mut pct_convex_iter = pct_convex_array.iter();
+
+    let allow_holes_val = args
+        .get(2)
+        .unwrap_or(&ColumnarValue::Scalar(ScalarValue::Boolean(Some(false))))
+        .cast_to(&arrow_schema::DataType::Boolean, None)?
+        .to_array(executor.num_iterations())?;
+    let allow_holes_array = as_boolean_array(&allow_holes_val)?;
+    let mut allow_holes_iter = allow_holes_array.iter();
+
+    executor.execute_wkb_void(|maybe_wkb| {
+        match (
+            maybe_wkb,
+            pct_convex_iter.next().unwrap(),
+            allow_holes_iter.next().unwrap(),
+        ) {
+            (Some(wkb), Some(pct_convex), Some(allow_holes)) => {
+                invoke_scalar(&wkb, pct_convex, allow_holes, &mut builder)?;
+                builder.append_value([]);
+            }
+            _ => builder.append_null(),
+        }
+
+        Ok(())
+    })?;
+
+    executor.finish(Arc::new(builder.finish()))
+}
+
+fn invoke_scalar(
+    geom: &geo_types::Geometry<f64>,
+    pct_convex: f64,
+    _allow_holes: bool,
+    writer: &mut impl std::io::Write,
+) -> Result<()> {
+    let dims = geom.dim();
+    match geom.as_type() {
+        geo_traits::GeometryType::Point(pt) => {
+            if pt.coord().is_some() {
+                write_wkb_point_header(writer, dims)
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+                write_wkb_coord_trait(writer, &pt.coord().unwrap())
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+            } else {
+                write_wkb_empty_point(writer, dims)
+                    .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+            }
+        }
+
+        geo_traits::GeometryType::MultiPoint(mpt) => {
+            let hull = mpt.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::LineString(ls) => {
+            let hull = ls.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::Polygon(pgn) => {
+            let hull = pgn.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::MultiLineString(mls) => {
+            let hull = mls.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::MultiPolygon(mpgn) => {
+            let hull = mpgn.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        geo_traits::GeometryType::GeometryCollection(gcn) => {
+            let coords: Vec<geo_types::Coord> = gcn
+                .geometries()
+                .flat_map(|geom| geom.coords_iter())
+                .collect();
+
+            let multi_point = geo_types::MultiPoint::new(
+                coords.into_iter().map(geo_types::Point::from).collect(),
+            );
+
+            let hull = multi_point.concave_hull(pct_convex);
+            write_concave_hull(writer, dims, hull)?;
+        }
+
+        _ => {
+            return Err(DataFusionError::Execution(
+                "Unsupported geometry type for concave hull".to_string(),
+            ))
+        }
+    }
+
+    Ok(())
+}
+
+fn write_concave_hull<W: std::io::Write>(
+    writer: &mut W,
+    dims: Dimensions,
+    hull: geo_types::Polygon,
+) -> Result<()> {
+    write_wkb_polygon_header(writer, dims, hull.num_rings())
+        .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+    write_concave_ring(writer, hull.exterior())?;
+    for interior in hull.interiors() {
+        write_concave_ring(writer, interior)?
+    }
+    Ok(())
+}
+
+fn write_concave_ring(
+    writer: &mut impl std::io::Write,
+    ring: impl LineStringTrait<T = f64>,
+) -> Result<()> {
+    write_wkb_polygon_ring_header(writer, ring.num_coords())
+        .map_err(|e| DataFusionError::Execution(e.to_string()))?;
+    ring.coords().rev().try_for_each(|coord| {
+        write_wkb_coord_trait(writer, &coord).map_err(|e| DataFusionError::Execution(e.to_string()))
+    })
+}
+
+#[cfg(test)]
+mod tests {
+    use arrow_schema::DataType;
+    use rstest::rstest;
+    use sedona_expr::scalar_udf::SedonaScalarUDF;
+    use sedona_schema::datatypes::SedonaType;
+    use sedona_schema::datatypes::WKB_VIEW_GEOMETRY;
+    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_concavehull", st_concavehull_impl());
+        let tester = ScalarUdfTester::new(
+            udf.into(),
+            vec![sedona_type.clone(), SedonaType::Arrow(DataType::Float64)],
+        );
+        assert_eq!(tester.return_type().unwrap(), WKB_GEOMETRY);
+
+        let result = tester
+            .invoke_scalar_scalar(
+                "GEOMETRYCOLLECTION (MULTIPOINT((1 1), (3 3)), POINT(5 6), LINESTRING(4 5, 5 6))",
+                0.1,
+            )
+            .unwrap();
+        tester.assert_scalar_result_equals(result, "POLYGON ((3 3, 1 1, 4 5, 5 6, 3 3))");

Review Comment:
   This has been helpful, but for MultiPolygons, PostGis returns a MultiPolygon after ST_ConcaveHull, the `geo` crate here returns a Polygon.
   ```sh
   actual WKB scalar:
     POLYGON((6 1,8 1,8 3,6 3,6 3,5 5,2 5,2 2,5 2,6 1))
   expected WKB scalar:
     MULTIPOLYGON(((5 2,6 3,8 3,8 1,6 1,5 2)),((2 5,5 5,5 2,2 2,2 5)))
     ```
     They tend to be topologically identical, but I'm guessing being different geometries is the reason why it's failing.
     
     I tried processing the Polygons in the Multipolygon individually, I get this
     ```sh
     actual WKB scalar:
     MULTIPOLYGON(((5 2,5 5,2 5,2 2,5 2)),((8 1,8 3,6 3,6 1,8 1)))
   expected WKB scalar:
     MULTIPOLYGON(((5 2,6 3,8 3,8 1,6 1,5 2)),((2 5,5 5,5 2,2 2,2 5)))
     ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] ST_ConcaveHull Implementation [sedona-db]

Posted by "Abeeujah (via GitHub)" <gi...@apache.org>.
Abeeujah commented on code in PR #431:
URL: https://github.com/apache/sedona-db/pull/431#discussion_r2611274553


##########
rust/sedona-geo/src/st_concavehull.rs:
##########
@@ -0,0 +1,270 @@
+// 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.
+
+#![allow(dead_code)]
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_common::ScalarValue;
+use datafusion_common::{
+    cast::{as_boolean_array, as_float64_array},
+    DataFusionError,
+};
+use datafusion_expr::ColumnarValue;
+use geo::{ConcaveHull, CoordsIter};
+use geo_traits::{GeometryCollectionTrait, GeometryTrait, PointTrait};
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_geometry::wkb_factory::{
+    write_wkb_coord_trait, write_wkb_empty_point, write_wkb_point_header, WKB_MIN_PROBABLE_BYTES,
+};
+use sedona_schema::datatypes::SedonaType;
+use sedona_schema::{datatypes::WKB_GEOMETRY, matchers::ArgMatcher};
+use wkb::writer::WriteOptions;
+
+use crate::to_geo::GeoTypesExecutor;
+
+/// ST_ConcaveHull implementation using [ConcaveHull]
+pub fn st_concavehull_impl() -> ScalarKernelRef {
+    Arc::new(STConcaveHull {})
+}
+
+#[derive(Debug)]
+struct STConcaveHull {}
+
+impl SedonaScalarKernel for STConcaveHull {
+    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> {
+        invoke_batch_impl(arg_types, args)
+    }

Review Comment:
   I was working on two kernels, one to accept the optional boolean parameter to allow holes and the other that uses the default `false` value for the allow holes parameter, that's why I had the `invoke_batch_impl` there.
   
   But this particular library wasn't actually supporting allow holes, so I'd just go ahead and inline here.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org