You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@sedona.apache.org by "james-willis (via GitHub)" <gi...@apache.org> on 2026/06/17 21:03:30 UTC

[PR] feat(rust/sedona-raster-functions): add RS_Value [sedona-db]

james-willis opened a new pull request, #974:
URL: https://github.com/apache/sedona-db/pull/974

   (no comment)


-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double
+//! ```
+//!
+//! Returns the value of the pixel that contains the point (no resampling), or
+//! the value at the given 1-based grid cell. The result is `NULL` when the
+//! raster/arguments are null, the point/cell is out of bounds, or the value
+//! equals the band's nodata.
+//!
+//! The function is tagged [`NEEDS_PIXELS_METADATA_KEY`], so the planner wraps
+//! its raster argument in `RS_EnsureLoaded`; by the time a kernel runs the band
+//! bytes are materialised InDb and a value is read directly from the band's
+//! [`NdBuffer`](sedona_raster::traits::NdBuffer) — no GDAL involved. Only 2-D
+//! rasters are supported; a band with extra (non-spatial) dimensions errors.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{exec_datafusion_err, exec_err, DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{CoordTrait, GeometryTrait, GeometryType, 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::traits::{nodata_bytes_to_f64_lossless, RasterRef};
+use sedona_schema::crs::CrsRef;
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+use wkb::reader::read_wkb;
+
+use crate::crs_utils::{crs_transform_wkb, resolve_crs};
+use crate::executor::RasterExecutor;
+use crate::rs_ensure_loaded::NEEDS_PIXELS_METADATA_KEY;
+
+/// `RS_Value()` scalar UDF — sample a pixel value at a point or grid cell.
+pub fn rs_value_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_value",
+        vec![
+            Arc::new(RsValuePoint { with_band: false }), // RS_Value(raster, point)
+            Arc::new(RsValuePoint { with_band: true }),  // RS_Value(raster, point, band)
+            Arc::new(RsValueGrid { with_band: false }),  // RS_Value(raster, colX, rowY)
+            Arc::new(RsValueGrid { with_band: true }),   // RS_Value(raster, colX, rowY, 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_Value(raster, point[, band])`.
+#[derive(Debug)]
+struct RsValuePoint {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValuePoint {
+    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(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        // The optional band argument, materialised once as an Int32 array.
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[2]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        // Reprojecting the point into the raster CRS needs a PROJ engine.
+        with_global_proj_engine(|engine| {
+            executor.execute_raster_wkb_crs_void(|raster_opt, wkb_opt, point_crs| {
+                let (raster, point_wkb, band_num) =
+                    match (raster_opt, wkb_opt, next_band(&mut band_iter)) {
+                        (Some(raster), Some(point_wkb), Some(band_num)) => {
+                            (raster, point_wkb, band_num)
+                        }
+                        _ => {
+                            builder.append_null();
+                            return Ok(());
+                        }
+                    };
+
+                // Bring the point into the raster's CRS. A reprojection only
+                // happens when both sides carry a (differing) CRS; otherwise
+                // the original WKB is sampled directly.
+                let raster_crs = resolve_crs(raster.crs())?;
+                let reprojected =
+                    reproject_point(point_wkb, point_crs, raster_crs.as_deref(), engine)?;
+                let wkb = reprojected.as_deref().unwrap_or(point_wkb);
+
+                let (x, y) = read_point_xy(wkb)?;
+                // Floor (not truncate toward zero) so a point just outside the
+                // top/left edge maps to a negative index and is rejected as out
+                // of bounds, rather than truncating to 0 and sampling an edge pixel.
+                let (raster_x, raster_y) = AffineMatrix::from_metadata(&raster.metadata())
+                    .inv_transform(x, y)
+                    .map_err(|e| exec_datafusion_err!("RS_Value: {e}"))?;
+                let (col, row) = (raster_x.floor() as i64, raster_y.floor() as i64);
+
+                match sample_pixel(raster, col, row, band_num)? {
+                    Some(value) => builder.append_value(value),
+                    None => builder.append_null(),
+                }
+                Ok(())
+            })
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Kernel for `RS_Value(raster, colX, rowY[, band])` with **1-based** grid
+/// coordinates.
+#[derive(Debug)]
+struct RsValueGrid {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValueGrid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let mut matchers = vec![
+            ArgMatcher::is_raster(),
+            ArgMatcher::is_integer(),
+            ArgMatcher::is_integer(),
+        ];
+        if self.with_band {
+            matchers.push(ArgMatcher::is_integer());
+        }
+        let matcher = ArgMatcher::new(matchers, SedonaType::Arrow(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        let col_array = as_int32_array(
+            &args[1]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();
+        let row_array = as_int32_array(
+            &args[2]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[3]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+
+        let mut col_iter = col_array.iter();
+        let mut row_iter = row_array.iter();
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        executor.execute_raster_void(|_, raster_opt| {
+            let col = col_iter.next().flatten();
+            let row = row_iter.next().flatten();
+            let band_num = next_band(&mut band_iter);
+
+            match (raster_opt, col, row, band_num) {
+                (Some(raster), Some(col), Some(row), Some(band_num)) => {
+                    // 1-based grid coordinates -> 0-based pixel indices.
+                    match sample_pixel(raster, col as i64 - 1, row as i64 - 1, band_num)? {
+                        Some(value) => builder.append_value(value),
+                        None => builder.append_null(),
+                    }
+                }
+                _ => builder.append_null(),
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Advance the optional band-number iterator one row, yielding the 1-based band
+/// to sample. A missing band argument defaults to band 1; a NULL band element
+/// returns `None`, which the caller propagates to a NULL result. Band 0 and
+/// negative values map to 0 so [`Bands::band`](sedona_raster::traits::Bands::band)
+/// rejects them as not 1-based rather than being silently coerced.
+fn next_band(
+    band_iter: &mut Option<arrow_array::iterator::ArrayIter<&arrow_array::Int32Array>>,
+) -> Option<usize> {
+    match band_iter.as_mut() {
+        None => Some(1),
+        Some(iter) => iter.next().flatten().map(|b| b.max(0) as usize),
+    }
+}
+
+/// Reproject `point_wkb` from its CRS into the raster CRS, returning the
+/// transformed WKB only when a reprojection actually happened (so the caller
+/// can sample the original bytes otherwise — no allocation in the common case).
+///
+/// Errors if exactly one of the point / raster carries a CRS: sampling across a
+/// known and an unknown CRS would silently mislocate the point.
+fn reproject_point(
+    point_wkb: &[u8],
+    point_crs: CrsRef<'_>,
+    raster_crs: CrsRef<'_>,
+    engine: &dyn sedona_geometry::transform::CrsEngine,
+) -> Result<Option<Vec<u8>>> {
+    match (point_crs, raster_crs) {
+        (Some(point_crs), Some(raster_crs)) => {
+            if point_crs.crs_equals(raster_crs) {
+                Ok(None)
+            } else {
+                Ok(Some(crs_transform_wkb(
+                    point_wkb, point_crs, raster_crs, engine,
+                )?))
+            }
+        }
+        (None, None) => Ok(None),
+        (Some(_), None) => {
+            exec_err!("RS_Value: point has a CRS but the raster does not")
+        }
+        (None, Some(_)) => {
+            exec_err!("RS_Value: raster has a CRS but the point does not")
+        }
+    }
+}
+
+/// Read the (x, y) coordinates of a WKB Point geometry.
+fn read_point_xy(wkb: &[u8]) -> Result<(f64, f64)> {
+    let geom = read_wkb(wkb).map_err(|e| DataFusionError::External(Box::new(e)))?;
+    match geom.as_type() {

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: issues-unsubscribe@sedona.apache.org

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


Re: [PR] feat(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double
+//! ```
+//!
+//! Returns the value of the pixel that contains the point (no resampling), or
+//! the value at the given 1-based grid cell. The result is `NULL` when the
+//! raster/arguments are null, the point/cell is out of bounds, or the value
+//! equals the band's nodata.
+//!
+//! The function is tagged [`NEEDS_PIXELS_METADATA_KEY`], so the planner wraps
+//! its raster argument in `RS_EnsureLoaded`; by the time a kernel runs the band
+//! bytes are materialised InDb and a value is read directly from the band's
+//! [`NdBuffer`](sedona_raster::traits::NdBuffer) — no GDAL involved. Only 2-D
+//! rasters are supported; a band with extra (non-spatial) dimensions errors.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{exec_datafusion_err, exec_err, DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{CoordTrait, GeometryTrait, GeometryType, 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::traits::{nodata_bytes_to_f64_lossless, RasterRef};
+use sedona_schema::crs::CrsRef;
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+use wkb::reader::read_wkb;
+
+use crate::crs_utils::{crs_transform_wkb, resolve_crs};
+use crate::executor::RasterExecutor;
+use crate::rs_ensure_loaded::NEEDS_PIXELS_METADATA_KEY;
+
+/// `RS_Value()` scalar UDF — sample a pixel value at a point or grid cell.
+pub fn rs_value_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_value",
+        vec![
+            Arc::new(RsValuePoint { with_band: false }), // RS_Value(raster, point)
+            Arc::new(RsValuePoint { with_band: true }),  // RS_Value(raster, point, band)
+            Arc::new(RsValueGrid { with_band: false }),  // RS_Value(raster, colX, rowY)
+            Arc::new(RsValueGrid { with_band: true }),   // RS_Value(raster, colX, rowY, 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_Value(raster, point[, band])`.
+#[derive(Debug)]
+struct RsValuePoint {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValuePoint {
+    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(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        // The optional band argument, materialised once as an Int32 array.
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[2]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        // Reprojecting the point into the raster CRS needs a PROJ engine.
+        with_global_proj_engine(|engine| {
+            executor.execute_raster_wkb_crs_void(|raster_opt, wkb_opt, point_crs| {
+                let (raster, point_wkb, band_num) =
+                    match (raster_opt, wkb_opt, next_band(&mut band_iter)) {
+                        (Some(raster), Some(point_wkb), Some(band_num)) => {
+                            (raster, point_wkb, band_num)
+                        }
+                        _ => {
+                            builder.append_null();
+                            return Ok(());
+                        }
+                    };
+
+                // Bring the point into the raster's CRS. A reprojection only
+                // happens when both sides carry a (differing) CRS; otherwise
+                // the original WKB is sampled directly.
+                let raster_crs = resolve_crs(raster.crs())?;
+                let reprojected =
+                    reproject_point(point_wkb, point_crs, raster_crs.as_deref(), engine)?;
+                let wkb = reprojected.as_deref().unwrap_or(point_wkb);
+
+                let (x, y) = read_point_xy(wkb)?;
+                // Floor (not truncate toward zero) so a point just outside the
+                // top/left edge maps to a negative index and is rejected as out
+                // of bounds, rather than truncating to 0 and sampling an edge pixel.
+                let (raster_x, raster_y) = AffineMatrix::from_metadata(&raster.metadata())
+                    .inv_transform(x, y)
+                    .map_err(|e| exec_datafusion_err!("RS_Value: {e}"))?;
+                let (col, row) = (raster_x.floor() as i64, raster_y.floor() as i64);
+
+                match sample_pixel(raster, col, row, band_num)? {
+                    Some(value) => builder.append_value(value),
+                    None => builder.append_null(),
+                }
+                Ok(())
+            })
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Kernel for `RS_Value(raster, colX, rowY[, band])` with **1-based** grid
+/// coordinates.
+#[derive(Debug)]
+struct RsValueGrid {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValueGrid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let mut matchers = vec![
+            ArgMatcher::is_raster(),
+            ArgMatcher::is_integer(),
+            ArgMatcher::is_integer(),
+        ];
+        if self.with_band {
+            matchers.push(ArgMatcher::is_integer());
+        }
+        let matcher = ArgMatcher::new(matchers, SedonaType::Arrow(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        let col_array = as_int32_array(
+            &args[1]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();
+        let row_array = as_int32_array(
+            &args[2]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[3]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+
+        let mut col_iter = col_array.iter();
+        let mut row_iter = row_array.iter();
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        executor.execute_raster_void(|_, raster_opt| {
+            let col = col_iter.next().flatten();
+            let row = row_iter.next().flatten();
+            let band_num = next_band(&mut band_iter);
+
+            match (raster_opt, col, row, band_num) {
+                (Some(raster), Some(col), Some(row), Some(band_num)) => {
+                    // 1-based grid coordinates -> 0-based pixel indices.
+                    match sample_pixel(raster, col as i64 - 1, row as i64 - 1, band_num)? {
+                        Some(value) => builder.append_value(value),
+                        None => builder.append_null(),
+                    }
+                }
+                _ => builder.append_null(),
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Advance the optional band-number iterator one row, yielding the 1-based band
+/// to sample. A missing band argument defaults to band 1; a NULL band element
+/// returns `None`, which the caller propagates to a NULL result. Band 0 and
+/// negative values map to 0 so [`Bands::band`](sedona_raster::traits::Bands::band)
+/// rejects them as not 1-based rather than being silently coerced.
+fn next_band(
+    band_iter: &mut Option<arrow_array::iterator::ArrayIter<&arrow_array::Int32Array>>,
+) -> Option<usize> {
+    match band_iter.as_mut() {
+        None => Some(1),
+        Some(iter) => iter.next().flatten().map(|b| b.max(0) as usize),
+    }
+}
+
+/// Reproject `point_wkb` from its CRS into the raster CRS, returning the
+/// transformed WKB only when a reprojection actually happened (so the caller
+/// can sample the original bytes otherwise — no allocation in the common case).
+///
+/// Errors if exactly one of the point / raster carries a CRS: sampling across a
+/// known and an unknown CRS would silently mislocate the point.
+fn reproject_point(
+    point_wkb: &[u8],
+    point_crs: CrsRef<'_>,
+    raster_crs: CrsRef<'_>,
+    engine: &dyn sedona_geometry::transform::CrsEngine,
+) -> Result<Option<Vec<u8>>> {
+    match (point_crs, raster_crs) {
+        (Some(point_crs), Some(raster_crs)) => {
+            if point_crs.crs_equals(raster_crs) {
+                Ok(None)
+            } else {
+                Ok(Some(crs_transform_wkb(
+                    point_wkb, point_crs, raster_crs, engine,
+                )?))
+            }
+        }
+        (None, None) => Ok(None),
+        (Some(_), None) => {
+            exec_err!("RS_Value: point has a CRS but the raster does not")
+        }
+        (None, Some(_)) => {
+            exec_err!("RS_Value: raster has a CRS but the point does not")
+        }
+    }
+}
+
+/// Read the (x, y) coordinates of a WKB Point geometry.
+fn read_point_xy(wkb: &[u8]) -> Result<(f64, f64)> {
+    let geom = read_wkb(wkb).map_err(|e| DataFusionError::External(Box::new(e)))?;
+    match geom.as_type() {

Review Comment:
   I went with c to build the point-optimized parser. I thought the perf gains were worth it: 50% e2e on the Scalar Raster case:
   
   ```
     ┌──────────────────────────────┬────────────────────────┐
     │             case             │         change         │
     ├──────────────────────────────┼────────────────────────┤
     │ ScalarArray (primary target) │ −56% (≈10.6 → 4.66 ms) │
     ├──────────────────────────────┼────────────────────────┤
     │ ArrayArray                   │ −11.7%                 │
     ├──────────────────────────────┼────────────────────────┤
     │ ArrayArrayScalar             │ −12.2%                 │
     └──────────────────────────────┴────────────────────────┘
   ```



-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double
+//! ```
+//!
+//! Returns the value of the pixel that contains the point (no resampling), or
+//! the value at the given 1-based grid cell. The result is `NULL` when the
+//! raster/arguments are null, the point/cell is out of bounds, or the value
+//! equals the band's nodata.
+//!
+//! The function is tagged [`NEEDS_PIXELS_METADATA_KEY`], so the planner wraps
+//! its raster argument in `RS_EnsureLoaded`; by the time a kernel runs the band
+//! bytes are materialised InDb and a value is read directly from the band's
+//! [`NdBuffer`](sedona_raster::traits::NdBuffer) — no GDAL involved. Only 2-D
+//! rasters are supported; a band with extra (non-spatial) dimensions errors.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{exec_datafusion_err, exec_err, DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{CoordTrait, GeometryTrait, GeometryType, 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::traits::{nodata_bytes_to_f64_lossless, RasterRef};
+use sedona_schema::crs::CrsRef;
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+use wkb::reader::read_wkb;
+
+use crate::crs_utils::{crs_transform_wkb, resolve_crs};
+use crate::executor::RasterExecutor;
+use crate::rs_ensure_loaded::NEEDS_PIXELS_METADATA_KEY;
+
+/// `RS_Value()` scalar UDF — sample a pixel value at a point or grid cell.
+pub fn rs_value_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_value",
+        vec![
+            Arc::new(RsValuePoint { with_band: false }), // RS_Value(raster, point)
+            Arc::new(RsValuePoint { with_band: true }),  // RS_Value(raster, point, band)
+            Arc::new(RsValueGrid { with_band: false }),  // RS_Value(raster, colX, rowY)
+            Arc::new(RsValueGrid { with_band: true }),   // RS_Value(raster, colX, rowY, 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_Value(raster, point[, band])`.
+#[derive(Debug)]
+struct RsValuePoint {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValuePoint {
+    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(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        // The optional band argument, materialised once as an Int32 array.
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[2]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        // Reprojecting the point into the raster CRS needs a PROJ engine.
+        with_global_proj_engine(|engine| {
+            executor.execute_raster_wkb_crs_void(|raster_opt, wkb_opt, point_crs| {
+                let (raster, point_wkb, band_num) =
+                    match (raster_opt, wkb_opt, next_band(&mut band_iter)) {
+                        (Some(raster), Some(point_wkb), Some(band_num)) => {
+                            (raster, point_wkb, band_num)
+                        }
+                        _ => {
+                            builder.append_null();
+                            return Ok(());
+                        }
+                    };
+
+                // Bring the point into the raster's CRS. A reprojection only
+                // happens when both sides carry a (differing) CRS; otherwise
+                // the original WKB is sampled directly.
+                let raster_crs = resolve_crs(raster.crs())?;
+                let reprojected =
+                    reproject_point(point_wkb, point_crs, raster_crs.as_deref(), engine)?;
+                let wkb = reprojected.as_deref().unwrap_or(point_wkb);
+
+                let (x, y) = read_point_xy(wkb)?;
+                // Floor (not truncate toward zero) so a point just outside the
+                // top/left edge maps to a negative index and is rejected as out
+                // of bounds, rather than truncating to 0 and sampling an edge pixel.
+                let (raster_x, raster_y) = AffineMatrix::from_metadata(&raster.metadata())
+                    .inv_transform(x, y)
+                    .map_err(|e| exec_datafusion_err!("RS_Value: {e}"))?;
+                let (col, row) = (raster_x.floor() as i64, raster_y.floor() as i64);
+
+                match sample_pixel(raster, col, row, band_num)? {
+                    Some(value) => builder.append_value(value),
+                    None => builder.append_null(),
+                }
+                Ok(())
+            })
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Kernel for `RS_Value(raster, colX, rowY[, band])` with **1-based** grid
+/// coordinates.
+#[derive(Debug)]
+struct RsValueGrid {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValueGrid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let mut matchers = vec![
+            ArgMatcher::is_raster(),
+            ArgMatcher::is_integer(),
+            ArgMatcher::is_integer(),
+        ];
+        if self.with_band {
+            matchers.push(ArgMatcher::is_integer());
+        }
+        let matcher = ArgMatcher::new(matchers, SedonaType::Arrow(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        let col_array = as_int32_array(
+            &args[1]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();
+        let row_array = as_int32_array(
+            &args[2]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[3]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+
+        let mut col_iter = col_array.iter();
+        let mut row_iter = row_array.iter();
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        executor.execute_raster_void(|_, raster_opt| {
+            let col = col_iter.next().flatten();
+            let row = row_iter.next().flatten();
+            let band_num = next_band(&mut band_iter);
+
+            match (raster_opt, col, row, band_num) {
+                (Some(raster), Some(col), Some(row), Some(band_num)) => {
+                    // 1-based grid coordinates -> 0-based pixel indices.
+                    match sample_pixel(raster, col as i64 - 1, row as i64 - 1, band_num)? {
+                        Some(value) => builder.append_value(value),
+                        None => builder.append_null(),
+                    }
+                }
+                _ => builder.append_null(),
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Advance the optional band-number iterator one row, yielding the 1-based band
+/// to sample. A missing band argument defaults to band 1; a NULL band element
+/// returns `None`, which the caller propagates to a NULL result. Band 0 and
+/// negative values map to 0 so [`Bands::band`](sedona_raster::traits::Bands::band)
+/// rejects them as not 1-based rather than being silently coerced.
+fn next_band(
+    band_iter: &mut Option<arrow_array::iterator::ArrayIter<&arrow_array::Int32Array>>,
+) -> Option<usize> {
+    match band_iter.as_mut() {
+        None => Some(1),
+        Some(iter) => iter.next().flatten().map(|b| b.max(0) as usize),
+    }
+}
+
+/// Reproject `point_wkb` from its CRS into the raster CRS, returning the
+/// transformed WKB only when a reprojection actually happened (so the caller
+/// can sample the original bytes otherwise — no allocation in the common case).
+///
+/// Errors if exactly one of the point / raster carries a CRS: sampling across a
+/// known and an unknown CRS would silently mislocate the point.
+fn reproject_point(
+    point_wkb: &[u8],
+    point_crs: CrsRef<'_>,
+    raster_crs: CrsRef<'_>,
+    engine: &dyn sedona_geometry::transform::CrsEngine,
+) -> Result<Option<Vec<u8>>> {
+    match (point_crs, raster_crs) {
+        (Some(point_crs), Some(raster_crs)) => {
+            if point_crs.crs_equals(raster_crs) {
+                Ok(None)
+            } else {
+                Ok(Some(crs_transform_wkb(
+                    point_wkb, point_crs, raster_crs, engine,
+                )?))
+            }
+        }
+        (None, None) => Ok(None),
+        (Some(_), None) => {
+            exec_err!("RS_Value: point has a CRS but the raster does not")
+        }
+        (None, Some(_)) => {
+            exec_err!("RS_Value: raster has a CRS but the point does not")
+        }

Review Comment:
   is erroring the right behavior or should we assume that they match?



-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
docs/reference/sql/rs_value.qmd:
##########
@@ -0,0 +1,85 @@
+---
+# 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.
+
+title: RS_Value
+description: >
+  Returns the value of a single raster pixel as a double, selected either by a
+  point geometry or by 1-based grid coordinates. Returns null if the location is
+  outside the raster or the pixel holds the band's nodata value.
+kernels:
+  - returns: float64
+    args:
+    - raster
+    - name: point
+      type: geometry
+      description: >
+        The pixel that contains this point is sampled (no resampling).
+        Reprojected into the raster CRS when both carry one.
+  - returns: float64
+    args:
+    - raster
+    - name: point
+      type: geometry
+    - name: band
+      type: int
+      description: Band index (1-based). Defaults to 1 if not specified.
+  - returns: float64
+    args:
+    - raster
+    - name: colX
+      type: int
+      description: Column index (1-based).
+    - name: rowY
+      type: int
+      description: Row index (1-based).

Review Comment:
   But the signature here is based on trying to match postgis as much as possible:
   
   > Here are PostGIS's ST_Value (raster) signatures, straight from the current docs:
   >  * ST_Value(raster rast, geometry pt, boolean exclude_nodata_value=true)
   >  * ST_Value(raster rast, integer band, geometry pt, boolean exclude_nodata_value=true, text
   >           resample='nearest')
   >  * ST_Value(raster rast, integer x, integer y, boolean exclude_nodata_value=true)
   >  * ST_Value(raster rast, integer band, integer x, integer y, boolean exclude_nodata_value=true)



-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
docs/reference/sql/rs_value.qmd:
##########
@@ -0,0 +1,85 @@
+---
+# 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.
+
+title: RS_Value
+description: >
+  Returns the value of a single raster pixel as a double, selected either by a
+  point geometry or by 1-based grid coordinates. Returns null if the location is
+  outside the raster or the pixel holds the band's nodata value.
+kernels:
+  - returns: float64
+    args:
+    - raster
+    - name: point
+      type: geometry
+      description: >
+        The pixel that contains this point is sampled (no resampling).
+        Reprojected into the raster CRS when both carry one.
+  - returns: float64
+    args:
+    - raster
+    - name: point
+      type: geometry
+    - name: band
+      type: int
+      description: Band index (1-based). Defaults to 1 if not specified.
+  - returns: float64
+    args:
+    - raster
+    - name: colX
+      type: int
+      description: Column index (1-based).
+    - name: rowY
+      type: int
+      description: Row index (1-based).

Review Comment:
   punted the col/row version of the function for now



-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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

   > My inclination is to punt on the optimization work in order to add functionality. Also will eventually add a benchmark for these functions
   
   I think you should benchmark them now and put in a reasonable effort to optimize them now...we know we need this function to be fast and it will never be easier to get both of our eyes on it. The patterns you come up with for this function will help you with all of the other functions that come after.


-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double
+//! ```
+//!
+//! Returns the value of the pixel that contains the point (no resampling), or
+//! the value at the given 1-based grid cell. The result is `NULL` when the
+//! raster/arguments are null, the point/cell is out of bounds, or the value
+//! equals the band's nodata.
+//!
+//! The function is tagged [`NEEDS_PIXELS_METADATA_KEY`], so the planner wraps
+//! its raster argument in `RS_EnsureLoaded`; by the time a kernel runs the band
+//! bytes are materialised InDb and a value is read directly from the band's
+//! [`NdBuffer`](sedona_raster::traits::NdBuffer) — no GDAL involved. Only 2-D
+//! rasters are supported; a band with extra (non-spatial) dimensions errors.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{exec_datafusion_err, exec_err, DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{CoordTrait, GeometryTrait, GeometryType, 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::traits::{nodata_bytes_to_f64_lossless, RasterRef};
+use sedona_schema::crs::CrsRef;
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+use wkb::reader::read_wkb;
+
+use crate::crs_utils::{crs_transform_wkb, resolve_crs};
+use crate::executor::RasterExecutor;
+use crate::rs_ensure_loaded::NEEDS_PIXELS_METADATA_KEY;
+
+/// `RS_Value()` scalar UDF — sample a pixel value at a point or grid cell.
+pub fn rs_value_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_value",
+        vec![
+            Arc::new(RsValuePoint { with_band: false }), // RS_Value(raster, point)
+            Arc::new(RsValuePoint { with_band: true }),  // RS_Value(raster, point, band)
+            Arc::new(RsValueGrid { with_band: false }),  // RS_Value(raster, colX, rowY)
+            Arc::new(RsValueGrid { with_band: true }),   // RS_Value(raster, colX, rowY, 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_Value(raster, point[, band])`.
+#[derive(Debug)]
+struct RsValuePoint {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValuePoint {
+    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(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        // The optional band argument, materialised once as an Int32 array.
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[2]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        // Reprojecting the point into the raster CRS needs a PROJ engine.
+        with_global_proj_engine(|engine| {
+            executor.execute_raster_wkb_crs_void(|raster_opt, wkb_opt, point_crs| {
+                let (raster, point_wkb, band_num) =
+                    match (raster_opt, wkb_opt, next_band(&mut band_iter)) {
+                        (Some(raster), Some(point_wkb), Some(band_num)) => {
+                            (raster, point_wkb, band_num)
+                        }
+                        _ => {
+                            builder.append_null();
+                            return Ok(());
+                        }
+                    };
+
+                // Bring the point into the raster's CRS. A reprojection only
+                // happens when both sides carry a (differing) CRS; otherwise
+                // the original WKB is sampled directly.
+                let raster_crs = resolve_crs(raster.crs())?;
+                let reprojected =
+                    reproject_point(point_wkb, point_crs, raster_crs.as_deref(), engine)?;
+                let wkb = reprojected.as_deref().unwrap_or(point_wkb);
+
+                let (x, y) = read_point_xy(wkb)?;
+                // Floor (not truncate toward zero) so a point just outside the
+                // top/left edge maps to a negative index and is rejected as out
+                // of bounds, rather than truncating to 0 and sampling an edge pixel.
+                let (raster_x, raster_y) = AffineMatrix::from_metadata(&raster.metadata())
+                    .inv_transform(x, y)
+                    .map_err(|e| exec_datafusion_err!("RS_Value: {e}"))?;
+                let (col, row) = (raster_x.floor() as i64, raster_y.floor() as i64);
+
+                match sample_pixel(raster, col, row, band_num)? {
+                    Some(value) => builder.append_value(value),
+                    None => builder.append_null(),
+                }
+                Ok(())
+            })
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Kernel for `RS_Value(raster, colX, rowY[, band])` with **1-based** grid
+/// coordinates.
+#[derive(Debug)]
+struct RsValueGrid {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValueGrid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let mut matchers = vec![
+            ArgMatcher::is_raster(),
+            ArgMatcher::is_integer(),
+            ArgMatcher::is_integer(),
+        ];
+        if self.with_band {
+            matchers.push(ArgMatcher::is_integer());
+        }
+        let matcher = ArgMatcher::new(matchers, SedonaType::Arrow(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        let col_array = as_int32_array(
+            &args[1]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();

Review Comment:
   refactored a bit to avoid the allocation



-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
python/sedonadb/tests/functions/test_raster_functions.py:
##########
@@ -98,3 +98,36 @@ def test_rs_ensureloaded(con, sedona_testing):
     assert arr.shape == (512, 512)
     assert arr.dtype == "uint16"
     assert arr[0, 0] == 2324
+
+
+# Point sampling. RS_Example fills band `b` with the constant value `b`, except
+# the top-left pixel which is set to the nodata value (127). (74.58, 110.57) is
+# the centroid of pixel (10, 10) (0-based) in the raster's OGC:CRS84 space; the
+# point and raster share a CRS so no reprojection happens. A point far outside
+# the footprint yields NULL. (The `needs_pixels` -> RS_EnsureLoaded planner path
+# is covered against a real OutDb raster by `test_rs_ensureloaded`.)
+@pytest.mark.parametrize(

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: issues-unsubscribe@sedona.apache.org

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


Re: [PR] feat(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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

   I spent a few hours doing benchmarking/profiling. I found that branch elimination did basically nothing. The big gains were in the Scalar raster case hoist and the use of a point-specific wkb parser.


-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
rust/sedona-geometry/src/wkb_header.rs:
##########
@@ -1059,4 +1130,102 @@ mod tests {
         let header = WkbHeader::try_new(&wkb).unwrap();
         assert!(header.is_empty().unwrap());
     }
+
+    #[test]
+    fn read_point_xy_iso_little_endian() {
+        // 2-D / 3-D / 4-D ISO points all expose the same leading (x, y), and the
+        // result must agree with the general parser's `first_xy`.
+        for wkt_value in [
+            "POINT (1 2)",
+            "POINT Z (1 2 3)",
+            "POINT M (1 2 3)",
+            "POINT ZM (1 2 3 4)",
+        ] {
+            let wkb = make_wkb(wkt_value);
+            assert_eq!(
+                read_point_xy(&wkb).unwrap(),
+                Some((1.0, 2.0)),
+                "{wkt_value}"
+            );
+            assert_eq!(
+                read_point_xy(&wkb).unwrap(),
+                Some(WkbHeader::try_new(&wkb).unwrap().first_xy()),
+                "disagrees with first_xy for {wkt_value}"
+            );
+        }
+    }
+
+    #[test]
+    fn read_point_xy_big_endian() {
+        // Byte order 0x00, type 1 (BE), x = 1.0, y = 2.0 — all big-endian.
+        let wkb: [u8; 21] = [
+            0x00, // big-endian
+            0x00, 0x00, 0x00, 0x01, // type code 1 (Point)
+            0x3F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // x = 1.0
+            0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // y = 2.0
+        ];
+        assert_eq!(read_point_xy(&wkb).unwrap(), Some((1.0, 2.0)));
+    }
+
+    #[test]
+    fn read_point_xy_ewkb_with_srid() {
+        use sedona_testing::fixtures::*;

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: issues-unsubscribe@sedona.apache.org

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


Re: [PR] feat(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double
+//! ```
+//!
+//! Returns the value of the pixel that contains the point (no resampling), or
+//! the value at the given 1-based grid cell. The result is `NULL` when the
+//! raster/arguments are null, the point/cell is out of bounds, or the value
+//! equals the band's nodata.
+//!
+//! The function is tagged [`NEEDS_PIXELS_METADATA_KEY`], so the planner wraps
+//! its raster argument in `RS_EnsureLoaded`; by the time a kernel runs the band
+//! bytes are materialised InDb and a value is read directly from the band's
+//! [`NdBuffer`](sedona_raster::traits::NdBuffer) — no GDAL involved. Only 2-D
+//! rasters are supported; a band with extra (non-spatial) dimensions errors.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{exec_datafusion_err, exec_err, DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{CoordTrait, GeometryTrait, GeometryType, 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::traits::{nodata_bytes_to_f64_lossless, RasterRef};
+use sedona_schema::crs::CrsRef;
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+use wkb::reader::read_wkb;
+
+use crate::crs_utils::{crs_transform_wkb, resolve_crs};
+use crate::executor::RasterExecutor;
+use crate::rs_ensure_loaded::NEEDS_PIXELS_METADATA_KEY;
+
+/// `RS_Value()` scalar UDF — sample a pixel value at a point or grid cell.
+pub fn rs_value_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_value",
+        vec![
+            Arc::new(RsValuePoint { with_band: false }), // RS_Value(raster, point)
+            Arc::new(RsValuePoint { with_band: true }),  // RS_Value(raster, point, band)
+            Arc::new(RsValueGrid { with_band: false }),  // RS_Value(raster, colX, rowY)
+            Arc::new(RsValueGrid { with_band: true }),   // RS_Value(raster, colX, rowY, 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_Value(raster, point[, band])`.
+#[derive(Debug)]
+struct RsValuePoint {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValuePoint {
+    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(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        // The optional band argument, materialised once as an Int32 array.
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[2]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        // Reprojecting the point into the raster CRS needs a PROJ engine.
+        with_global_proj_engine(|engine| {
+            executor.execute_raster_wkb_crs_void(|raster_opt, wkb_opt, point_crs| {
+                let (raster, point_wkb, band_num) =
+                    match (raster_opt, wkb_opt, next_band(&mut band_iter)) {
+                        (Some(raster), Some(point_wkb), Some(band_num)) => {
+                            (raster, point_wkb, band_num)
+                        }
+                        _ => {
+                            builder.append_null();
+                            return Ok(());
+                        }
+                    };
+
+                // Bring the point into the raster's CRS. A reprojection only
+                // happens when both sides carry a (differing) CRS; otherwise
+                // the original WKB is sampled directly.
+                let raster_crs = resolve_crs(raster.crs())?;
+                let reprojected =
+                    reproject_point(point_wkb, point_crs, raster_crs.as_deref(), engine)?;
+                let wkb = reprojected.as_deref().unwrap_or(point_wkb);
+
+                let (x, y) = read_point_xy(wkb)?;
+                // Floor (not truncate toward zero) so a point just outside the
+                // top/left edge maps to a negative index and is rejected as out
+                // of bounds, rather than truncating to 0 and sampling an edge pixel.
+                let (raster_x, raster_y) = AffineMatrix::from_metadata(&raster.metadata())
+                    .inv_transform(x, y)
+                    .map_err(|e| exec_datafusion_err!("RS_Value: {e}"))?;
+                let (col, row) = (raster_x.floor() as i64, raster_y.floor() as i64);

Review Comment:
   POINT EMPTY should now just return null



-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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

   My inclination is to punt on the optimization work in order to add functionality. Also will eventually add a benchmark for these functions


-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
docs/reference/sql/rs_value.qmd:
##########
@@ -0,0 +1,85 @@
+---
+# 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.
+
+title: RS_Value
+description: >
+  Returns the value of a single raster pixel as a double, selected either by a
+  point geometry or by 1-based grid coordinates. Returns null if the location is
+  outside the raster or the pixel holds the band's nodata value.
+kernels:
+  - returns: float64
+    args:
+    - raster
+    - name: point
+      type: geometry
+      description: >
+        The pixel that contains this point is sampled (no resampling).
+        Reprojected into the raster CRS when both carry one.
+  - returns: float64
+    args:
+    - raster
+    - name: point
+      type: geometry
+    - name: band
+      type: int
+      description: Band index (1-based). Defaults to 1 if not specified.
+  - returns: float64
+    args:
+    - raster
+    - name: colX
+      type: int
+      description: Column index (1-based).
+    - name: rowY
+      type: int
+      description: Row index (1-based).
+  - returns: float64
+    args:
+    - raster
+    - name: colX
+      type: int
+    - name: rowY
+      type: int
+    - name: band
+      type: int
+      description: Band index (1-based). Defaults to 1 if not specified.
+---
+
+## Description
+
+`RS_Value` samples one pixel of a raster. The location is given either as a
+point geometry — the value of the pixel that contains the point is returned, with
+no interpolation — or as 1-based `(colX, rowY)` grid coordinates. The band
+defaults to 1.
+
+The result is `NULL` when the point or grid cell falls outside the raster, or
+when the sampled pixel equals the band's nodata value. Only 2-D rasters are
+supported.
+
+## Examples
+
+```sql
+SELECT RS_Value(RS_Example(), 2, 1);
+```
+
+```sql
+SELECT RS_Value(RS_Example(), 2, 1, 2);
+```
+
+```sql
+SELECT RS_Value(RS_Example(), ST_SetCRS(ST_Point(74.58, 110.57), 'OGC:CRS84'));

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: issues-unsubscribe@sedona.apache.org

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


Re: [PR] feat(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
docs/reference/sql/rs_value.qmd:
##########
@@ -0,0 +1,85 @@
+---
+# 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.
+
+title: RS_Value
+description: >
+  Returns the value of a single raster pixel as a double, selected either by a
+  point geometry or by 1-based grid coordinates. Returns null if the location is
+  outside the raster or the pixel holds the band's nodata value.
+kernels:
+  - returns: float64
+    args:
+    - raster
+    - name: point
+      type: geometry
+      description: >
+        The pixel that contains this point is sampled (no resampling).
+        Reprojected into the raster CRS when both carry one.
+  - returns: float64
+    args:
+    - raster
+    - name: point
+      type: geometry
+    - name: band
+      type: int
+      description: Band index (1-based). Defaults to 1 if not specified.
+  - returns: float64
+    args:
+    - raster
+    - name: colX
+      type: int
+      description: Column index (1-based).
+    - name: rowY
+      type: int
+      description: Row index (1-based).

Review Comment:
   Sure, but nobody asked me to review those 🙂 . Compared to GDAL and xarray the PostGIS and Sedona Spark APIs are not particularly popular...part of porting that to SedonaDB is to make it fast, but if anybody is ever going to use this we're also going to have to make it less awkward.



-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double
+//! ```
+//!
+//! Returns the value of the pixel that contains the point (no resampling), or
+//! the value at the given 1-based grid cell. The result is `NULL` when the
+//! raster/arguments are null, the point/cell is out of bounds, or the value
+//! equals the band's nodata.
+//!
+//! The function is tagged [`NEEDS_PIXELS_METADATA_KEY`], so the planner wraps
+//! its raster argument in `RS_EnsureLoaded`; by the time a kernel runs the band
+//! bytes are materialised InDb and a value is read directly from the band's
+//! [`NdBuffer`](sedona_raster::traits::NdBuffer) — no GDAL involved. Only 2-D
+//! rasters are supported; a band with extra (non-spatial) dimensions errors.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{exec_datafusion_err, exec_err, DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{CoordTrait, GeometryTrait, GeometryType, 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::traits::{nodata_bytes_to_f64_lossless, RasterRef};
+use sedona_schema::crs::CrsRef;
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+use wkb::reader::read_wkb;
+
+use crate::crs_utils::{crs_transform_wkb, resolve_crs};
+use crate::executor::RasterExecutor;
+use crate::rs_ensure_loaded::NEEDS_PIXELS_METADATA_KEY;
+
+/// `RS_Value()` scalar UDF — sample a pixel value at a point or grid cell.
+pub fn rs_value_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_value",
+        vec![
+            Arc::new(RsValuePoint { with_band: false }), // RS_Value(raster, point)
+            Arc::new(RsValuePoint { with_band: true }),  // RS_Value(raster, point, band)
+            Arc::new(RsValueGrid { with_band: false }),  // RS_Value(raster, colX, rowY)
+            Arc::new(RsValueGrid { with_band: true }),   // RS_Value(raster, colX, rowY, 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_Value(raster, point[, band])`.
+#[derive(Debug)]
+struct RsValuePoint {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValuePoint {
+    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(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        // The optional band argument, materialised once as an Int32 array.
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[2]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        // Reprojecting the point into the raster CRS needs a PROJ engine.
+        with_global_proj_engine(|engine| {
+            executor.execute_raster_wkb_crs_void(|raster_opt, wkb_opt, point_crs| {
+                let (raster, point_wkb, band_num) =
+                    match (raster_opt, wkb_opt, next_band(&mut band_iter)) {
+                        (Some(raster), Some(point_wkb), Some(band_num)) => {
+                            (raster, point_wkb, band_num)
+                        }
+                        _ => {
+                            builder.append_null();
+                            return Ok(());
+                        }
+                    };
+
+                // Bring the point into the raster's CRS. A reprojection only
+                // happens when both sides carry a (differing) CRS; otherwise
+                // the original WKB is sampled directly.
+                let raster_crs = resolve_crs(raster.crs())?;
+                let reprojected =
+                    reproject_point(point_wkb, point_crs, raster_crs.as_deref(), engine)?;
+                let wkb = reprojected.as_deref().unwrap_or(point_wkb);
+
+                let (x, y) = read_point_xy(wkb)?;
+                // Floor (not truncate toward zero) so a point just outside the
+                // top/left edge maps to a negative index and is rejected as out
+                // of bounds, rather than truncating to 0 and sampling an edge pixel.
+                let (raster_x, raster_y) = AffineMatrix::from_metadata(&raster.metadata())
+                    .inv_transform(x, y)
+                    .map_err(|e| exec_datafusion_err!("RS_Value: {e}"))?;
+                let (col, row) = (raster_x.floor() as i64, raster_y.floor() as i64);
+
+                match sample_pixel(raster, col, row, band_num)? {
+                    Some(value) => builder.append_value(value),
+                    None => builder.append_null(),
+                }
+                Ok(())
+            })
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Kernel for `RS_Value(raster, colX, rowY[, band])` with **1-based** grid
+/// coordinates.
+#[derive(Debug)]
+struct RsValueGrid {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValueGrid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let mut matchers = vec![
+            ArgMatcher::is_raster(),
+            ArgMatcher::is_integer(),
+            ArgMatcher::is_integer(),
+        ];
+        if self.with_band {
+            matchers.push(ArgMatcher::is_integer());
+        }
+        let matcher = ArgMatcher::new(matchers, SedonaType::Arrow(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        let col_array = as_int32_array(
+            &args[1]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();
+        let row_array = as_int32_array(
+            &args[2]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[3]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+
+        let mut col_iter = col_array.iter();
+        let mut row_iter = row_array.iter();
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        executor.execute_raster_void(|_, raster_opt| {
+            let col = col_iter.next().flatten();
+            let row = row_iter.next().flatten();
+            let band_num = next_band(&mut band_iter);
+
+            match (raster_opt, col, row, band_num) {
+                (Some(raster), Some(col), Some(row), Some(band_num)) => {
+                    // 1-based grid coordinates -> 0-based pixel indices.
+                    match sample_pixel(raster, col as i64 - 1, row as i64 - 1, band_num)? {
+                        Some(value) => builder.append_value(value),
+                        None => builder.append_null(),
+                    }
+                }
+                _ => builder.append_null(),
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Advance the optional band-number iterator one row, yielding the 1-based band
+/// to sample. A missing band argument defaults to band 1; a NULL band element
+/// returns `None`, which the caller propagates to a NULL result. Band 0 and
+/// negative values map to 0 so [`Bands::band`](sedona_raster::traits::Bands::band)
+/// rejects them as not 1-based rather than being silently coerced.
+fn next_band(
+    band_iter: &mut Option<arrow_array::iterator::ArrayIter<&arrow_array::Int32Array>>,
+) -> Option<usize> {
+    match band_iter.as_mut() {
+        None => Some(1),
+        Some(iter) => iter.next().flatten().map(|b| b.max(0) as usize),
+    }
+}
+
+/// Reproject `point_wkb` from its CRS into the raster CRS, returning the
+/// transformed WKB only when a reprojection actually happened (so the caller
+/// can sample the original bytes otherwise — no allocation in the common case).
+///
+/// Errors if exactly one of the point / raster carries a CRS: sampling across a
+/// known and an unknown CRS would silently mislocate the point.
+fn reproject_point(
+    point_wkb: &[u8],
+    point_crs: CrsRef<'_>,
+    raster_crs: CrsRef<'_>,
+    engine: &dyn sedona_geometry::transform::CrsEngine,
+) -> Result<Option<Vec<u8>>> {
+    match (point_crs, raster_crs) {
+        (Some(point_crs), Some(raster_crs)) => {
+            if point_crs.crs_equals(raster_crs) {
+                Ok(None)
+            } else {
+                Ok(Some(crs_transform_wkb(
+                    point_wkb, point_crs, raster_crs, engine,
+                )?))
+            }
+        }
+        (None, None) => Ok(None),
+        (Some(_), None) => {
+            exec_err!("RS_Value: point has a CRS but the raster does not")
+        }
+        (None, Some(_)) => {
+            exec_err!("RS_Value: raster has a CRS but the point does not")
+        }
+    }
+}
+
+/// Read the (x, y) coordinates of a WKB Point geometry.
+fn read_point_xy(wkb: &[u8]) -> Result<(f64, f64)> {
+    let geom = read_wkb(wkb).map_err(|e| DataFusionError::External(Box::new(e)))?;
+    match geom.as_type() {

Review Comment:
   been playing with the profiler. WkbHeader is slower.
   
   ```
     ┌─────────────────────────────────────────────────────────┬──────────┬─────────────────┐
     │                         option                          │ ns/point │   vs current    │
     ├─────────────────────────────────────────────────────────┼──────────┼─────────────────┤
     │ (a) WkbHeader::try_new + first_xy — current             │ 19.1     │ —               │
     ├─────────────────────────────────────────────────────────┼──────────┼─────────────────┤
     │ (b) wkb read_wkb + coord — what I replaced this session │ 7.5      │ −11.6 ns (2.5×) │
     ├─────────────────────────────────────────────────────────┼──────────┼─────────────────┤
     │ (c) hand-rolled minimal                                 │ 0.9      │ −18.2 ns (21×)  │
     └─────────────────────────────────────────────────────────┴──────────┴─────────────────┘
   ```
   
   going to consider if I want to revert orproductionize the hand rolled point parser



-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
docs/reference/sql/rs_value.qmd:
##########
@@ -0,0 +1,85 @@
+---
+# 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.
+
+title: RS_Value
+description: >
+  Returns the value of a single raster pixel as a double, selected either by a
+  point geometry or by 1-based grid coordinates. Returns null if the location is
+  outside the raster or the pixel holds the band's nodata value.
+kernels:
+  - returns: float64
+    args:
+    - raster
+    - name: point
+      type: geometry
+      description: >
+        The pixel that contains this point is sampled (no resampling).
+        Reprojected into the raster CRS when both carry one.
+  - returns: float64
+    args:
+    - raster
+    - name: point
+      type: geometry
+    - name: band
+      type: int
+      description: Band index (1-based). Defaults to 1 if not specified.
+  - returns: float64
+    args:
+    - raster
+    - name: colX
+      type: int
+      description: Column index (1-based).
+    - name: rowY
+      type: int
+      description: Row index (1-based).

Review Comment:
   Would it be better to keep st functions in sync between sedona and sedona_db? I understand the concern and bad decisions in the past on the orders of params, but if we'd make them different in signatures, users would need to change their SQL to adapt in between if they ever want to run on both engines.



-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
docs/reference/sql/rs_value.qmd:
##########
@@ -0,0 +1,85 @@
+---
+# 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.
+
+title: RS_Value
+description: >
+  Returns the value of a single raster pixel as a double, selected either by a
+  point geometry or by 1-based grid coordinates. Returns null if the location is
+  outside the raster or the pixel holds the band's nodata value.
+kernels:
+  - returns: float64
+    args:
+    - raster
+    - name: point
+      type: geometry
+      description: >
+        The pixel that contains this point is sampled (no resampling).
+        Reprojected into the raster CRS when both carry one.
+  - returns: float64
+    args:
+    - raster
+    - name: point
+      type: geometry
+    - name: band
+      type: int
+      description: Band index (1-based). Defaults to 1 if not specified.
+  - returns: float64
+    args:
+    - raster
+    - name: colX
+      type: int
+      description: Column index (1-based).
+    - name: rowY
+      type: int
+      description: Row index (1-based).
+  - returns: float64
+    args:
+    - raster
+    - name: colX
+      type: int
+    - name: rowY
+      type: int
+    - name: band
+      type: int
+      description: Band index (1-based). Defaults to 1 if not specified.
+---
+
+## Description
+
+`RS_Value` samples one pixel of a raster. The location is given either as a
+point geometry — the value of the pixel that contains the point is returned, with
+no interpolation — or as 1-based `(colX, rowY)` grid coordinates. The band
+defaults to 1.
+
+The result is `NULL` when the point or grid cell falls outside the raster, or
+when the sampled pixel equals the band's nodata value. Only 2-D rasters are
+supported.
+
+## Examples
+
+```sql
+SELECT RS_Value(RS_Example(), 2, 1);
+```
+
+```sql
+SELECT RS_Value(RS_Example(), 2, 1, 2);
+```
+
+```sql
+SELECT RS_Value(RS_Example(), ST_SetCRS(ST_Point(74.58, 110.57), 'OGC:CRS84'));

Review Comment:
   ```suggestion
   SELECT RS_Value(RS_Example(), ST_Point(74.58, 110.57, 'OGC:CRS84');
   ```



##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double

Review Comment:
   These two should really be a separate function (indexing order is unintuitive and conflicts with PostGIS ST_Value)



##########
docs/reference/sql/rs_value.qmd:
##########
@@ -0,0 +1,85 @@
+---
+# 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.
+
+title: RS_Value
+description: >
+  Returns the value of a single raster pixel as a double, selected either by a
+  point geometry or by 1-based grid coordinates. Returns null if the location is
+  outside the raster or the pixel holds the band's nodata value.
+kernels:
+  - returns: float64
+    args:
+    - raster
+    - name: point
+      type: geometry
+      description: >
+        The pixel that contains this point is sampled (no resampling).
+        Reprojected into the raster CRS when both carry one.
+  - returns: float64
+    args:
+    - raster
+    - name: point
+      type: geometry
+    - name: band
+      type: int
+      description: Band index (1-based). Defaults to 1 if not specified.
+  - returns: float64
+    args:
+    - raster
+    - name: colX
+      type: int
+      description: Column index (1-based).
+    - name: rowY
+      type: int
+      description: Row index (1-based).

Review Comment:
   Indexing is typically rows, cols (e.g., numpy, R) instead of cols, rows.



##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double
+//! ```
+//!
+//! Returns the value of the pixel that contains the point (no resampling), or
+//! the value at the given 1-based grid cell. The result is `NULL` when the
+//! raster/arguments are null, the point/cell is out of bounds, or the value
+//! equals the band's nodata.
+//!
+//! The function is tagged [`NEEDS_PIXELS_METADATA_KEY`], so the planner wraps
+//! its raster argument in `RS_EnsureLoaded`; by the time a kernel runs the band
+//! bytes are materialised InDb and a value is read directly from the band's
+//! [`NdBuffer`](sedona_raster::traits::NdBuffer) — no GDAL involved. Only 2-D
+//! rasters are supported; a band with extra (non-spatial) dimensions errors.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{exec_datafusion_err, exec_err, DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{CoordTrait, GeometryTrait, GeometryType, 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::traits::{nodata_bytes_to_f64_lossless, RasterRef};
+use sedona_schema::crs::CrsRef;
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+use wkb::reader::read_wkb;
+
+use crate::crs_utils::{crs_transform_wkb, resolve_crs};
+use crate::executor::RasterExecutor;
+use crate::rs_ensure_loaded::NEEDS_PIXELS_METADATA_KEY;
+
+/// `RS_Value()` scalar UDF — sample a pixel value at a point or grid cell.
+pub fn rs_value_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_value",
+        vec![
+            Arc::new(RsValuePoint { with_band: false }), // RS_Value(raster, point)
+            Arc::new(RsValuePoint { with_band: true }),  // RS_Value(raster, point, band)
+            Arc::new(RsValueGrid { with_band: false }),  // RS_Value(raster, colX, rowY)
+            Arc::new(RsValueGrid { with_band: true }),   // RS_Value(raster, colX, rowY, 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_Value(raster, point[, band])`.
+#[derive(Debug)]
+struct RsValuePoint {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValuePoint {
+    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(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        // The optional band argument, materialised once as an Int32 array.
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[2]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        // Reprojecting the point into the raster CRS needs a PROJ engine.
+        with_global_proj_engine(|engine| {

Review Comment:
   This can stay but I'll open a PR so that we don't have to do this...we shouldn't have to need a PROJ dependency for this to work (e.g., in the likely event all CRSes are equal, no need for PROJ).



##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double
+//! ```
+//!
+//! Returns the value of the pixel that contains the point (no resampling), or
+//! the value at the given 1-based grid cell. The result is `NULL` when the
+//! raster/arguments are null, the point/cell is out of bounds, or the value
+//! equals the band's nodata.
+//!
+//! The function is tagged [`NEEDS_PIXELS_METADATA_KEY`], so the planner wraps
+//! its raster argument in `RS_EnsureLoaded`; by the time a kernel runs the band
+//! bytes are materialised InDb and a value is read directly from the band's
+//! [`NdBuffer`](sedona_raster::traits::NdBuffer) — no GDAL involved. Only 2-D
+//! rasters are supported; a band with extra (non-spatial) dimensions errors.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{exec_datafusion_err, exec_err, DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{CoordTrait, GeometryTrait, GeometryType, 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::traits::{nodata_bytes_to_f64_lossless, RasterRef};
+use sedona_schema::crs::CrsRef;
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+use wkb::reader::read_wkb;
+
+use crate::crs_utils::{crs_transform_wkb, resolve_crs};
+use crate::executor::RasterExecutor;
+use crate::rs_ensure_loaded::NEEDS_PIXELS_METADATA_KEY;
+
+/// `RS_Value()` scalar UDF — sample a pixel value at a point or grid cell.
+pub fn rs_value_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_value",
+        vec![
+            Arc::new(RsValuePoint { with_band: false }), // RS_Value(raster, point)
+            Arc::new(RsValuePoint { with_band: true }),  // RS_Value(raster, point, band)
+            Arc::new(RsValueGrid { with_band: false }),  // RS_Value(raster, colX, rowY)
+            Arc::new(RsValueGrid { with_band: true }),   // RS_Value(raster, colX, rowY, 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_Value(raster, point[, band])`.
+#[derive(Debug)]
+struct RsValuePoint {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValuePoint {
+    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(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        // The optional band argument, materialised once as an Int32 array.
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[2]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        // Reprojecting the point into the raster CRS needs a PROJ engine.
+        with_global_proj_engine(|engine| {
+            executor.execute_raster_wkb_crs_void(|raster_opt, wkb_opt, point_crs| {
+                let (raster, point_wkb, band_num) =
+                    match (raster_opt, wkb_opt, next_band(&mut band_iter)) {
+                        (Some(raster), Some(point_wkb), Some(band_num)) => {
+                            (raster, point_wkb, band_num)
+                        }
+                        _ => {
+                            builder.append_null();
+                            return Ok(());
+                        }
+                    };
+
+                // Bring the point into the raster's CRS. A reprojection only
+                // happens when both sides carry a (differing) CRS; otherwise
+                // the original WKB is sampled directly.
+                let raster_crs = resolve_crs(raster.crs())?;
+                let reprojected =
+                    reproject_point(point_wkb, point_crs, raster_crs.as_deref(), engine)?;
+                let wkb = reprojected.as_deref().unwrap_or(point_wkb);
+
+                let (x, y) = read_point_xy(wkb)?;
+                // Floor (not truncate toward zero) so a point just outside the
+                // top/left edge maps to a negative index and is rejected as out
+                // of bounds, rather than truncating to 0 and sampling an edge pixel.
+                let (raster_x, raster_y) = AffineMatrix::from_metadata(&raster.metadata())
+                    .inv_transform(x, y)
+                    .map_err(|e| exec_datafusion_err!("RS_Value: {e}"))?;
+                let (col, row) = (raster_x.floor() as i64, raster_y.floor() as i64);
+
+                match sample_pixel(raster, col, row, band_num)? {
+                    Some(value) => builder.append_value(value),
+                    None => builder.append_null(),
+                }
+                Ok(())
+            })
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Kernel for `RS_Value(raster, colX, rowY[, band])` with **1-based** grid
+/// coordinates.
+#[derive(Debug)]
+struct RsValueGrid {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValueGrid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let mut matchers = vec![
+            ArgMatcher::is_raster(),
+            ArgMatcher::is_integer(),
+            ArgMatcher::is_integer(),
+        ];
+        if self.with_band {
+            matchers.push(ArgMatcher::is_integer());
+        }
+        let matcher = ArgMatcher::new(matchers, SedonaType::Arrow(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        let col_array = as_int32_array(
+            &args[1]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();

Review Comment:
   I trust the linter here but I am surprised you need to clone this (it's vaguely more expensive to clone an Int32Array than an ArrayRef).



##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double
+//! ```
+//!
+//! Returns the value of the pixel that contains the point (no resampling), or
+//! the value at the given 1-based grid cell. The result is `NULL` when the
+//! raster/arguments are null, the point/cell is out of bounds, or the value
+//! equals the band's nodata.
+//!
+//! The function is tagged [`NEEDS_PIXELS_METADATA_KEY`], so the planner wraps
+//! its raster argument in `RS_EnsureLoaded`; by the time a kernel runs the band
+//! bytes are materialised InDb and a value is read directly from the band's
+//! [`NdBuffer`](sedona_raster::traits::NdBuffer) — no GDAL involved. Only 2-D
+//! rasters are supported; a band with extra (non-spatial) dimensions errors.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{exec_datafusion_err, exec_err, DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{CoordTrait, GeometryTrait, GeometryType, 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::traits::{nodata_bytes_to_f64_lossless, RasterRef};
+use sedona_schema::crs::CrsRef;
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+use wkb::reader::read_wkb;
+
+use crate::crs_utils::{crs_transform_wkb, resolve_crs};
+use crate::executor::RasterExecutor;
+use crate::rs_ensure_loaded::NEEDS_PIXELS_METADATA_KEY;
+
+/// `RS_Value()` scalar UDF — sample a pixel value at a point or grid cell.
+pub fn rs_value_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_value",
+        vec![
+            Arc::new(RsValuePoint { with_band: false }), // RS_Value(raster, point)
+            Arc::new(RsValuePoint { with_band: true }),  // RS_Value(raster, point, band)
+            Arc::new(RsValueGrid { with_band: false }),  // RS_Value(raster, colX, rowY)
+            Arc::new(RsValueGrid { with_band: true }),   // RS_Value(raster, colX, rowY, 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_Value(raster, point[, band])`.
+#[derive(Debug)]
+struct RsValuePoint {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValuePoint {
+    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(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        // The optional band argument, materialised once as an Int32 array.
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[2]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        // Reprojecting the point into the raster CRS needs a PROJ engine.
+        with_global_proj_engine(|engine| {
+            executor.execute_raster_wkb_crs_void(|raster_opt, wkb_opt, point_crs| {
+                let (raster, point_wkb, band_num) =
+                    match (raster_opt, wkb_opt, next_band(&mut band_iter)) {
+                        (Some(raster), Some(point_wkb), Some(band_num)) => {
+                            (raster, point_wkb, band_num)
+                        }
+                        _ => {
+                            builder.append_null();
+                            return Ok(());
+                        }
+                    };
+
+                // Bring the point into the raster's CRS. A reprojection only
+                // happens when both sides carry a (differing) CRS; otherwise
+                // the original WKB is sampled directly.
+                let raster_crs = resolve_crs(raster.crs())?;
+                let reprojected =
+                    reproject_point(point_wkb, point_crs, raster_crs.as_deref(), engine)?;
+                let wkb = reprojected.as_deref().unwrap_or(point_wkb);
+
+                let (x, y) = read_point_xy(wkb)?;
+                // Floor (not truncate toward zero) so a point just outside the
+                // top/left edge maps to a negative index and is rejected as out
+                // of bounds, rather than truncating to 0 and sampling an edge pixel.
+                let (raster_x, raster_y) = AffineMatrix::from_metadata(&raster.metadata())
+                    .inv_transform(x, y)
+                    .map_err(|e| exec_datafusion_err!("RS_Value: {e}"))?;
+                let (col, row) = (raster_x.floor() as i64, raster_y.floor() as i64);

Review Comment:
   Can this math overflow an i64 and panic?



##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double
+//! ```
+//!
+//! Returns the value of the pixel that contains the point (no resampling), or
+//! the value at the given 1-based grid cell. The result is `NULL` when the
+//! raster/arguments are null, the point/cell is out of bounds, or the value
+//! equals the band's nodata.
+//!
+//! The function is tagged [`NEEDS_PIXELS_METADATA_KEY`], so the planner wraps
+//! its raster argument in `RS_EnsureLoaded`; by the time a kernel runs the band
+//! bytes are materialised InDb and a value is read directly from the band's
+//! [`NdBuffer`](sedona_raster::traits::NdBuffer) — no GDAL involved. Only 2-D
+//! rasters are supported; a band with extra (non-spatial) dimensions errors.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{exec_datafusion_err, exec_err, DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{CoordTrait, GeometryTrait, GeometryType, 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::traits::{nodata_bytes_to_f64_lossless, RasterRef};
+use sedona_schema::crs::CrsRef;
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+use wkb::reader::read_wkb;
+
+use crate::crs_utils::{crs_transform_wkb, resolve_crs};
+use crate::executor::RasterExecutor;
+use crate::rs_ensure_loaded::NEEDS_PIXELS_METADATA_KEY;
+
+/// `RS_Value()` scalar UDF — sample a pixel value at a point or grid cell.
+pub fn rs_value_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_value",
+        vec![
+            Arc::new(RsValuePoint { with_band: false }), // RS_Value(raster, point)
+            Arc::new(RsValuePoint { with_band: true }),  // RS_Value(raster, point, band)
+            Arc::new(RsValueGrid { with_band: false }),  // RS_Value(raster, colX, rowY)
+            Arc::new(RsValueGrid { with_band: true }),   // RS_Value(raster, colX, rowY, 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_Value(raster, point[, band])`.
+#[derive(Debug)]
+struct RsValuePoint {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValuePoint {
+    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(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        // The optional band argument, materialised once as an Int32 array.
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[2]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        // Reprojecting the point into the raster CRS needs a PROJ engine.
+        with_global_proj_engine(|engine| {
+            executor.execute_raster_wkb_crs_void(|raster_opt, wkb_opt, point_crs| {
+                let (raster, point_wkb, band_num) =
+                    match (raster_opt, wkb_opt, next_band(&mut band_iter)) {
+                        (Some(raster), Some(point_wkb), Some(band_num)) => {
+                            (raster, point_wkb, band_num)
+                        }
+                        _ => {
+                            builder.append_null();
+                            return Ok(());
+                        }
+                    };
+
+                // Bring the point into the raster's CRS. A reprojection only
+                // happens when both sides carry a (differing) CRS; otherwise
+                // the original WKB is sampled directly.
+                let raster_crs = resolve_crs(raster.crs())?;
+                let reprojected =
+                    reproject_point(point_wkb, point_crs, raster_crs.as_deref(), engine)?;
+                let wkb = reprojected.as_deref().unwrap_or(point_wkb);
+
+                let (x, y) = read_point_xy(wkb)?;
+                // Floor (not truncate toward zero) so a point just outside the
+                // top/left edge maps to a negative index and is rejected as out
+                // of bounds, rather than truncating to 0 and sampling an edge pixel.
+                let (raster_x, raster_y) = AffineMatrix::from_metadata(&raster.metadata())
+                    .inv_transform(x, y)
+                    .map_err(|e| exec_datafusion_err!("RS_Value: {e}"))?;
+                let (col, row) = (raster_x.floor() as i64, raster_y.floor() as i64);
+
+                match sample_pixel(raster, col, row, band_num)? {
+                    Some(value) => builder.append_value(value),
+                    None => builder.append_null(),
+                }
+                Ok(())
+            })
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Kernel for `RS_Value(raster, colX, rowY[, band])` with **1-based** grid
+/// coordinates.
+#[derive(Debug)]
+struct RsValueGrid {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValueGrid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let mut matchers = vec![
+            ArgMatcher::is_raster(),
+            ArgMatcher::is_integer(),
+            ArgMatcher::is_integer(),
+        ];
+        if self.with_band {
+            matchers.push(ArgMatcher::is_integer());
+        }
+        let matcher = ArgMatcher::new(matchers, SedonaType::Arrow(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        let col_array = as_int32_array(
+            &args[1]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();
+        let row_array = as_int32_array(
+            &args[2]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[3]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+
+        let mut col_iter = col_array.iter();
+        let mut row_iter = row_array.iter();
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        executor.execute_raster_void(|_, raster_opt| {
+            let col = col_iter.next().flatten();
+            let row = row_iter.next().flatten();
+            let band_num = next_band(&mut band_iter);
+
+            match (raster_opt, col, row, band_num) {
+                (Some(raster), Some(col), Some(row), Some(band_num)) => {
+                    // 1-based grid coordinates -> 0-based pixel indices.
+                    match sample_pixel(raster, col as i64 - 1, row as i64 - 1, band_num)? {
+                        Some(value) => builder.append_value(value),
+                        None => builder.append_null(),
+                    }
+                }
+                _ => builder.append_null(),
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Advance the optional band-number iterator one row, yielding the 1-based band
+/// to sample. A missing band argument defaults to band 1; a NULL band element
+/// returns `None`, which the caller propagates to a NULL result. Band 0 and
+/// negative values map to 0 so [`Bands::band`](sedona_raster::traits::Bands::band)
+/// rejects them as not 1-based rather than being silently coerced.
+fn next_band(
+    band_iter: &mut Option<arrow_array::iterator::ArrayIter<&arrow_array::Int32Array>>,
+) -> Option<usize> {
+    match band_iter.as_mut() {
+        None => Some(1),
+        Some(iter) => iter.next().flatten().map(|b| b.max(0) as usize),
+    }
+}
+
+/// Reproject `point_wkb` from its CRS into the raster CRS, returning the
+/// transformed WKB only when a reprojection actually happened (so the caller
+/// can sample the original bytes otherwise — no allocation in the common case).
+///
+/// Errors if exactly one of the point / raster carries a CRS: sampling across a
+/// known and an unknown CRS would silently mislocate the point.
+fn reproject_point(
+    point_wkb: &[u8],
+    point_crs: CrsRef<'_>,
+    raster_crs: CrsRef<'_>,
+    engine: &dyn sedona_geometry::transform::CrsEngine,
+) -> Result<Option<Vec<u8>>> {
+    match (point_crs, raster_crs) {
+        (Some(point_crs), Some(raster_crs)) => {
+            if point_crs.crs_equals(raster_crs) {
+                Ok(None)
+            } else {
+                Ok(Some(crs_transform_wkb(
+                    point_wkb, point_crs, raster_crs, engine,
+                )?))
+            }
+        }
+        (None, None) => Ok(None),
+        (Some(_), None) => {
+            exec_err!("RS_Value: point has a CRS but the raster does not")
+        }
+        (None, Some(_)) => {
+            exec_err!("RS_Value: raster has a CRS but the point does not")
+        }

Review Comment:
   It is probably the right behaviour for now. If this becomes annoying we can consider options (e.g., an "elided" CRS like `wk::wk_crs_inherit()` in R).



##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double
+//! ```
+//!
+//! Returns the value of the pixel that contains the point (no resampling), or
+//! the value at the given 1-based grid cell. The result is `NULL` when the
+//! raster/arguments are null, the point/cell is out of bounds, or the value
+//! equals the band's nodata.
+//!
+//! The function is tagged [`NEEDS_PIXELS_METADATA_KEY`], so the planner wraps
+//! its raster argument in `RS_EnsureLoaded`; by the time a kernel runs the band
+//! bytes are materialised InDb and a value is read directly from the band's
+//! [`NdBuffer`](sedona_raster::traits::NdBuffer) — no GDAL involved. Only 2-D
+//! rasters are supported; a band with extra (non-spatial) dimensions errors.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{exec_datafusion_err, exec_err, DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{CoordTrait, GeometryTrait, GeometryType, 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::traits::{nodata_bytes_to_f64_lossless, RasterRef};
+use sedona_schema::crs::CrsRef;
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+use wkb::reader::read_wkb;
+
+use crate::crs_utils::{crs_transform_wkb, resolve_crs};
+use crate::executor::RasterExecutor;
+use crate::rs_ensure_loaded::NEEDS_PIXELS_METADATA_KEY;
+
+/// `RS_Value()` scalar UDF — sample a pixel value at a point or grid cell.
+pub fn rs_value_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_value",
+        vec![
+            Arc::new(RsValuePoint { with_band: false }), // RS_Value(raster, point)
+            Arc::new(RsValuePoint { with_band: true }),  // RS_Value(raster, point, band)
+            Arc::new(RsValueGrid { with_band: false }),  // RS_Value(raster, colX, rowY)
+            Arc::new(RsValueGrid { with_band: true }),   // RS_Value(raster, colX, rowY, 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_Value(raster, point[, band])`.
+#[derive(Debug)]
+struct RsValuePoint {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValuePoint {
+    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(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        // The optional band argument, materialised once as an Int32 array.
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[2]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        // Reprojecting the point into the raster CRS needs a PROJ engine.
+        with_global_proj_engine(|engine| {
+            executor.execute_raster_wkb_crs_void(|raster_opt, wkb_opt, point_crs| {
+                let (raster, point_wkb, band_num) =
+                    match (raster_opt, wkb_opt, next_band(&mut band_iter)) {
+                        (Some(raster), Some(point_wkb), Some(band_num)) => {
+                            (raster, point_wkb, band_num)
+                        }
+                        _ => {
+                            builder.append_null();
+                            return Ok(());
+                        }
+                    };
+
+                // Bring the point into the raster's CRS. A reprojection only
+                // happens when both sides carry a (differing) CRS; otherwise
+                // the original WKB is sampled directly.
+                let raster_crs = resolve_crs(raster.crs())?;
+                let reprojected =
+                    reproject_point(point_wkb, point_crs, raster_crs.as_deref(), engine)?;
+                let wkb = reprojected.as_deref().unwrap_or(point_wkb);
+
+                let (x, y) = read_point_xy(wkb)?;
+                // Floor (not truncate toward zero) so a point just outside the
+                // top/left edge maps to a negative index and is rejected as out
+                // of bounds, rather than truncating to 0 and sampling an edge pixel.
+                let (raster_x, raster_y) = AffineMatrix::from_metadata(&raster.metadata())
+                    .inv_transform(x, y)
+                    .map_err(|e| exec_datafusion_err!("RS_Value: {e}"))?;
+                let (col, row) = (raster_x.floor() as i64, raster_y.floor() as i64);
+
+                match sample_pixel(raster, col, row, band_num)? {
+                    Some(value) => builder.append_value(value),
+                    None => builder.append_null(),
+                }
+                Ok(())
+            })
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Kernel for `RS_Value(raster, colX, rowY[, band])` with **1-based** grid
+/// coordinates.
+#[derive(Debug)]
+struct RsValueGrid {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValueGrid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let mut matchers = vec![
+            ArgMatcher::is_raster(),
+            ArgMatcher::is_integer(),
+            ArgMatcher::is_integer(),
+        ];
+        if self.with_band {
+            matchers.push(ArgMatcher::is_integer());
+        }
+        let matcher = ArgMatcher::new(matchers, SedonaType::Arrow(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        let col_array = as_int32_array(
+            &args[1]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();
+        let row_array = as_int32_array(
+            &args[2]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[3]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+
+        let mut col_iter = col_array.iter();
+        let mut row_iter = row_array.iter();
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        executor.execute_raster_void(|_, raster_opt| {
+            let col = col_iter.next().flatten();
+            let row = row_iter.next().flatten();
+            let band_num = next_band(&mut band_iter);
+
+            match (raster_opt, col, row, band_num) {
+                (Some(raster), Some(col), Some(row), Some(band_num)) => {
+                    // 1-based grid coordinates -> 0-based pixel indices.
+                    match sample_pixel(raster, col as i64 - 1, row as i64 - 1, band_num)? {
+                        Some(value) => builder.append_value(value),
+                        None => builder.append_null(),
+                    }
+                }
+                _ => builder.append_null(),
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Advance the optional band-number iterator one row, yielding the 1-based band
+/// to sample. A missing band argument defaults to band 1; a NULL band element
+/// returns `None`, which the caller propagates to a NULL result. Band 0 and
+/// negative values map to 0 so [`Bands::band`](sedona_raster::traits::Bands::band)
+/// rejects them as not 1-based rather than being silently coerced.
+fn next_band(
+    band_iter: &mut Option<arrow_array::iterator::ArrayIter<&arrow_array::Int32Array>>,
+) -> Option<usize> {
+    match band_iter.as_mut() {
+        None => Some(1),
+        Some(iter) => iter.next().flatten().map(|b| b.max(0) as usize),
+    }
+}
+
+/// Reproject `point_wkb` from its CRS into the raster CRS, returning the
+/// transformed WKB only when a reprojection actually happened (so the caller
+/// can sample the original bytes otherwise — no allocation in the common case).
+///
+/// Errors if exactly one of the point / raster carries a CRS: sampling across a
+/// known and an unknown CRS would silently mislocate the point.
+fn reproject_point(
+    point_wkb: &[u8],
+    point_crs: CrsRef<'_>,
+    raster_crs: CrsRef<'_>,
+    engine: &dyn sedona_geometry::transform::CrsEngine,
+) -> Result<Option<Vec<u8>>> {
+    match (point_crs, raster_crs) {
+        (Some(point_crs), Some(raster_crs)) => {
+            if point_crs.crs_equals(raster_crs) {
+                Ok(None)
+            } else {
+                Ok(Some(crs_transform_wkb(
+                    point_wkb, point_crs, raster_crs, engine,
+                )?))
+            }
+        }
+        (None, None) => Ok(None),
+        (Some(_), None) => {
+            exec_err!("RS_Value: point has a CRS but the raster does not")
+        }
+        (None, Some(_)) => {
+            exec_err!("RS_Value: raster has a CRS but the point does not")
+        }
+    }
+}
+
+/// Read the (x, y) coordinates of a WKB Point geometry.
+fn read_point_xy(wkb: &[u8]) -> Result<(f64, f64)> {
+    let geom = read_wkb(wkb).map_err(|e| DataFusionError::External(Box::new(e)))?;
+    match geom.as_type() {

Review Comment:
   You can use `WkbHeader` for this, which is possibly faster



##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double
+//! ```
+//!
+//! Returns the value of the pixel that contains the point (no resampling), or
+//! the value at the given 1-based grid cell. The result is `NULL` when the
+//! raster/arguments are null, the point/cell is out of bounds, or the value
+//! equals the band's nodata.
+//!
+//! The function is tagged [`NEEDS_PIXELS_METADATA_KEY`], so the planner wraps
+//! its raster argument in `RS_EnsureLoaded`; by the time a kernel runs the band
+//! bytes are materialised InDb and a value is read directly from the band's
+//! [`NdBuffer`](sedona_raster::traits::NdBuffer) — no GDAL involved. Only 2-D
+//! rasters are supported; a band with extra (non-spatial) dimensions errors.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{exec_datafusion_err, exec_err, DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{CoordTrait, GeometryTrait, GeometryType, 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::traits::{nodata_bytes_to_f64_lossless, RasterRef};
+use sedona_schema::crs::CrsRef;
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+use wkb::reader::read_wkb;
+
+use crate::crs_utils::{crs_transform_wkb, resolve_crs};
+use crate::executor::RasterExecutor;
+use crate::rs_ensure_loaded::NEEDS_PIXELS_METADATA_KEY;
+
+/// `RS_Value()` scalar UDF — sample a pixel value at a point or grid cell.
+pub fn rs_value_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_value",
+        vec![
+            Arc::new(RsValuePoint { with_band: false }), // RS_Value(raster, point)
+            Arc::new(RsValuePoint { with_band: true }),  // RS_Value(raster, point, band)
+            Arc::new(RsValueGrid { with_band: false }),  // RS_Value(raster, colX, rowY)
+            Arc::new(RsValueGrid { with_band: true }),   // RS_Value(raster, colX, rowY, 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_Value(raster, point[, band])`.
+#[derive(Debug)]
+struct RsValuePoint {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValuePoint {
+    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(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        // The optional band argument, materialised once as an Int32 array.
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[2]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        // Reprojecting the point into the raster CRS needs a PROJ engine.
+        with_global_proj_engine(|engine| {
+            executor.execute_raster_wkb_crs_void(|raster_opt, wkb_opt, point_crs| {
+                let (raster, point_wkb, band_num) =
+                    match (raster_opt, wkb_opt, next_band(&mut band_iter)) {
+                        (Some(raster), Some(point_wkb), Some(band_num)) => {
+                            (raster, point_wkb, band_num)
+                        }
+                        _ => {
+                            builder.append_null();
+                            return Ok(());
+                        }
+                    };
+
+                // Bring the point into the raster's CRS. A reprojection only
+                // happens when both sides carry a (differing) CRS; otherwise
+                // the original WKB is sampled directly.
+                let raster_crs = resolve_crs(raster.crs())?;
+                let reprojected =
+                    reproject_point(point_wkb, point_crs, raster_crs.as_deref(), engine)?;
+                let wkb = reprojected.as_deref().unwrap_or(point_wkb);
+
+                let (x, y) = read_point_xy(wkb)?;
+                // Floor (not truncate toward zero) so a point just outside the
+                // top/left edge maps to a negative index and is rejected as out
+                // of bounds, rather than truncating to 0 and sampling an edge pixel.
+                let (raster_x, raster_y) = AffineMatrix::from_metadata(&raster.metadata())
+                    .inv_transform(x, y)
+                    .map_err(|e| exec_datafusion_err!("RS_Value: {e}"))?;
+                let (col, row) = (raster_x.floor() as i64, raster_y.floor() as i64);
+
+                match sample_pixel(raster, col, row, band_num)? {
+                    Some(value) => builder.append_value(value),
+                    None => builder.append_null(),
+                }
+                Ok(())
+            })
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Kernel for `RS_Value(raster, colX, rowY[, band])` with **1-based** grid
+/// coordinates.
+#[derive(Debug)]
+struct RsValueGrid {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValueGrid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let mut matchers = vec![
+            ArgMatcher::is_raster(),
+            ArgMatcher::is_integer(),
+            ArgMatcher::is_integer(),
+        ];
+        if self.with_band {
+            matchers.push(ArgMatcher::is_integer());
+        }
+        let matcher = ArgMatcher::new(matchers, SedonaType::Arrow(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        let col_array = as_int32_array(
+            &args[1]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();
+        let row_array = as_int32_array(
+            &args[2]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[3]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+
+        let mut col_iter = col_array.iter();
+        let mut row_iter = row_array.iter();
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        executor.execute_raster_void(|_, raster_opt| {
+            let col = col_iter.next().flatten();
+            let row = row_iter.next().flatten();
+            let band_num = next_band(&mut band_iter);
+
+            match (raster_opt, col, row, band_num) {
+                (Some(raster), Some(col), Some(row), Some(band_num)) => {
+                    // 1-based grid coordinates -> 0-based pixel indices.
+                    match sample_pixel(raster, col as i64 - 1, row as i64 - 1, band_num)? {
+                        Some(value) => builder.append_value(value),
+                        None => builder.append_null(),
+                    }
+                }
+                _ => builder.append_null(),
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Advance the optional band-number iterator one row, yielding the 1-based band
+/// to sample. A missing band argument defaults to band 1; a NULL band element
+/// returns `None`, which the caller propagates to a NULL result. Band 0 and
+/// negative values map to 0 so [`Bands::band`](sedona_raster::traits::Bands::band)
+/// rejects them as not 1-based rather than being silently coerced.
+fn next_band(
+    band_iter: &mut Option<arrow_array::iterator::ArrayIter<&arrow_array::Int32Array>>,
+) -> Option<usize> {
+    match band_iter.as_mut() {
+        None => Some(1),
+        Some(iter) => iter.next().flatten().map(|b| b.max(0) as usize),
+    }
+}
+
+/// Reproject `point_wkb` from its CRS into the raster CRS, returning the
+/// transformed WKB only when a reprojection actually happened (so the caller
+/// can sample the original bytes otherwise — no allocation in the common case).
+///
+/// Errors if exactly one of the point / raster carries a CRS: sampling across a
+/// known and an unknown CRS would silently mislocate the point.
+fn reproject_point(
+    point_wkb: &[u8],
+    point_crs: CrsRef<'_>,
+    raster_crs: CrsRef<'_>,
+    engine: &dyn sedona_geometry::transform::CrsEngine,
+) -> Result<Option<Vec<u8>>> {
+    match (point_crs, raster_crs) {
+        (Some(point_crs), Some(raster_crs)) => {
+            if point_crs.crs_equals(raster_crs) {
+                Ok(None)
+            } else {
+                Ok(Some(crs_transform_wkb(
+                    point_wkb, point_crs, raster_crs, engine,
+                )?))
+            }
+        }
+        (None, None) => Ok(None),
+        (Some(_), None) => {
+            exec_err!("RS_Value: point has a CRS but the raster does not")
+        }
+        (None, Some(_)) => {
+            exec_err!("RS_Value: raster has a CRS but the point does not")
+        }
+    }
+}
+
+/// Read the (x, y) coordinates of a WKB Point geometry.
+fn read_point_xy(wkb: &[u8]) -> Result<(f64, f64)> {
+    let geom = read_wkb(wkb).map_err(|e| DataFusionError::External(Box::new(e)))?;
+    match geom.as_type() {
+        GeometryType::Point(point) => {
+            let coord = point
+                .coord()
+                .ok_or_else(|| exec_datafusion_err!("RS_Value: empty point geometry"))?;
+            Ok((coord.x(), coord.y()))
+        }
+        _ => exec_err!("RS_Value expects a Point geometry"),
+    }
+}
+
+/// Sample band `band_num` (1-based) at 0-based pixel `(col, row)` as `f64`.
+///
+/// Returns `None` when the pixel is out of bounds or equals the band's nodata.
+/// Reads exactly one pixel by computing its byte offset from the band's
+/// [`NdBuffer`](sedona_raster::traits::NdBuffer) strides — zero-copy and O(1),
+/// no whole-band materialisation. Errors if the band index is out of range or
+/// the band is not 2-D.
+fn sample_pixel(
+    raster: &dyn RasterRef,
+    col: i64,
+    row: i64,
+    band_num: usize,
+) -> Result<Option<f64>> {
+    let band = raster
+        .bands()
+        .band(band_num)
+        .map_err(|e| exec_datafusion_err!("RS_Value: {e}"))?;
+
+    // 2-D only: the band must be a recognized spatial (y, x) grid, not just any
+    // two-axis band (e.g. (time, band) would have len 2 but no spatial meaning).
+    if !band.is_spatial_2d() {
+        return exec_err!("RS_Value supports 2-D rasters only; band is not a 2-D (y, x) grid");
+    }
+    let buffer = band
+        .nd_buffer()
+        .map_err(|e| exec_datafusion_err!("RS_Value: {e}"))?;
+    let (height, width) = (buffer.shape[0], buffer.shape[1]);
+    if row < 0 || row >= height || col < 0 || col >= width {
+        return Ok(None);
+    }
+
+    // Byte offset of the (row, col) pixel via the band's own strides, so the
+    // read stays correct for any layout the producer hands us.
+    let byte_offset = buffer.offset as i64 + row * buffer.strides[0] + col * buffer.strides[1];
+    let size = buffer.data_type.byte_size() as i64;
+    let start = usize::try_from(byte_offset)
+        .map_err(|_| exec_datafusion_err!("RS_Value: negative pixel byte offset"))?;
+    let end = usize::try_from(byte_offset + size)
+        .map_err(|_| exec_datafusion_err!("RS_Value: pixel byte offset overflow"))?;
+    let bytes = buffer.buffer.get(start..end).ok_or_else(|| {
+        exec_datafusion_err!("RS_Value: pixel is out of the band's buffer bounds")
+    })?;
+
+    // Decode the pixel to f64. The lossless converter errors (rather than
+    // silently rounding) on Int64/UInt64 values beyond f64's exact-integer
+    // range (2^53) — RS_Value returns a Double, so such a pixel can't be
+    // represented faithfully; failing loudly is preferred over a wrong value.
+    let value = nodata_bytes_to_f64_lossless(bytes, &buffer.data_type)

Review Comment:
   👍  (we'll have to figure out what to do about i64/u64 outputs at some point)



-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
docs/reference/sql/rs_value.qmd:
##########
@@ -0,0 +1,85 @@
+---
+# 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.
+
+title: RS_Value
+description: >
+  Returns the value of a single raster pixel as a double, selected either by a
+  point geometry or by 1-based grid coordinates. Returns null if the location is
+  outside the raster or the pixel holds the band's nodata value.
+kernels:
+  - returns: float64
+    args:
+    - raster
+    - name: point
+      type: geometry
+      description: >
+        The pixel that contains this point is sampled (no resampling).
+        Reprojected into the raster CRS when both carry one.
+  - returns: float64
+    args:
+    - raster
+    - name: point
+      type: geometry
+    - name: band
+      type: int
+      description: Band index (1-based). Defaults to 1 if not specified.
+  - returns: float64
+    args:
+    - raster
+    - name: colX
+      type: int
+      description: Column index (1-based).
+    - name: rowY
+      type: int
+      description: Row index (1-based).

Review Comment:
   also sedona spark: https://sedona.apache.org/latest/api/sql/Raster-Operators/RS_Value/
   



-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
python/sedonadb/tests/functions/test_raster_functions.py:
##########
@@ -98,3 +98,36 @@ def test_rs_ensureloaded(con, sedona_testing):
     assert arr.shape == (512, 512)
     assert arr.dtype == "uint16"
     assert arr[0, 0] == 2324
+
+
+# Point sampling. RS_Example fills band `b` with the constant value `b`, except
+# the top-left pixel which is set to the nodata value (127). (74.58, 110.57) is
+# the centroid of pixel (10, 10) (0-based) in the raster's OGC:CRS84 space; the
+# point and raster share a CRS so no reprojection happens. A point far outside
+# the footprint yields NULL. (The `needs_pixels` -> RS_EnsureLoaded planner path
+# is covered against a real OutDb raster by `test_rs_ensureloaded`.)
+@pytest.mark.parametrize(

Review Comment:
   One other test that would be valuable would be filling a numpy array with random values and sampling (1) every corner, center, and edge point (which is just the same grid shifted by 0.5 four ways) and (2) random points, maybe via sd_random_geometry. Then check both against rasterio for identical results. This could also use a fixture (I think we already have one for the sedona_testing directory).



##########
rust/sedona-geometry/src/wkb_header.rs:
##########
@@ -1059,4 +1130,102 @@ mod tests {
         let header = WkbHeader::try_new(&wkb).unwrap();
         assert!(header.is_empty().unwrap());
     }
+
+    #[test]
+    fn read_point_xy_iso_little_endian() {
+        // 2-D / 3-D / 4-D ISO points all expose the same leading (x, y), and the
+        // result must agree with the general parser's `first_xy`.
+        for wkt_value in [
+            "POINT (1 2)",
+            "POINT Z (1 2 3)",
+            "POINT M (1 2 3)",
+            "POINT ZM (1 2 3 4)",
+        ] {
+            let wkb = make_wkb(wkt_value);
+            assert_eq!(
+                read_point_xy(&wkb).unwrap(),
+                Some((1.0, 2.0)),
+                "{wkt_value}"
+            );
+            assert_eq!(
+                read_point_xy(&wkb).unwrap(),
+                Some(WkbHeader::try_new(&wkb).unwrap().first_xy()),
+                "disagrees with first_xy for {wkt_value}"
+            );
+        }
+    }
+
+    #[test]
+    fn read_point_xy_big_endian() {
+        // Byte order 0x00, type 1 (BE), x = 1.0, y = 2.0 — all big-endian.
+        let wkb: [u8; 21] = [
+            0x00, // big-endian
+            0x00, 0x00, 0x00, 0x01, // type code 1 (Point)
+            0x3F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // x = 1.0
+            0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // y = 2.0
+        ];
+        assert_eq!(read_point_xy(&wkb).unwrap(), Some((1.0, 2.0)));
+    }
+
+    #[test]
+    fn read_point_xy_ewkb_with_srid() {
+        use sedona_testing::fixtures::*;

Review Comment:
   This could probably be moved up to `mod test` since it shows up a few times



-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double
+//! ```
+//!
+//! Returns the value of the pixel that contains the point (no resampling), or
+//! the value at the given 1-based grid cell. The result is `NULL` when the
+//! raster/arguments are null, the point/cell is out of bounds, or the value
+//! equals the band's nodata.
+//!
+//! The function is tagged [`NEEDS_PIXELS_METADATA_KEY`], so the planner wraps
+//! its raster argument in `RS_EnsureLoaded`; by the time a kernel runs the band
+//! bytes are materialised InDb and a value is read directly from the band's
+//! [`NdBuffer`](sedona_raster::traits::NdBuffer) — no GDAL involved. Only 2-D
+//! rasters are supported; a band with extra (non-spatial) dimensions errors.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{exec_datafusion_err, exec_err, DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{CoordTrait, GeometryTrait, GeometryType, 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::traits::{nodata_bytes_to_f64_lossless, RasterRef};
+use sedona_schema::crs::CrsRef;
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+use wkb::reader::read_wkb;
+
+use crate::crs_utils::{crs_transform_wkb, resolve_crs};
+use crate::executor::RasterExecutor;
+use crate::rs_ensure_loaded::NEEDS_PIXELS_METADATA_KEY;
+
+/// `RS_Value()` scalar UDF — sample a pixel value at a point or grid cell.
+pub fn rs_value_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_value",
+        vec![
+            Arc::new(RsValuePoint { with_band: false }), // RS_Value(raster, point)
+            Arc::new(RsValuePoint { with_band: true }),  // RS_Value(raster, point, band)
+            Arc::new(RsValueGrid { with_band: false }),  // RS_Value(raster, colX, rowY)
+            Arc::new(RsValueGrid { with_band: true }),   // RS_Value(raster, colX, rowY, 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_Value(raster, point[, band])`.
+#[derive(Debug)]
+struct RsValuePoint {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValuePoint {
+    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(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        // The optional band argument, materialised once as an Int32 array.
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[2]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        // Reprojecting the point into the raster CRS needs a PROJ engine.
+        with_global_proj_engine(|engine| {
+            executor.execute_raster_wkb_crs_void(|raster_opt, wkb_opt, point_crs| {
+                let (raster, point_wkb, band_num) =
+                    match (raster_opt, wkb_opt, next_band(&mut band_iter)) {
+                        (Some(raster), Some(point_wkb), Some(band_num)) => {
+                            (raster, point_wkb, band_num)
+                        }
+                        _ => {
+                            builder.append_null();
+                            return Ok(());
+                        }
+                    };
+
+                // Bring the point into the raster's CRS. A reprojection only
+                // happens when both sides carry a (differing) CRS; otherwise
+                // the original WKB is sampled directly.
+                let raster_crs = resolve_crs(raster.crs())?;
+                let reprojected =
+                    reproject_point(point_wkb, point_crs, raster_crs.as_deref(), engine)?;
+                let wkb = reprojected.as_deref().unwrap_or(point_wkb);
+
+                let (x, y) = read_point_xy(wkb)?;
+                // Floor (not truncate toward zero) so a point just outside the
+                // top/left edge maps to a negative index and is rejected as out
+                // of bounds, rather than truncating to 0 and sampling an edge pixel.
+                let (raster_x, raster_y) = AffineMatrix::from_metadata(&raster.metadata())
+                    .inv_transform(x, y)
+                    .map_err(|e| exec_datafusion_err!("RS_Value: {e}"))?;
+                let (col, row) = (raster_x.floor() as i64, raster_y.floor() as i64);

Review Comment:
   Also, `NaN` values from a POINT EMPTY might cause this to panic (worth testing if it is not tested already)



-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double

Review Comment:
   Ill defer these then.



-- 
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(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double
+//! ```
+//!
+//! Returns the value of the pixel that contains the point (no resampling), or
+//! the value at the given 1-based grid cell. The result is `NULL` when the
+//! raster/arguments are null, the point/cell is out of bounds, or the value
+//! equals the band's nodata.
+//!
+//! The function is tagged [`NEEDS_PIXELS_METADATA_KEY`], so the planner wraps
+//! its raster argument in `RS_EnsureLoaded`; by the time a kernel runs the band
+//! bytes are materialised InDb and a value is read directly from the band's
+//! [`NdBuffer`](sedona_raster::traits::NdBuffer) — no GDAL involved. Only 2-D
+//! rasters are supported; a band with extra (non-spatial) dimensions errors.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{exec_datafusion_err, exec_err, DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{CoordTrait, GeometryTrait, GeometryType, 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::traits::{nodata_bytes_to_f64_lossless, RasterRef};
+use sedona_schema::crs::CrsRef;
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+use wkb::reader::read_wkb;
+
+use crate::crs_utils::{crs_transform_wkb, resolve_crs};
+use crate::executor::RasterExecutor;
+use crate::rs_ensure_loaded::NEEDS_PIXELS_METADATA_KEY;
+
+/// `RS_Value()` scalar UDF — sample a pixel value at a point or grid cell.
+pub fn rs_value_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_value",
+        vec![
+            Arc::new(RsValuePoint { with_band: false }), // RS_Value(raster, point)
+            Arc::new(RsValuePoint { with_band: true }),  // RS_Value(raster, point, band)
+            Arc::new(RsValueGrid { with_band: false }),  // RS_Value(raster, colX, rowY)
+            Arc::new(RsValueGrid { with_band: true }),   // RS_Value(raster, colX, rowY, 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_Value(raster, point[, band])`.
+#[derive(Debug)]
+struct RsValuePoint {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValuePoint {
+    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(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        // The optional band argument, materialised once as an Int32 array.
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[2]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        // Reprojecting the point into the raster CRS needs a PROJ engine.
+        with_global_proj_engine(|engine| {
+            executor.execute_raster_wkb_crs_void(|raster_opt, wkb_opt, point_crs| {
+                let (raster, point_wkb, band_num) =
+                    match (raster_opt, wkb_opt, next_band(&mut band_iter)) {
+                        (Some(raster), Some(point_wkb), Some(band_num)) => {
+                            (raster, point_wkb, band_num)
+                        }
+                        _ => {
+                            builder.append_null();
+                            return Ok(());
+                        }
+                    };
+
+                // Bring the point into the raster's CRS. A reprojection only
+                // happens when both sides carry a (differing) CRS; otherwise
+                // the original WKB is sampled directly.
+                let raster_crs = resolve_crs(raster.crs())?;
+                let reprojected =
+                    reproject_point(point_wkb, point_crs, raster_crs.as_deref(), engine)?;
+                let wkb = reprojected.as_deref().unwrap_or(point_wkb);
+
+                let (x, y) = read_point_xy(wkb)?;
+                // Floor (not truncate toward zero) so a point just outside the
+                // top/left edge maps to a negative index and is rejected as out
+                // of bounds, rather than truncating to 0 and sampling an edge pixel.
+                let (raster_x, raster_y) = AffineMatrix::from_metadata(&raster.metadata())
+                    .inv_transform(x, y)
+                    .map_err(|e| exec_datafusion_err!("RS_Value: {e}"))?;
+                let (col, row) = (raster_x.floor() as i64, raster_y.floor() as i64);

Review Comment:
   I think overflow is very unlikely but I added a checked_mul operator 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] feat(rust/sedona-raster-functions): add RS_Value for spatial 2d rasters [sedona-db]

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


##########
rust/sedona-raster-functions/src/rs_value.rs:
##########
@@ -0,0 +1,583 @@
+// 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_Value` — sample a raster's pixel value at a point or grid cell.
+//!
+//! ```text
+//! RS_Value(raster, point)              -> Double  -- band defaults to 1
+//! RS_Value(raster, point, band)        -> Double
+//! RS_Value(raster, colX, rowY)         -> Double  -- 1-based grid coords, band 1
+//! RS_Value(raster, colX, rowY, band)   -> Double
+//! ```
+//!
+//! Returns the value of the pixel that contains the point (no resampling), or
+//! the value at the given 1-based grid cell. The result is `NULL` when the
+//! raster/arguments are null, the point/cell is out of bounds, or the value
+//! equals the band's nodata.
+//!
+//! The function is tagged [`NEEDS_PIXELS_METADATA_KEY`], so the planner wraps
+//! its raster argument in `RS_EnsureLoaded`; by the time a kernel runs the band
+//! bytes are materialised InDb and a value is read directly from the band's
+//! [`NdBuffer`](sedona_raster::traits::NdBuffer) — no GDAL involved. Only 2-D
+//! rasters are supported; a band with extra (non-spatial) dimensions errors.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{exec_datafusion_err, exec_err, DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::{CoordTrait, GeometryTrait, GeometryType, 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::traits::{nodata_bytes_to_f64_lossless, RasterRef};
+use sedona_schema::crs::CrsRef;
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+use wkb::reader::read_wkb;
+
+use crate::crs_utils::{crs_transform_wkb, resolve_crs};
+use crate::executor::RasterExecutor;
+use crate::rs_ensure_loaded::NEEDS_PIXELS_METADATA_KEY;
+
+/// `RS_Value()` scalar UDF — sample a pixel value at a point or grid cell.
+pub fn rs_value_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_value",
+        vec![
+            Arc::new(RsValuePoint { with_band: false }), // RS_Value(raster, point)
+            Arc::new(RsValuePoint { with_band: true }),  // RS_Value(raster, point, band)
+            Arc::new(RsValueGrid { with_band: false }),  // RS_Value(raster, colX, rowY)
+            Arc::new(RsValueGrid { with_band: true }),   // RS_Value(raster, colX, rowY, 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_Value(raster, point[, band])`.
+#[derive(Debug)]
+struct RsValuePoint {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValuePoint {
+    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(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        // The optional band argument, materialised once as an Int32 array.
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[2]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        // Reprojecting the point into the raster CRS needs a PROJ engine.
+        with_global_proj_engine(|engine| {
+            executor.execute_raster_wkb_crs_void(|raster_opt, wkb_opt, point_crs| {
+                let (raster, point_wkb, band_num) =
+                    match (raster_opt, wkb_opt, next_band(&mut band_iter)) {
+                        (Some(raster), Some(point_wkb), Some(band_num)) => {
+                            (raster, point_wkb, band_num)
+                        }
+                        _ => {
+                            builder.append_null();
+                            return Ok(());
+                        }
+                    };
+
+                // Bring the point into the raster's CRS. A reprojection only
+                // happens when both sides carry a (differing) CRS; otherwise
+                // the original WKB is sampled directly.
+                let raster_crs = resolve_crs(raster.crs())?;
+                let reprojected =
+                    reproject_point(point_wkb, point_crs, raster_crs.as_deref(), engine)?;
+                let wkb = reprojected.as_deref().unwrap_or(point_wkb);
+
+                let (x, y) = read_point_xy(wkb)?;
+                // Floor (not truncate toward zero) so a point just outside the
+                // top/left edge maps to a negative index and is rejected as out
+                // of bounds, rather than truncating to 0 and sampling an edge pixel.
+                let (raster_x, raster_y) = AffineMatrix::from_metadata(&raster.metadata())
+                    .inv_transform(x, y)
+                    .map_err(|e| exec_datafusion_err!("RS_Value: {e}"))?;
+                let (col, row) = (raster_x.floor() as i64, raster_y.floor() as i64);
+
+                match sample_pixel(raster, col, row, band_num)? {
+                    Some(value) => builder.append_value(value),
+                    None => builder.append_null(),
+                }
+                Ok(())
+            })
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Kernel for `RS_Value(raster, colX, rowY[, band])` with **1-based** grid
+/// coordinates.
+#[derive(Debug)]
+struct RsValueGrid {
+    with_band: bool,
+}
+
+impl SedonaScalarKernel for RsValueGrid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let mut matchers = vec![
+            ArgMatcher::is_raster(),
+            ArgMatcher::is_integer(),
+            ArgMatcher::is_integer(),
+        ];
+        if self.with_band {
+            matchers.push(ArgMatcher::is_integer());
+        }
+        let matcher = ArgMatcher::new(matchers, SedonaType::Arrow(DataType::Float64));
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = RasterExecutor::new(arg_types, args);
+        let num_iterations = executor.num_iterations();
+        let mut builder = Float64Builder::with_capacity(num_iterations);
+
+        let col_array = as_int32_array(
+            &args[1]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();
+        let row_array = as_int32_array(
+            &args[2]
+                .clone()
+                .cast_to(&DataType::Int32, None)?
+                .into_array(num_iterations)?,
+        )?
+        .clone();
+        let band_array = if self.with_band {
+            Some(
+                as_int32_array(
+                    &args[3]
+                        .clone()
+                        .cast_to(&DataType::Int32, None)?
+                        .into_array(num_iterations)?,
+                )?
+                .clone(),
+            )
+        } else {
+            None
+        };
+
+        let mut col_iter = col_array.iter();
+        let mut row_iter = row_array.iter();
+        let mut band_iter = band_array.as_ref().map(|a| a.iter());
+
+        executor.execute_raster_void(|_, raster_opt| {
+            let col = col_iter.next().flatten();
+            let row = row_iter.next().flatten();
+            let band_num = next_band(&mut band_iter);
+
+            match (raster_opt, col, row, band_num) {
+                (Some(raster), Some(col), Some(row), Some(band_num)) => {
+                    // 1-based grid coordinates -> 0-based pixel indices.
+                    match sample_pixel(raster, col as i64 - 1, row as i64 - 1, band_num)? {
+                        Some(value) => builder.append_value(value),
+                        None => builder.append_null(),
+                    }
+                }
+                _ => builder.append_null(),
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+/// Advance the optional band-number iterator one row, yielding the 1-based band
+/// to sample. A missing band argument defaults to band 1; a NULL band element
+/// returns `None`, which the caller propagates to a NULL result. Band 0 and
+/// negative values map to 0 so [`Bands::band`](sedona_raster::traits::Bands::band)
+/// rejects them as not 1-based rather than being silently coerced.
+fn next_band(
+    band_iter: &mut Option<arrow_array::iterator::ArrayIter<&arrow_array::Int32Array>>,
+) -> Option<usize> {
+    match band_iter.as_mut() {
+        None => Some(1),
+        Some(iter) => iter.next().flatten().map(|b| b.max(0) as usize),
+    }
+}
+
+/// Reproject `point_wkb` from its CRS into the raster CRS, returning the
+/// transformed WKB only when a reprojection actually happened (so the caller
+/// can sample the original bytes otherwise — no allocation in the common case).
+///
+/// Errors if exactly one of the point / raster carries a CRS: sampling across a
+/// known and an unknown CRS would silently mislocate the point.
+fn reproject_point(
+    point_wkb: &[u8],
+    point_crs: CrsRef<'_>,
+    raster_crs: CrsRef<'_>,
+    engine: &dyn sedona_geometry::transform::CrsEngine,
+) -> Result<Option<Vec<u8>>> {
+    match (point_crs, raster_crs) {
+        (Some(point_crs), Some(raster_crs)) => {
+            if point_crs.crs_equals(raster_crs) {
+                Ok(None)
+            } else {
+                Ok(Some(crs_transform_wkb(
+                    point_wkb, point_crs, raster_crs, engine,
+                )?))
+            }
+        }
+        (None, None) => Ok(None),
+        (Some(_), None) => {
+            exec_err!("RS_Value: point has a CRS but the raster does not")
+        }
+        (None, Some(_)) => {
+            exec_err!("RS_Value: raster has a CRS but the point does not")
+        }
+    }
+}
+
+/// Read the (x, y) coordinates of a WKB Point geometry.
+fn read_point_xy(wkb: &[u8]) -> Result<(f64, f64)> {
+    let geom = read_wkb(wkb).map_err(|e| DataFusionError::External(Box::new(e)))?;
+    match geom.as_type() {

Review Comment:
   I went with c to build the point-optimized parser. I thought the perf gains were worth it: 50% e2e on the Scalar Raster case:
   
   ```
     ┌──────────────────────────────┬────────────────────────┐
     │             case             │         change         │
     ├──────────────────────────────┼────────────────────────┤
     │ ScalarArray (primary target) │ −56% (≈10.6 → 4.66 ms) │
     ├──────────────────────────────┼────────────────────────┤
     │ ArrayArray                   │ −11.7%                 │
     ├──────────────────────────────┼────────────────────────┤
     │ ArrayArrayScalar             │ −12.2%                 │
     └──────────────────────────────┴────────────────────────┘
   ```
   
   We can reuse this implementation on other functions that only accept 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