james-willis commented on code in PR #1027:
URL: https://github.com/apache/sedona-db/pull/1027#discussion_r3590125775


##########
rust/sedona-raster-functions/src/rs_values.rs:
##########
@@ -0,0 +1,956 @@
+// 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.
+
+//! `RS_Values` — sample a raster's pixel value at each point of a MultiPoint.
+//!
+//! ```text
+//! RS_Values(raster, points)        -> List<Double>  -- single-band rasters 
only
+//! RS_Values(raster, points, band)  -> List<Double>
+//! ```
+//!
+//! The plural companion of [`RS_Value`](crate::rs_value): where `RS_Value` 
takes
+//! one Point and returns one Double, `RS_Values` takes a MultiPoint (a single
+//! Point is also accepted) and returns a `List<Double>` — one element per
+//! sub-point, in input order. Each element is `NULL` when its sub-point is 
empty,
+//! out of bounds, or reads the band's nodata; the whole list is `NULL` when 
the
+//! raster, geometry, or band is `NULL`. An empty MultiPoint yields an empty 
list.
+//!
+//! Sampling, CRS handling, and pixel decoding are shared with `RS_Value` via
+//! [`crate::sampling`]; this module only adds the per-sub-point iteration and 
the
+//! list-shaped output.
+//!
+//! Like `RS_Value`, the function is tagged [`NEEDS_PIXELS_METADATA_KEY`] so 
the
+//! planner materialises the raster InDb before a kernel runs, and only 2-D
+//! rasters are supported.
+
+use std::sync::Arc;
+
+use arrow_array::builder::{Float64Builder, ListBuilder};
+use arrow_array::{Array, ArrayRef, StructArray};
+use arrow_schema::{DataType, Field};
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{exec_datafusion_err, exec_err, Result, ScalarValue};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{CoordTrait, GeometryTrait, GeometryType, MultiPointTrait, 
PointTrait};
+use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF};
+use sedona_proj::transform::with_global_proj_engine;
+use sedona_raster::affine_transformation::AffineMatrix;
+use sedona_raster::array::RasterStructArray;
+use sedona_raster::traits::{BandRef, NdBuffer, RasterRef};
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+use wkb::reader::read_wkb;
+
+use crate::crs_utils::resolve_crs;
+use crate::executor::RasterExecutor;
+use crate::rs_ensure_loaded::NEEDS_PIXELS_METADATA_KEY;
+use crate::sampling::{
+    column_reproject_decision, default_band, int32_array_arg, next_band, 
read_pixel, reproject_wkb,
+    xy_to_pixel,
+};
+
+/// The `List<Float64>` output type, matching what a default
+/// `ListBuilder<Float64Builder>` produces (field "item", nullable).
+fn list_float64_type() -> DataType {
+    DataType::List(Arc::new(Field::new("item", DataType::Float64, true)))
+}
+
+/// `RS_Values()` scalar UDF — sample pixel values at each point of a 
MultiPoint.
+pub fn rs_values_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_values",
+        vec![
+            Arc::new(RsValues { with_band: false }), // RS_Values(raster, 
points)
+            Arc::new(RsValues { with_band: true }),  // RS_Values(raster, 
points, band)
+        ],
+        Volatility::Immutable,
+    )
+    // The kernels read pixel bytes, so the raster argument must be 
materialised
+    // InDb first; the planner injects RS_EnsureLoaded based on this flag.
+    .with_metadata(NEEDS_PIXELS_METADATA_KEY, "true")
+}
+
+/// Kernel for `RS_Values(raster, points[, band])`.
+#[derive(Debug)]
+struct RsValues {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValues {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let mut matchers = vec![
+            ArgMatcher::is_raster(),
+            ArgMatcher::is_geometry_or_geography(),
+        ];
+        if self.with_band {
+            matchers.push(ArgMatcher::is_integer());
+        }
+        let matcher = ArgMatcher::new(matchers, 
SedonaType::Arrow(list_float64_type()));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        // Fast path: a constant (scalar) raster lets us resolve the affine
+        // transform, CRS, and band buffer once for the whole batch instead of
+        // per row — the common RS_Values(raster_expr, points_column[, band])
+        // shape. Only a band *column* falls back to per-row band resolution.
+        if let ColumnarValue::Scalar(ScalarValue::Struct(raster_struct)) = 
&args[0] {
+            return self.invoke_scalar_raster(arg_types, args, 
raster_struct.as_ref());
+        }
+
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut list_builder = ListBuilder::new(Float64Builder::new());
+        // Per-row scratch for the parsed sub-point coordinates, reused across
+        // rows so the parse does not allocate per row.
+        let mut points_scratch: Vec<Option<(f64, f64)>> = Vec::new();
+
+        // The optional band argument, materialised once as an Int32 array. 
Held
+        // as an `ArrayRef` so the typed view below borrows it instead of 
cloning
+        // the typed `Int32Array`.
+        let band_arr = if self.with_band {
+            Some(int32_array_arg(&args[2], num_iterations)?)
+        } else {
+            None
+        };
+        let band_array = band_arr.as_ref().map(|a| 
as_int32_array(a)).transpose()?;
+        let mut band_iter = band_array.map(|a| a.iter());
+
+        // Reprojecting the points into the raster CRS needs a PROJ engine.
+        with_global_proj_engine(|engine| {

Review Comment:
   done



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to