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