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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
