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