You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sedona.apache.org by pa...@apache.org on 2026/06/27 01:41:54 UTC
(sedona-db) branch main updated: feat(rust/sedona-raster-functions): add RS_SetGeoReference and RS_SetBandNoDataValue (#1003)
This is an automated email from the ASF dual-hosted git repository.
paleolimbot pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/sedona-db.git
The following commit(s) were added to refs/heads/main by this push:
new b23ccd15f feat(rust/sedona-raster-functions): add RS_SetGeoReference and RS_SetBandNoDataValue (#1003)
b23ccd15f is described below
commit b23ccd15f649487b043be219b2dfbb6bad7a668d
Author: James Willis <ja...@users.noreply.github.com>
AuthorDate: Fri Jun 26 18:41:49 2026 -0700
feat(rust/sedona-raster-functions): add RS_SetGeoReference and RS_SetBandNoDataValue (#1003)
---
docs/reference/sql/rs_georeference.qmd | 8 +-
..._georeference.qmd => rs_setbandnodatavalue.qmd} | 38 ++-
docs/reference/sql/rs_setgeoreference.qmd | 61 ++++
.../tests/functions/test_raster_functions.py | 46 +++
rust/sedona-raster-functions/src/lib.rs | 2 +
rust/sedona-raster-functions/src/register.rs | 2 +
.../sedona-raster-functions/src/rs_georeference.rs | 82 +++--
.../src/rs_set_band_nodata.rs | 322 +++++++++++++++++++
.../src/rs_set_georeference.rs | 343 +++++++++++++++++++++
rust/sedona-raster/src/builder.rs | 90 +++++-
rust/sedona-raster/src/traits.rs | 93 ++++++
11 files changed, 1049 insertions(+), 38 deletions(-)
diff --git a/docs/reference/sql/rs_georeference.qmd b/docs/reference/sql/rs_georeference.qmd
index 6f8d3dac6..d9b4c0925 100644
--- a/docs/reference/sql/rs_georeference.qmd
+++ b/docs/reference/sql/rs_georeference.qmd
@@ -32,9 +32,11 @@ kernels:
- name: format
type: utf8
description: >
- Output format, either 'GDAL' (default) or 'ESRI'. GDAL reports the
- upper-left corner of the upper-left pixel; ESRI shifts the coordinates
- to the center of the upper-left pixel.
+ Output format: 'GDAL' (default; alias 'PIXEL') reports the upper-left
+ corner of the upper-left pixel; 'ESRI' (alias 'NODE') shifts the
+ coordinates to the center of the upper-left pixel. The center convention
+ ('ESRI'/'NODE') is rejected for skewed (rotated) rasters, where the
+ half-pixel shift would be inexact.
---
## Examples
diff --git a/docs/reference/sql/rs_georeference.qmd b/docs/reference/sql/rs_setbandnodatavalue.qmd
similarity index 51%
copy from docs/reference/sql/rs_georeference.qmd
copy to docs/reference/sql/rs_setbandnodatavalue.qmd
index 6f8d3dac6..63a7da5a7 100644
--- a/docs/reference/sql/rs_georeference.qmd
+++ b/docs/reference/sql/rs_setbandnodatavalue.qmd
@@ -16,29 +16,37 @@
# specific language governing permissions and limitations
# under the License.
-title: RS_GeoReference
+title: RS_SetBandNoDataValue
description: >
- Returns the georeference metadata of raster as a string in GDAL or ESRI format
- as commonly seen in a world file. Default is GDAL if not specified. Both formats
- output six lines: scalex, skewy, skewx, scaley, upperleftx, upperlefty. In GDAL
- format the upper-left coordinates refer to the corner of the upper-left pixel,
- while in ESRI format they are shifted to the center of the upper-left pixel.
+ Sets the nodata value of the specified band, packing the value into the band's
+ native data type. A null raster, band, or nodata value yields a null raster.
+ This is metadata-only: raster cell values are not modified.
kernels:
- - returns: utf8
- args: [raster]
- - returns: utf8
+ - returns: raster
args:
- raster
- - name: format
- type: utf8
+ - name: nodata
+ type: float64
description: >
- Output format, either 'GDAL' (default) or 'ESRI'. GDAL reports the
- upper-left corner of the upper-left pixel; ESRI shifts the coordinates
- to the center of the upper-left pixel.
+ Nodata value to set. The raster must be single-band; for a multiband
+ raster, specify the band with the three-argument form below.
+ - returns: raster
+ args:
+ - raster
+ - name: band
+ type: int
+ description: Band index (1-based).
+ - name: nodata
+ type: float64
+ description: Nodata value to set on the band.
---
## Examples
```sql
-SELECT RS_GeoReference(RS_Example());
+SELECT RS_BandNoDataValue(RS_SetBandNoDataValue(RS_Example(), 1, 0), 1);
+```
+
+```sql
+SELECT RS_BandNoDataValue(RS_SetBandNoDataValue(RS_Example(), 2, 255), 2);
```
diff --git a/docs/reference/sql/rs_setgeoreference.qmd b/docs/reference/sql/rs_setgeoreference.qmd
new file mode 100644
index 000000000..f492ea39e
--- /dev/null
+++ b/docs/reference/sql/rs_setgeoreference.qmd
@@ -0,0 +1,61 @@
+---
+# 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_SetGeoReference
+description: >
+ Sets the affine geotransform of a raster from a world-file georeference string
+ of six whitespace-separated numbers in the order scalex, skewy, skewx, scaley,
+ upperleftx, upperlefty — the same order RS_GeoReference emits. The format is
+ 'GDAL' (default) or 'ESRI'; in GDAL the upper-left coordinates refer to the
+ corner of the upper-left pixel, while in ESRI they refer to its center. This is
+ metadata-only: raster cell values are not resampled.
+kernels:
+ - returns: raster
+ args:
+ - raster
+ - name: georeference
+ type: string
+ description: >
+ Six whitespace-separated numbers — scalex, skewy, skewx, scaley,
+ upperleftx, upperlefty.
+ - returns: raster
+ args:
+ - raster
+ - name: georeference
+ type: string
+ description: >
+ Six whitespace-separated numbers — scalex, skewy, skewx, scaley,
+ upperleftx, upperlefty.
+ - name: format
+ type: string
+ description: >
+ Coordinate convention for the upper-left values: 'GDAL' (default; alias
+ 'PIXEL') places them at the pixel corner, 'ESRI' (alias 'NODE') at the
+ pixel center. The center convention ('ESRI'/'NODE') is rejected for
+ skewed (rotated) rasters, where the half-pixel shift would be inexact.
+---
+
+## Examples
+
+```sql
+SELECT RS_GeoReference(RS_SetGeoReference(RS_Example(), '2 0 0 -3 100 200'));
+```
+
+```sql
+SELECT RS_GeoReference(RS_SetGeoReference(RS_Example(), '2 0 0 -3 101 198.5', 'ESRI'));
+```
diff --git a/python/sedonadb/tests/functions/test_raster_functions.py b/python/sedonadb/tests/functions/test_raster_functions.py
index 37640bcf8..4e91b1330 100644
--- a/python/sedonadb/tests/functions/test_raster_functions.py
+++ b/python/sedonadb/tests/functions/test_raster_functions.py
@@ -222,3 +222,49 @@ def test_rs_value_matches_rasterio(con):
con.drop_view(view)
assert got == pytest.approx(expected)
+
+
+def test_rs_setgeoreference_roundtrips_with_getter():
+ # RS_GeoReference emits scaleX, skewY, skewX, scaleY, upperLeftX, upperLeftY;
+ # RS_SetGeoReference accepts the same six values back (GDAL order).
+ eng = SedonaDB()
+ eng.assert_query_result(
+ "SELECT RS_GeoReference(RS_SetGeoReference(RS_Example(), '2 0 0 -3 100 200'))",
+ "2.0000000000\n0.0000000000\n0.0000000000\n-3.0000000000\n100.0000000000\n200.0000000000",
+ )
+
+
+def test_rs_setgeoreference_esri_shifts_to_corner():
+ # ESRI upper-left is the pixel center; the stored (GDAL) upper-left is the
+ # corner: 101 - 2*0.5 = 100 and 198.5 - (-3)*0.5 = 200.
+ eng = SedonaDB()
+ eng.assert_query_result(
+ "SELECT RS_GeoReference(RS_SetGeoReference(RS_Example(), '2 0 0 -3 101 198.5', 'ESRI'))",
+ "2.0000000000\n0.0000000000\n0.0000000000\n-3.0000000000\n100.0000000000\n200.0000000000",
+ )
+
+
+@pytest.mark.parametrize(
+ ("expr", "expected"),
+ [
+ # Three-arg form targets a specific band; read it back with the getter.
+ ("RS_BandNoDataValue(RS_SetBandNoDataValue(RS_Example(), 1, 0), 1)", 0.0),
+ ("RS_BandNoDataValue(RS_SetBandNoDataValue(RS_Example(), 2, 255), 2)", 255.0),
+ # A null nodata value yields a null raster, so the getter returns null.
+ (
+ "RS_BandNoDataValue(RS_SetBandNoDataValue(RS_Example(), CAST(NULL AS DOUBLE)), 1)",
+ None,
+ ),
+ ],
+)
+def test_rs_setbandnodatavalue(expr, expected):
+ SedonaDB().assert_query_result(f"SELECT {expr}", expected)
+
+
+def test_rs_setbandnodatavalue_two_arg_requires_single_band():
+ # The 2-arg form is ambiguous on a multiband raster (RS_Example has multiple
+ # bands), so it errors rather than silently setting only band 1.
+ with pytest.raises(Exception, match="specify which band"):
+ SedonaDB().assert_query_result(
+ "SELECT RS_SetBandNoDataValue(RS_Example(), 0)", None
+ )
diff --git a/rust/sedona-raster-functions/src/lib.rs b/rust/sedona-raster-functions/src/lib.rs
index 4de2d5975..85f3f7d9a 100644
--- a/rust/sedona-raster-functions/src/lib.rs
+++ b/rust/sedona-raster-functions/src/lib.rs
@@ -33,6 +33,8 @@ pub mod rs_isempty;
pub mod rs_numbands;
pub mod rs_pixel_functions;
pub mod rs_rastercoordinate;
+pub mod rs_set_band_nodata;
+pub mod rs_set_georeference;
pub mod rs_setsrid;
pub mod rs_size;
pub mod rs_slice;
diff --git a/rust/sedona-raster-functions/src/register.rs b/rust/sedona-raster-functions/src/register.rs
index e3d118da4..95cfc7e61 100644
--- a/rust/sedona-raster-functions/src/register.rs
+++ b/rust/sedona-raster-functions/src/register.rs
@@ -66,6 +66,8 @@ pub fn default_function_set() -> FunctionSet {
crate::rs_rastercoordinate::rs_worldtorastercoord_udf,
crate::rs_rastercoordinate::rs_worldtorastercoordx_udf,
crate::rs_rastercoordinate::rs_worldtorastercoordy_udf,
+ crate::rs_set_band_nodata::rs_set_band_nodata_value_udf,
+ crate::rs_set_georeference::rs_set_georeference_udf,
crate::rs_setsrid::rs_set_crs_udf,
crate::rs_setsrid::rs_set_srid_udf,
crate::rs_size::rs_height_udf,
diff --git a/rust/sedona-raster-functions/src/rs_georeference.rs b/rust/sedona-raster-functions/src/rs_georeference.rs
index bf9b7470b..3af249d4d 100644
--- a/rust/sedona-raster-functions/src/rs_georeference.rs
+++ b/rust/sedona-raster-functions/src/rs_georeference.rs
@@ -46,28 +46,55 @@ pub fn rs_georeference_udf() -> SedonaScalarUDF {
/// [world file](https://en.wikipedia.org/wiki/World_file).
///
/// Both formats output six lines: scalex, skewy, skewx, scaley, upperleftx, upperlefty.
-/// The difference is how the upper-left coordinate is reported:
+/// The difference is how the upper-left coordinate is reported. Shared with the
+/// [`RS_SetGeoReference`](crate::rs_set_georeference) setter so the two agree on
+/// accepted format strings.
+///
+/// The two conventions are the world-file pixel-corner vs pixel-center
+/// distinction, which is the same as the GeoZarr `"pixel"` (cell-area, corner)
+/// vs `"node"` (cell-center) registration — so `"PIXEL"` and `"NODE"` are
+/// accepted as aliases for `GDAL` and `ESRI` respectively.
+///
+/// NOTE: the center shift (`ESRI`/`NODE`) uses `scale * 0.5` and cannot
+/// represent skew, so it is only well-defined for north-up (zero-skew) rasters.
+/// A skewed raster is rejected for the center convention rather than silently
+/// approximated.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum GeoReferenceFormat {
- /// GDAL format: upperleftx and upperlefty are the coordinates of the upper-left corner
- /// of the upper-left pixel.
+pub(crate) enum GeoReferenceFormat {
+ /// GDAL format (alias `PIXEL`): upperleftx and upperlefty are the coordinates of
+ /// the upper-left corner of the upper-left pixel.
Gdal,
- /// ESRI format: upperleftx and upperlefty are shifted to the center of the upper-left
- /// pixel, i.e. `upperleftx + scalex * 0.5` and `upperlefty + scaley * 0.5`.
+ /// ESRI format (alias `NODE`): upperleftx and upperlefty are shifted to the center
+ /// of the upper-left pixel, i.e. `upperleftx + scalex * 0.5` and `upperlefty + scaley * 0.5`.
Esri,
}
impl GeoReferenceFormat {
- fn from_str(s: &str) -> Result<Self> {
+ pub(crate) fn from_str(s: &str) -> Result<Self> {
match s.to_uppercase().as_str() {
- "GDAL" => Ok(GeoReferenceFormat::Gdal),
- "ESRI" => Ok(GeoReferenceFormat::Esri),
+ "GDAL" | "PIXEL" => Ok(GeoReferenceFormat::Gdal),
+ "ESRI" | "NODE" => Ok(GeoReferenceFormat::Esri),
_ => Err(DataFusionError::Execution(format!(
- "Invalid GeoReference format '{}'. Supported formats are 'GDAL' and 'ESRI'.",
+ "Invalid GeoReference format '{}'. Supported formats are \
+ 'GDAL' (alias 'PIXEL') and 'ESRI' (alias 'NODE').",
s
))),
}
}
+
+ /// Error if this is the center convention (`ESRI`/`NODE`) applied to a
+ /// skewed raster: the pixel-center shift uses only `scale` and would be
+ /// inexact in the presence of skew, so we reject rather than approximate.
+ pub(crate) fn reject_skew(&self, skew_x: f64, skew_y: f64) -> Result<()> {
+ if *self == GeoReferenceFormat::Esri && (skew_x != 0.0 || skew_y != 0.0) {
+ return Err(DataFusionError::Execution(
+ "ESRI/NODE (pixel-center) georeference is not supported for skewed (rotated) \
+ rasters because the center shift would be inexact; use 'GDAL'/'PIXEL' instead."
+ .to_string(),
+ ));
+ }
+ Ok(())
+ }
}
/// Estimated bytes per georeference string for StringBuilder preallocation.
@@ -174,6 +201,7 @@ fn format_georeference(
)
}
GeoReferenceFormat::Esri => {
+ format.reject_skew(skew_x, skew_y)?;
let esri_upper_left_x = upper_left_x + scale_x * 0.5;
let esri_upper_left_y = upper_left_y + scale_y * 0.5;
format!(
@@ -240,14 +268,15 @@ mod tests {
let udf: ScalarUDF = rs_georeference_udf().into();
let tester = ScalarUdfTester::new(udf, vec![RASTER, SedonaType::Arrow(DataType::Utf8)]);
+ // Only the index-0 test raster is north-up; the center (ESRI) convention
+ // requires that (skewed rasters are rejected — see the test below).
let expected: Arc<dyn Array> = Arc::new(StringArray::from(vec![
Some("0.1000000000\n0.0000000000\n0.0000000000\n-0.2000000000\n1.0500000000\n1.9000000000"),
None,
- Some("0.2000000000\n0.0800000000\n0.0600000000\n-0.4000000000\n3.1000000000\n3.8000000000"),
]));
- for format in ["ESRI", "esri"] {
- let rasters = generate_test_rasters(3, Some(1)).unwrap();
+ for format in ["ESRI", "esri", "NODE", "node"] {
+ let rasters = generate_test_rasters(2, Some(1)).unwrap();
let result = tester
.invoke_array_scalar(Arc::new(rasters), format)
.unwrap();
@@ -255,6 +284,21 @@ mod tests {
}
}
+ #[test]
+ fn udf_georeference_esri_skewed_errors() {
+ // The ESRI/NODE center shift can't represent skew, so it's rejected for a
+ // skewed raster rather than silently approximated. Test raster index 2 is
+ // skewed (skew scales with the generator index).
+ let udf: ScalarUDF = rs_georeference_udf().into();
+ let tester = ScalarUdfTester::new(udf, vec![RASTER, SedonaType::Arrow(DataType::Utf8)]);
+ let rasters = generate_test_rasters(3, Some(1)).unwrap();
+ let err = tester
+ .invoke_array_scalar(Arc::new(rasters), "ESRI")
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("skewed"), "unexpected error: {err}");
+ }
+
#[test]
fn udf_georeference_null_scalar() {
let udf: ScalarUDF = rs_georeference_udf().into();
@@ -272,24 +316,24 @@ mod tests {
let rasters = generate_test_rasters(4, Some(1)).unwrap();
let formats = Arc::new(StringArray::from(vec![
- Some("GDAL"), // explicit GDAL
+ Some("ESRI"), // explicit ESRI on the north-up index-0 raster
Some("ESRI"), // won't matter since raster 1 is null
None, // null format -> NULL output
- Some("ESRI"), // explicit ESRI
+ Some("GDAL"), // explicit GDAL (raster 3 is skewed; ESRI would be rejected)
]));
let result = tester
.invoke_arrays(vec![Arc::new(rasters), formats])
.unwrap();
let expected: Arc<dyn Array> = Arc::new(StringArray::from(vec![
- // explicit GDAL
- Some("0.1000000000\n0.0000000000\n0.0000000000\n-0.2000000000\n1.0000000000\n2.0000000000"),
+ // explicit ESRI (north-up): upper-left shifted to pixel center
+ Some("0.1000000000\n0.0000000000\n0.0000000000\n-0.2000000000\n1.0500000000\n1.9000000000"),
// null raster
None,
// null format -> NULL output
None,
- // explicit ESRI
- Some("0.3000000000\n0.1200000000\n0.0900000000\n-0.6000000000\n4.1500000000\n4.7000000000"),
+ // explicit GDAL on a skewed raster (GDAL has no center shift)
+ Some("0.3000000000\n0.1200000000\n0.0900000000\n-0.6000000000\n4.0000000000\n5.0000000000"),
]));
assert_array_equal(&result, &expected);
}
diff --git a/rust/sedona-raster-functions/src/rs_set_band_nodata.rs b/rust/sedona-raster-functions/src/rs_set_band_nodata.rs
new file mode 100644
index 000000000..c54c1ce37
--- /dev/null
+++ b/rust/sedona-raster-functions/src/rs_set_band_nodata.rs
@@ -0,0 +1,322 @@
+// 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_SetBandNoDataValue` — set a band's nodata sentinel.
+//!
+//! ```text
+//! RS_SetBandNoDataValue(raster, nodata) -> Raster -- single-band rasters only
+//! RS_SetBandNoDataValue(raster, band, nodata) -> Raster
+//! ```
+//!
+//! The setter companion to the `RS_BandNoDataValue` getter. `nodata` is a double
+//! packed into the band's native data type. A null raster, band, or nodata value
+//! yields a null raster (matching `RS_SetCRS`/`RS_SetSRID`).
+//!
+//! An out-of-range band index is an error — unlike the getter, which returns
+//! NULL for a missing band. The asymmetry is deliberate: this op rewrites the
+//! whole raster, so silently nulling it on a typo'd band index would lose data,
+//! whereas the getter's NULL is a harmless scalar miss.
+//!
+//! `nodata` is taken as `f64`, so an integer sentinel beyond 2^53 cannot be
+//! represented exactly; pass nodata within `f64`'s exact-integer range.
+//!
+//! The raster is rebuilt with [`BandRef::copy_into`], which carries each band's
+//! pixel data over by sharing the backing buffers (zero-copy) — only the
+//! addressed band's nodata is overridden.
+
+use std::sync::Arc;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::{Float64Type, Int64Type};
+use arrow_array::Array;
+use arrow_schema::DataType;
+use datafusion_common::error::Result;
+use datafusion_common::{arrow_datafusion_err, exec_err};
+use datafusion_expr::{ColumnarValue, Volatility};
+use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF};
+use sedona_raster::builder::{RasterBuilder, RasterOverrides};
+use sedona_raster::traits::{nodata_f64_to_bytes, BandOverrides, RasterRef};
+use sedona_schema::datatypes::SedonaType;
+use sedona_schema::matchers::ArgMatcher;
+
+use crate::executor::RasterExecutor;
+
+/// RS_SetBandNoDataValue() scalar UDF implementation
+pub fn rs_set_band_nodata_value_udf() -> SedonaScalarUDF {
+ SedonaScalarUDF::new(
+ "rs_setbandnodatavalue",
+ vec![
+ Arc::new(RsSetBandNoDataValue { with_band: false }),
+ Arc::new(RsSetBandNoDataValue { with_band: true }),
+ ],
+ Volatility::Immutable,
+ )
+}
+
+#[derive(Debug)]
+struct RsSetBandNoDataValue {
+ with_band: bool,
+}
+
+impl SedonaScalarKernel for RsSetBandNoDataValue {
+ fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+ let mut matchers = vec![ArgMatcher::is_raster()];
+ if self.with_band {
+ matchers.push(ArgMatcher::is_integer());
+ }
+ matchers.push(ArgMatcher::is_numeric());
+ let matcher = ArgMatcher::new(matchers, SedonaType::Raster);
+ matcher.match_args(args)
+ }
+
+ fn invoke_batch(
+ &self,
+ arg_types: &[SedonaType],
+ args: &[ColumnarValue],
+ ) -> Result<ColumnarValue> {
+ let executor = RasterExecutor::new(arg_types, args);
+ let n = executor.num_iterations();
+
+ // The band column (1-based; absent for the 2-arg form, where the band is
+ // resolved in `set_band_nodata`) and the nodata value column, read inline
+ // per row.
+ let band_array = if self.with_band {
+ Some(
+ args[1]
+ .clone()
+ .cast_to(&DataType::Int64, None)?
+ .into_array(n)?,
+ )
+ } else {
+ None
+ };
+ let band_values = band_array.as_ref().map(|a| a.as_primitive::<Int64Type>());
+
+ // nodata is taken as f64. An integer sentinel is cast losslessly here so
+ // long as it is within f64's exact-integer range (±2^53); a larger
+ // i64/u64 would lose precision in this cast. Whether the value fits the
+ // *band's* data type is validated later by `nodata_f64_to_bytes`, which
+ // errors rather than truncating. (Dedicated integer kernels could be
+ // registered if exact large-integer sentinels are ever needed.)
+ let value_arg = if self.with_band { &args[2] } else { &args[1] };
+ let value_array = value_arg
+ .clone()
+ .cast_to(&DataType::Float64, None)?
+ .into_array(n)?;
+ let value_values = value_array.as_primitive::<Float64Type>();
+
+ let mut builder = RasterBuilder::new(n);
+ executor.execute_raster_void(|i, raster_opt| {
+ let null_out =
+ |b: &mut RasterBuilder| b.append_null().map_err(|e| arrow_datafusion_err!(e));
+
+ // A null raster, band, or value yields a null raster.
+ let Some(raster) = raster_opt else {
+ return null_out(&mut builder);
+ };
+ let band = match band_values {
+ Some(bands) if bands.is_null(i) => return null_out(&mut builder),
+ Some(bands) => Some(bands.value(i)),
+ None => None,
+ };
+ if value_values.is_null(i) {
+ return null_out(&mut builder);
+ }
+ set_band_nodata(&mut builder, raster, band, value_values.value(i))
+ })?;
+
+ executor.finish(Arc::new(builder.finish()?))
+ }
+}
+
+/// Copy `raster` into `builder`, overriding the addressed (1-based) band's
+/// nodata with `value` packed into that band's data type. Every other band is
+/// copied with its data shared and metadata inherited.
+///
+/// `band` is `None` for the 2-argument form (no band given): it defaults to band
+/// 1 only when the raster is single-band, and errors on a multiband raster so a
+/// caller can't silently set nodata on just band 1.
+fn set_band_nodata(
+ builder: &mut RasterBuilder,
+ raster: &dyn RasterRef,
+ band: Option<i64>,
+ value: f64,
+) -> Result<()> {
+ let num_bands = raster.num_bands();
+ let band = match band {
+ Some(band) => band,
+ None if num_bands == 1 => 1,
+ None => {
+ return exec_err!(
+ "RS_SetBandNoDataValue: raster has {num_bands} bands; specify which band to set \
+ (the 2-argument form is only allowed for a single-band raster)"
+ )
+ }
+ };
+ if band < 1 || band as usize > num_bands {
+ return exec_err!(
+ "RS_SetBandNoDataValue: band {band} out of range (raster has {num_bands} band(s))"
+ );
+ }
+
+ // Copy the raster header (transform/dims/crs) verbatim; we rebuild the bands
+ // below so we can override the addressed band's nodata.
+ builder.start_raster_from(raster, RasterOverrides::default())?;
+
+ for band_idx in 0..num_bands {
+ let band_ref = raster.band(band_idx)?;
+ // Override the nodata only on the addressed band; others inherit.
+ let nodata_bytes = if band_idx + 1 == band as usize {
+ Some(nodata_f64_to_bytes(value, &band_ref.data_type())?)
+ } else {
+ None
+ };
+ band_ref.copy_into(
+ builder,
+ BandOverrides {
+ nodata: nodata_bytes.as_deref(),
+ ..Default::default()
+ },
+ )?;
+ builder.finish_band()?;
+ }
+
+ builder.finish_raster()?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use arrow_schema::DataType;
+ use datafusion_common::ScalarValue;
+ use datafusion_expr::ScalarUDF;
+ use sedona_schema::datatypes::RASTER;
+ use sedona_testing::raster_spec::{assert_rasters_equal, RasterSpec};
+ use sedona_testing::rasters::generate_test_rasters;
+ use sedona_testing::testers::ScalarUdfTester;
+
+ /// Two UInt8 bands, no nodata.
+ fn two_band() -> RasterSpec {
+ RasterSpec::d2(2, 1)
+ .band_values(&[1u8, 2])
+ .band_values(&[3u8, 4])
+ }
+
+ fn tester_2arg() -> ScalarUdfTester {
+ let udf: ScalarUDF = rs_set_band_nodata_value_udf().into();
+ ScalarUdfTester::new(udf, vec![RASTER, SedonaType::Arrow(DataType::Float64)])
+ }
+
+ fn tester_3arg() -> ScalarUdfTester {
+ let udf: ScalarUDF = rs_set_band_nodata_value_udf().into();
+ ScalarUdfTester::new(
+ udf,
+ vec![
+ RASTER,
+ SedonaType::Arrow(DataType::Int32),
+ SedonaType::Arrow(DataType::Float64),
+ ],
+ )
+ }
+
+ #[test]
+ fn udf_metadata() {
+ let udf: ScalarUDF = rs_set_band_nodata_value_udf().into();
+ assert_eq!(udf.name(), "rs_setbandnodatavalue");
+ }
+
+ #[test]
+ fn sets_default_band_nodata_preserving_everything_else() {
+ // Two-arg form sets the sole band's nodata on a single-band raster;
+ // pixels, transform, CRS are all preserved (the whole-raster comparison
+ // proves it).
+ let tester = tester_2arg();
+ tester.assert_return_type(RASTER);
+
+ let one_band = RasterSpec::d2(2, 1).band_values(&[1u8, 2]);
+ let result = tester
+ .invoke_array_scalar(Arc::new(one_band.build()), 5.0)
+ .unwrap();
+ let expected = RasterSpec::d2(2, 1).band_values(&[1u8, 2]).nodata(5u8);
+ assert_rasters_equal(&result, &[Some(expected)]);
+ }
+
+ #[test]
+ fn two_arg_form_on_multiband_errors() {
+ // The 2-arg form is ambiguous on a multiband raster — require an
+ // explicit band rather than silently setting only band 1.
+ let err = tester_2arg()
+ .invoke_array_scalar(Arc::new(two_band().build()), 5.0)
+ .unwrap_err()
+ .to_string();
+ assert!(
+ err.contains("specify which band"),
+ "unexpected error: {err}"
+ );
+ }
+
+ #[test]
+ fn sets_specific_band_nodata() {
+ let result = tester_3arg()
+ .invoke_array_scalar_scalar(Arc::new(two_band().build()), 2_i32, 9.0)
+ .unwrap();
+ let expected = RasterSpec::d2(2, 1)
+ .band_values(&[1u8, 2])
+ .band_values(&[3u8, 4])
+ .nodata(9u8);
+ assert_rasters_equal(&result, &[Some(expected)]);
+ }
+
+ #[test]
+ fn null_value_nulls_raster() {
+ let result = tester_2arg()
+ .invoke_array_scalar(Arc::new(two_band().build()), ScalarValue::Float64(None))
+ .unwrap();
+ assert_rasters_equal(&result, &[None]);
+ }
+
+ #[test]
+ fn null_raster_stays_null() {
+ let rasters = generate_test_rasters(1, Some(0)).unwrap();
+ let result = tester_2arg()
+ .invoke_array_scalar(Arc::new(rasters), 1.0)
+ .unwrap();
+ assert_rasters_equal(&result, &[None]);
+ }
+
+ #[test]
+ fn band_out_of_range_errors() {
+ let err = tester_3arg()
+ .invoke_array_scalar_scalar(Arc::new(two_band().build()), 5_i32, 1.0)
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("out of range"), "unexpected error: {err}");
+ }
+
+ #[test]
+ fn value_out_of_dtype_range_errors() {
+ // 300 doesn't fit in a UInt8 band. Use a single-band raster so the 2-arg
+ // form resolves a band and reaches the dtype range check.
+ let one_band = RasterSpec::d2(2, 1).band_values(&[1u8, 2]);
+ let err = tester_2arg()
+ .invoke_array_scalar(Arc::new(one_band.build()), 300.0)
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("UInt8"), "unexpected error: {err}");
+ }
+}
diff --git a/rust/sedona-raster-functions/src/rs_set_georeference.rs b/rust/sedona-raster-functions/src/rs_set_georeference.rs
new file mode 100644
index 000000000..b67ddf029
--- /dev/null
+++ b/rust/sedona-raster-functions/src/rs_set_georeference.rs
@@ -0,0 +1,343 @@
+// 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_SetGeoReference` — set a raster's affine geotransform.
+//!
+//! ```text
+//! RS_SetGeoReference(raster, georef) -> Raster -- GDAL format
+//! RS_SetGeoReference(raster, georef, format) -> Raster
+//! ```
+//!
+//! The setter companion to [`rs_georeference`](crate::rs_georeference): `georef`
+//! is a world-file string of six whitespace-separated numbers in the same order
+//! the getter emits — `scaleX skewY skewX scaleY upperLeftX upperLeftY`. The
+//! `format` is `GDAL` (default, alias `PIXEL`) or `ESRI` (alias `NODE`); in the
+//! ESRI/center convention the upper-left coordinates refer to the *center* of
+//! the upper-left pixel and are shifted back to the pixel corner on the way in
+//! (rejected for skewed rasters, where the shift would be inexact).
+//!
+//! The raster is rebuilt with [`RasterBuilder::copy_raster_from`] overriding the
+//! transform; each band's pixel buffers are shared zero-copy, and the CRS is
+//! carried over unchanged.
+
+use std::sync::Arc;
+
+use arrow_array::Array;
+use arrow_schema::DataType;
+use datafusion_common::cast::as_string_array;
+use datafusion_common::error::Result;
+use datafusion_common::{arrow_datafusion_err, exec_datafusion_err, exec_err};
+use datafusion_expr::{ColumnarValue, Volatility};
+use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF};
+use sedona_raster::builder::{RasterBuilder, RasterOverrides};
+use sedona_schema::datatypes::SedonaType;
+use sedona_schema::matchers::ArgMatcher;
+
+use crate::executor::RasterExecutor;
+// Shared with the getter so the two agree on accepted format strings and the
+// ESRI center-shift convention (see RS_GeoReference).
+use crate::rs_georeference::GeoReferenceFormat;
+
+/// RS_SetGeoReference() scalar UDF implementation
+pub fn rs_set_georeference_udf() -> SedonaScalarUDF {
+ SedonaScalarUDF::new(
+ "rs_setgeoreference",
+ vec![
+ Arc::new(RsSetGeoReference { with_format: false }),
+ Arc::new(RsSetGeoReference { with_format: true }),
+ ],
+ Volatility::Immutable,
+ )
+}
+
+#[derive(Debug)]
+struct RsSetGeoReference {
+ with_format: bool,
+}
+
+impl SedonaScalarKernel for RsSetGeoReference {
+ fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+ let mut matchers = vec![ArgMatcher::is_raster(), ArgMatcher::is_string()];
+ if self.with_format {
+ matchers.push(ArgMatcher::is_string());
+ }
+ let matcher = ArgMatcher::new(matchers, SedonaType::Raster);
+ matcher.match_args(args)
+ }
+
+ fn invoke_batch(
+ &self,
+ arg_types: &[SedonaType],
+ args: &[ColumnarValue],
+ ) -> Result<ColumnarValue> {
+ let executor = RasterExecutor::new(arg_types, args);
+ let n = executor.num_iterations();
+
+ // Expand the georeference string (and optional format) to row arrays.
+ let georef_array = args[1]
+ .clone()
+ .cast_to(&DataType::Utf8, None)?
+ .into_array(n)?;
+ let georef_array = as_string_array(&georef_array)?;
+
+ let format_array = if self.with_format {
+ Some(
+ args[2]
+ .clone()
+ .cast_to(&DataType::Utf8, None)?
+ .into_array(n)?,
+ )
+ } else {
+ None
+ };
+ let format_array = format_array
+ .as_ref()
+ .map(|a| as_string_array(a))
+ .transpose()?;
+
+ let mut builder = RasterBuilder::new(n);
+ executor.execute_raster_void(|i, raster_opt| {
+ let null_out =
+ |b: &mut RasterBuilder| b.append_null().map_err(|e| arrow_datafusion_err!(e));
+
+ // A null georef or format is a null *input* and yields a null raster
+ // (matching RS_SetCRS); check those first so a null-driven row never
+ // raises an error.
+ if georef_array.is_null(i) {
+ return null_out(&mut builder);
+ }
+ let format = match &format_array {
+ Some(fmt) if fmt.is_null(i) => return null_out(&mut builder),
+ Some(fmt) => GeoReferenceFormat::from_str(fmt.value(i))?,
+ None => GeoReferenceFormat::Gdal,
+ };
+
+ // Parse and validate the georef up front — before the null-raster
+ // check — so an invalid (non-null) georef errors for every row,
+ // rather than being masked on the rows that happen to align with a
+ // null raster.
+ let transform = parse_georeference(georef_array.value(i), format)?;
+
+ let Some(raster) = raster_opt else {
+ return null_out(&mut builder);
+ };
+ builder
+ .copy_raster_from(
+ raster,
+ RasterOverrides {
+ transform: Some(transform),
+ },
+ )
+ .map_err(|e| arrow_datafusion_err!(e))
+ })?;
+
+ executor.finish(Arc::new(
+ builder.finish().map_err(|e| arrow_datafusion_err!(e))?,
+ ))
+ }
+}
+
+/// Parse a world-file georeference string into a GDAL-order transform
+/// `[upper_left_x, scale_x, skew_x, upper_left_y, skew_y, scale_y]`.
+///
+/// The input lists six whitespace-separated numbers in world-file order
+/// (`scaleX skewY skewX scaleY upperLeftX upperLeftY`); for ESRI the upper-left
+/// coordinates are pixel-center and shifted back to the corner.
+///
+/// The stringly-typed six-value format is a bit unwieldy; a future dedicated
+/// affine-matrix type (cf. `sedona_raster::affine_transformation::AffineMatrix`,
+/// which could also back `ST_Affine`) would be a cleaner input.
+fn parse_georeference(georef: &str, format: GeoReferenceFormat) -> Result<[f64; 6]> {
+ let values: Vec<f64> = georef
+ .split_whitespace()
+ .map(|token| {
+ token
+ .parse::<f64>()
+ .map_err(|_| exec_datafusion_err!("RS_SetGeoReference: invalid number '{token}'"))
+ })
+ .collect::<Result<_>>()?;
+
+ if values.len() != 6 {
+ return exec_err!(
+ "RS_SetGeoReference: expected 6 whitespace-separated values \
+ (scaleX skewY skewX scaleY upperLeftX upperLeftY), got {}",
+ values.len()
+ );
+ }
+
+ let [scale_x, skew_y, skew_x, scale_y, mut upper_left_x, mut upper_left_y] = [
+ values[0], values[1], values[2], values[3], values[4], values[5],
+ ];
+
+ if format == GeoReferenceFormat::Esri {
+ // ESRI reports the upper-left *pixel center*; shift to the corner. The
+ // shift can't represent skew, so a skewed raster is rejected rather than
+ // approximated (shared with the getter via reject_skew).
+ format.reject_skew(skew_x, skew_y)?;
+ upper_left_x -= scale_x * 0.5;
+ upper_left_y -= scale_y * 0.5;
+ }
+
+ // GDAL geotransform order.
+ Ok([upper_left_x, scale_x, skew_x, upper_left_y, skew_y, scale_y])
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use arrow_array::ArrayRef;
+ use datafusion_common::ScalarValue;
+ use datafusion_expr::ScalarUDF;
+ use sedona_schema::datatypes::RASTER;
+ use sedona_testing::raster_spec::{assert_rasters_equal, raster_array, RasterSpec};
+ use sedona_testing::testers::ScalarUdfTester;
+
+ /// A 2x2 raster with a CRS — so the comparisons confirm the CRS (and pixels)
+ /// survive the transform swap.
+ fn base() -> RasterSpec {
+ RasterSpec::d2(2, 2)
+ .band_values(&[1u8, 2, 3, 4])
+ .crs(Some("OGC:CRS84"))
+ }
+
+ fn tester_2arg() -> ScalarUdfTester {
+ let udf: ScalarUDF = rs_set_georeference_udf().into();
+ ScalarUdfTester::new(udf, vec![RASTER, SedonaType::Arrow(DataType::Utf8)])
+ }
+
+ fn tester_3arg() -> ScalarUdfTester {
+ let udf: ScalarUDF = rs_set_georeference_udf().into();
+ ScalarUdfTester::new(
+ udf,
+ vec![
+ RASTER,
+ SedonaType::Arrow(DataType::Utf8),
+ SedonaType::Arrow(DataType::Utf8),
+ ],
+ )
+ }
+
+ #[test]
+ fn udf_metadata() {
+ let udf: ScalarUDF = rs_set_georeference_udf().into();
+ assert_eq!(udf.name(), "rs_setgeoreference");
+ }
+
+ #[test]
+ fn sets_transform_preserving_crs_and_bands() {
+ // World-file order: scaleX skewY skewX scaleY upperLeftX upperLeftY.
+ let tester = tester_2arg();
+ tester.assert_return_type(RASTER);
+
+ let result = tester
+ .invoke_array_scalar(Arc::new(base().build()), "2 0.5 0.25 -3 100 200")
+ .unwrap();
+ // GDAL-order transform: [upperLeftX, scaleX, skewX, upperLeftY, skewY, scaleY].
+ // CRS and pixels must be untouched — assert_rasters_equal checks all of it.
+ let expected = base().transform([100.0, 2.0, 0.25, 200.0, 0.5, -3.0]);
+ assert_rasters_equal(&result, &[Some(expected)]);
+ }
+
+ #[test]
+ fn esri_shifts_upper_left_to_corner() {
+ // ESRI upper-left is the pixel center; the stored (GDAL) corner is
+ // center - scale*0.5: x = 101 - 2*0.5 = 100, y = 198.5 - (-3)*0.5 = 200.
+ let result = tester_3arg()
+ .invoke_array_scalar_scalar(Arc::new(base().build()), "2 0 0 -3 101 198.5", "ESRI")
+ .unwrap();
+ let expected = base().transform([100.0, 2.0, 0.0, 200.0, 0.0, -3.0]);
+ assert_rasters_equal(&result, &[Some(expected)]);
+ }
+
+ #[test]
+ fn null_georef_nulls_raster() {
+ let result = tester_2arg()
+ .invoke_array_scalar(Arc::new(base().build()), ScalarValue::Utf8(None))
+ .unwrap();
+ assert_rasters_equal(&result, &[None]);
+ }
+
+ #[test]
+ fn invalid_georef_errors_even_for_null_raster() {
+ // A malformed (non-null) georef errors for the whole batch even when its
+ // row's raster is null — invalid georeferences are always reported, not
+ // masked by a null raster (only a null *georef* yields a null raster).
+ let rasters = raster_array([None, Some(base())]);
+ let georefs: ArrayRef = Arc::new(arrow_array::StringArray::from(vec![
+ Some("not a georeference"),
+ Some("2 0 0 -3 100 200"),
+ ]));
+
+ let err = tester_2arg()
+ .invoke_array_array(Arc::new(rasters), georefs)
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("invalid number"), "unexpected error: {err}");
+ }
+
+ #[test]
+ fn esri_skewed_raster_errors() {
+ // ESRI/center georeference can't represent skew; reject rather than
+ // silently approximate. World-file order: scaleX skewY skewX scaleY ...
+ let err = tester_3arg()
+ .invoke_array_scalar_scalar(Arc::new(base().build()), "2 0.5 0.25 -3 100 200", "ESRI")
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("skewed"), "unexpected error: {err}");
+ }
+
+ #[test]
+ fn node_alias_sets_transform_like_esri() {
+ // "NODE" is an alias for the ESRI/center convention.
+ let result = tester_3arg()
+ .invoke_array_scalar_scalar(Arc::new(base().build()), "2 0 0 -3 101 198.5", "NODE")
+ .unwrap();
+ let expected = base().transform([100.0, 2.0, 0.0, 200.0, 0.0, -3.0]);
+ assert_rasters_equal(&result, &[Some(expected)]);
+ }
+
+ #[test]
+ fn wrong_value_count_errors() {
+ let err = tester_2arg()
+ .invoke_array_scalar(Arc::new(base().build()), "1 2 3")
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("6"), "unexpected error: {err}");
+ }
+
+ #[test]
+ fn invalid_format_errors() {
+ let err = tester_3arg()
+ .invoke_array_scalar_scalar(Arc::new(base().build()), "2 0 0 -3 100 200", "NOPE")
+ .unwrap_err()
+ .to_string();
+ assert!(
+ err.contains("GeoReference format"),
+ "unexpected error: {err}"
+ );
+ }
+
+ #[test]
+ fn null_georef_with_invalid_format_is_null_not_error() {
+ // A null georef short-circuits to a null raster before the (invalid)
+ // format string is validated — a null-driving input never errors.
+ let result = tester_3arg()
+ .invoke_array_scalar_scalar(Arc::new(base().build()), ScalarValue::Utf8(None), "NOPE")
+ .unwrap();
+ assert_rasters_equal(&result, &[None]);
+ }
+}
diff --git a/rust/sedona-raster/src/builder.rs b/rust/sedona-raster/src/builder.rs
index d2dd5d175..90f6c5d52 100644
--- a/rust/sedona-raster/src/builder.rs
+++ b/rust/sedona-raster/src/builder.rs
@@ -29,9 +29,18 @@ use std::sync::Arc;
use sedona_schema::raster::{BandDataType, RasterSchema};
-use crate::traits::{BandMetadata, MetadataRef};
+use crate::traits::{BandMetadata, BandOverrides, MetadataRef, RasterRef};
use crate::view_entries::{ViewEntries, ViewEntry};
+/// Raster-level metadata overrides for [`RasterBuilder::start_raster_from`] and
+/// [`RasterBuilder::copy_raster_from`]. A `None` field inherits the source
+/// raster's value. The band-level analog is [`BandOverrides`].
+#[derive(Debug, Default, Clone)]
+pub struct RasterOverrides {
+ /// Override the 6-element GDAL geotransform; `None` inherits the source's.
+ pub transform: Option<[f64; 6]>,
+}
+
/// Maximum byte length of an inline `BinaryViewArray` view. Views this short
/// store their bytes in the 16-byte view itself; longer views reference a data
/// block by `(buffer_index, offset)`. Fixed by the Arrow columnar format spec.
@@ -267,6 +276,53 @@ impl RasterBuilder {
Ok(())
}
+ /// Start a raster from `source`, copying its geotransform, spatial
+ /// dims/shape, and CRS — with [`RasterOverrides`] applied — but **not** its
+ /// bands. The caller adds bands (e.g. via
+ /// [`BandRef::copy_into`](crate::traits::BandRef::copy_into)) and then calls
+ /// [`finish_raster`](Self::finish_raster). Use this when bands need
+ /// per-band changes; see [`copy_raster_from`](Self::copy_raster_from) to
+ /// copy a raster whole.
+ pub fn start_raster_from(
+ &mut self,
+ source: &dyn RasterRef,
+ overrides: RasterOverrides,
+ ) -> Result<(), ArrowError> {
+ let transform: [f64; 6] = match overrides.transform {
+ Some(transform) => transform,
+ None => source.transform().try_into().map_err(|_| {
+ ArrowError::InvalidArgumentError("raster transform is not 6 elements".to_string())
+ })?,
+ };
+ let spatial_dims = source.spatial_dims();
+ self.start_raster_nd(
+ &transform,
+ &spatial_dims,
+ source.spatial_shape(),
+ source.crs(),
+ )
+ }
+
+ /// Copy `source` whole: its metadata (with [`RasterOverrides`] applied) and
+ /// every band, each derived via
+ /// [`BandRef::copy_into`](crate::traits::BandRef::copy_into) so pixel buffers
+ /// are shared zero-copy. Finishes the raster — no further calls are needed
+ /// for this row.
+ pub fn copy_raster_from(
+ &mut self,
+ source: &dyn RasterRef,
+ overrides: RasterOverrides,
+ ) -> Result<(), ArrowError> {
+ self.start_raster_from(source, overrides)?;
+ for band_idx in 0..source.num_bands() {
+ source
+ .band(band_idx)?
+ .copy_into(self, BandOverrides::default())?;
+ self.finish_band()?;
+ }
+ self.finish_raster()
+ }
+
/// Convenience: start a 2-D raster with positional geotransform parameters.
/// Sets `spatial_dims=["x","y"]` and `spatial_shape=[width, height]` and
/// builds the 6-element GDAL transform internally. The N-D entry point is
@@ -1107,6 +1163,38 @@ mod tests {
assert!(result.is_err(), "Band number 2 should be out of range");
}
+ #[test]
+ fn copy_raster_from_overrides_transform_and_preserves_bands() {
+ use sedona_testing::raster_spec::{assert_rasters_equal, RasterSpec};
+
+ // Source: a CRS, a nodata sentinel, and pixel values to preserve.
+ let source = RasterSpec::d2(2, 1)
+ .band_values(&[1u8, 2])
+ .nodata(9u8)
+ .crs(Some("OGC:CRS84"))
+ .build();
+ let source = RasterStructArray::try_new(&source).unwrap();
+
+ let mut builder = RasterBuilder::new(1);
+ builder
+ .copy_raster_from(
+ &source.get(0).unwrap(),
+ RasterOverrides {
+ transform: Some([100.0, 2.0, 0.0, 200.0, 0.0, -3.0]),
+ },
+ )
+ .unwrap();
+ let out: ArrayRef = Arc::new(builder.finish().unwrap());
+
+ // Only the transform changed; CRS, nodata, and pixels carried over.
+ let expected = RasterSpec::d2(2, 1)
+ .band_values(&[1u8, 2])
+ .nodata(9u8)
+ .crs(Some("OGC:CRS84"))
+ .transform([100.0, 2.0, 0.0, 200.0, 0.0, -3.0]);
+ assert_rasters_equal(&out, &[Some(expected)]);
+ }
+
#[test]
fn test_band_data_types() {
// Create a test raster with bands of different data types
diff --git a/rust/sedona-raster/src/traits.rs b/rust/sedona-raster/src/traits.rs
index 22cfe0b4a..f679ab707 100644
--- a/rust/sedona-raster/src/traits.rs
+++ b/rust/sedona-raster/src/traits.rs
@@ -862,6 +862,65 @@ pub fn nodata_bytes_to_f64_lossless(bytes: &[u8], dt: &BandDataType) -> Result<f
}
}
+/// Pack an `f64` nodata value into the little-endian bytes of a band's data
+/// type — the inverse of [`nodata_bytes_to_f64_lossless`].
+///
+/// Errors when the value can't be represented exactly in `dt`: a non-integral
+/// value for an integer type, a value outside the type's range, or a 64-bit
+/// integer beyond 2^53 (which can't have arrived losslessly through `f64`).
+/// `Float32` is the one lossy case allowed — it rounds to the nearest `f32`, as
+/// any f64 → f32 narrowing does.
+pub fn nodata_f64_to_bytes(value: f64, dt: &BandDataType) -> Result<Vec<u8>, ArrowError> {
+ fn check_integer(value: f64, min: f64, max: f64, dt: &BandDataType) -> Result<(), ArrowError> {
+ if value.fract() != 0.0 || value < min || value > max {
+ return Err(ArrowError::InvalidArgumentError(format!(
+ "nodata value {value} is not a valid {dt:?} value"
+ )));
+ }
+ Ok(())
+ }
+
+ // The largest magnitude an integer can have and still round-trip through f64.
+ const F64_INT_MAX: f64 = (1u64 << 53) as f64;
+
+ Ok(match dt {
+ BandDataType::UInt8 => {
+ check_integer(value, 0.0, u8::MAX as f64, dt)?;
+ (value as u8).to_le_bytes().to_vec()
+ }
+ BandDataType::Int8 => {
+ check_integer(value, i8::MIN as f64, i8::MAX as f64, dt)?;
+ (value as i8).to_le_bytes().to_vec()
+ }
+ BandDataType::UInt16 => {
+ check_integer(value, 0.0, u16::MAX as f64, dt)?;
+ (value as u16).to_le_bytes().to_vec()
+ }
+ BandDataType::Int16 => {
+ check_integer(value, i16::MIN as f64, i16::MAX as f64, dt)?;
+ (value as i16).to_le_bytes().to_vec()
+ }
+ BandDataType::UInt32 => {
+ check_integer(value, 0.0, u32::MAX as f64, dt)?;
+ (value as u32).to_le_bytes().to_vec()
+ }
+ BandDataType::Int32 => {
+ check_integer(value, i32::MIN as f64, i32::MAX as f64, dt)?;
+ (value as i32).to_le_bytes().to_vec()
+ }
+ BandDataType::UInt64 => {
+ check_integer(value, 0.0, F64_INT_MAX, dt)?;
+ (value as u64).to_le_bytes().to_vec()
+ }
+ BandDataType::Int64 => {
+ check_integer(value, -F64_INT_MAX, F64_INT_MAX, dt)?;
+ (value as i64).to_le_bytes().to_vec()
+ }
+ BandDataType::Float32 => (value as f32).to_le_bytes().to_vec(),
+ BandDataType::Float64 => value.to_le_bytes().to_vec(),
+ })
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -872,6 +931,40 @@ mod tests {
assert_eq!(val, 42.0);
}
+ #[test]
+ fn test_nodata_f64_to_bytes_round_trips() {
+ for (dt, value) in [
+ (BandDataType::UInt8, 127.0),
+ (BandDataType::Int8, -2.0),
+ (BandDataType::UInt16, 65535.0),
+ (BandDataType::Int16, -1000.0),
+ (BandDataType::UInt32, 4_000_000_000.0),
+ (BandDataType::Int32, -2_000_000.0),
+ (BandDataType::UInt64, 9_007_199_254_740_992.0), // 2^53
+ (BandDataType::Int64, -9_007_199_254_740_992.0), // -2^53
+ (BandDataType::Float32, -9999.5),
+ (BandDataType::Float64, -9999.0),
+ ] {
+ let bytes = nodata_f64_to_bytes(value, &dt).unwrap();
+ assert_eq!(bytes.len(), dt.byte_size(), "{dt:?}");
+ assert_eq!(
+ nodata_bytes_to_f64_lossless(&bytes, &dt).unwrap(),
+ value,
+ "{dt:?} round-trip"
+ );
+ }
+ }
+
+ #[test]
+ fn test_nodata_f64_to_bytes_rejects_out_of_range() {
+ // Non-integral for an integer type, and out of range.
+ nodata_f64_to_bytes(1.5, &BandDataType::UInt8).unwrap_err();
+ nodata_f64_to_bytes(300.0, &BandDataType::UInt8).unwrap_err();
+ nodata_f64_to_bytes(-1.0, &BandDataType::UInt8).unwrap_err();
+ // Beyond 2^53 can't have arrived losslessly through f64.
+ nodata_f64_to_bytes(1e18, &BandDataType::Int64).unwrap_err();
+ }
+
#[test]
fn test_nodata_bytes_to_f64_int8() {
let val = nodata_bytes_to_f64(&[0xFE], &BandDataType::Int8).unwrap();