From 785e6be259337e8b8902c35edf96c3bab03d78a2 Mon Sep 17 00:00:00 2001 From: Romain Hugonnet Date: Fri, 27 Sep 2024 16:04:37 -0800 Subject: [PATCH] Fix inplace nodata modification --- geoutils/raster/multiraster.py | 6 +++++- tests/test_raster/test_multiraster.py | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/geoutils/raster/multiraster.py b/geoutils/raster/multiraster.py index 73b11769..af7e97b8 100644 --- a/geoutils/raster/multiraster.py +++ b/geoutils/raster/multiraster.py @@ -180,10 +180,14 @@ def stack_rasters( res=reference_raster.res, crs=reference_raster.crs, dtype=reference_raster.data.dtype, - nodata=reference_raster.nodata, + nodata=nodata, resampling=resampling_method, silent=True, ) + # If the georeferenced grid was the same, reproject() will have returned self with a warning (silenced here), + # and we want to copy the raster before modifying its nodata (or it will modify raster inputs of this function) + if reprojected_raster.georeferenced_grid_equal(raster): + reprojected_raster = reprojected_raster.copy() reprojected_raster.set_nodata(nodata) # Optionally calculate difference diff --git a/tests/test_raster/test_multiraster.py b/tests/test_raster/test_multiraster.py index 919b2b58..f93d2741 100644 --- a/tests/test_raster/test_multiraster.py +++ b/tests/test_raster/test_multiraster.py @@ -243,6 +243,10 @@ def test_stack_rasters(self, rasters) -> None: # type: ignore stacked_img = gu.raster.stack_rasters([rasters.img1, rasters.img2], resampling_method="bilinear") assert not np.array_equal(np.unique(stacked_img.data.compressed()), np.array([1, 5])) + # Check input nodata is not modified inplace (issue 609) + new_nodata_ref = rasters.img1.nodata + assert nodata_ref == new_nodata_ref + # Check nodata value output is consistent with reference input if nodata_ref is not None: assert stacked_img.nodata == nodata_ref