|
| 1 | +"""``to_geotiff(pack=True)`` refuses packed values the dtype cannot hold (#3260). |
| 2 | +
|
| 3 | +``_pack`` reverses the unpack transform and casts to the integer dtype |
| 4 | +recorded on ``attrs['mask_and_scale_dtype']``. Before #3260 the cast ran |
| 5 | +unguarded: a finite value whose packed form fell outside the dtype range |
| 6 | +wrapped (40000 -> -25536 in int16) and +/-Inf cast to a platform-defined |
| 7 | +integer, both silently. The guard raises ``ValueError`` instead -- at |
| 8 | +call time for numpy / cupy buffers, from the write's single compute for |
| 9 | +dask backings (same timing as the #3235 NaN guard). |
| 10 | +""" |
| 11 | +import numpy as np |
| 12 | +import pytest |
| 13 | +import xarray as xr |
| 14 | + |
| 15 | +from xrspatial.geotiff import open_geotiff, to_geotiff |
| 16 | +from xrspatial.geotiff._attrs import _pack_guard_int_range |
| 17 | + |
| 18 | +from .._helpers.markers import requires_gpu |
| 19 | + |
| 20 | + |
| 21 | +def _write_scaled_int16(path, *, nodata=None): |
| 22 | + """int16 source with SCALE=0.1 so unpacked values are data * 0.1.""" |
| 23 | + data = np.array([[100, 200], [300, 32000]], dtype=np.int16) |
| 24 | + attrs = { |
| 25 | + "crs": 4326, |
| 26 | + "gdal_metadata": {"SCALE": "0.1", "OFFSET": "0.0"}, |
| 27 | + } |
| 28 | + if nodata is not None: |
| 29 | + attrs["nodata"] = nodata |
| 30 | + da = xr.DataArray( |
| 31 | + data, |
| 32 | + dims=("y", "x"), |
| 33 | + coords={"y": [1.5, 0.5], "x": [0.5, 1.5]}, |
| 34 | + attrs=attrs, |
| 35 | + ) |
| 36 | + to_geotiff(da, str(path), nodata=nodata) |
| 37 | + return str(path) |
| 38 | + |
| 39 | + |
| 40 | +def _unpacked(path, *, gpu=False): |
| 41 | + kwargs = {"unpack": True} |
| 42 | + if gpu: |
| 43 | + kwargs["gpu"] = True |
| 44 | + return open_geotiff(path, **kwargs).copy() |
| 45 | + |
| 46 | + |
| 47 | +# --------------------------------------------------------------------------- |
| 48 | +# Finite overflow wraps in the cast: refused on every backend |
| 49 | +# --------------------------------------------------------------------------- |
| 50 | + |
| 51 | + |
| 52 | +@pytest.mark.parametrize("chunks,gpu", [ |
| 53 | + pytest.param(None, False, id="numpy"), |
| 54 | + pytest.param(1, False, id="dask"), |
| 55 | + pytest.param(None, True, marks=requires_gpu, id="gpu"), |
| 56 | + pytest.param(1, True, marks=requires_gpu, id="dask-gpu"), |
| 57 | +]) |
| 58 | +def test_pack_rejects_finite_overflow(tmp_path, chunks, gpu): |
| 59 | + src = _write_scaled_int16(tmp_path / "src_overflow_3260.tif") |
| 60 | + mod = _unpacked(src, gpu=gpu) |
| 61 | + # Packs to 40000 > int16 max 32767; pre-#3260 this wrapped to -25536. |
| 62 | + mod.data[0, 0] = 4000.0 |
| 63 | + if chunks is not None: |
| 64 | + mod = mod.chunk({"y": chunks}) |
| 65 | + out = str(tmp_path / "out_overflow_3260.tif") |
| 66 | + with pytest.raises(ValueError, match="cannot represent"): |
| 67 | + to_geotiff(mod, out, pack=True) |
| 68 | + |
| 69 | + |
| 70 | +@pytest.mark.parametrize("chunks", [None, 1], ids=["numpy", "dask"]) |
| 71 | +def test_pack_rejects_underflow_unsigned(tmp_path, chunks): |
| 72 | + """A negative packed value must not wrap into the top of a uint range.""" |
| 73 | + data = np.array([[10, 20], [30, 40]], dtype=np.uint16) |
| 74 | + da = xr.DataArray( |
| 75 | + data, |
| 76 | + dims=("y", "x"), |
| 77 | + coords={"y": [1.5, 0.5], "x": [0.5, 1.5]}, |
| 78 | + attrs={"crs": 4326, |
| 79 | + "gdal_metadata": {"SCALE": "0.5", "OFFSET": "0.0"}}, |
| 80 | + ) |
| 81 | + src = str(tmp_path / "src_u16_underflow_3260.tif") |
| 82 | + to_geotiff(da, src) |
| 83 | + |
| 84 | + mod = _unpacked(src) |
| 85 | + mod.data[0, 0] = -1.0 # packs to -2, below uint16 min |
| 86 | + if chunks is not None: |
| 87 | + mod = mod.chunk({"y": chunks}) |
| 88 | + out = str(tmp_path / "out_u16_underflow_3260.tif") |
| 89 | + with pytest.raises(ValueError, match="cannot represent"): |
| 90 | + to_geotiff(mod, out, pack=True) |
| 91 | + |
| 92 | + |
| 93 | +# --------------------------------------------------------------------------- |
| 94 | +# +/-Inf passes the NaN fill / NaN guard but must not reach the cast |
| 95 | +# --------------------------------------------------------------------------- |
| 96 | + |
| 97 | + |
| 98 | +@pytest.mark.parametrize("chunks", [None, 1], ids=["numpy", "dask"]) |
| 99 | +@pytest.mark.parametrize("value", [np.inf, -np.inf], ids=["inf", "neg-inf"]) |
| 100 | +def test_pack_rejects_inf(tmp_path, chunks, value): |
| 101 | + # A declared sentinel routes Inf past the NaN fill (isnan only), so |
| 102 | + # this leg pins the path where Inf used to reach the cast directly. |
| 103 | + src = _write_scaled_int16(tmp_path / "src_inf_3260.tif", nodata=-32768) |
| 104 | + mod = _unpacked(src) |
| 105 | + mod.data[0, 0] = value |
| 106 | + if chunks is not None: |
| 107 | + mod = mod.chunk({"y": chunks}) |
| 108 | + out = str(tmp_path / "out_inf_3260.tif") |
| 109 | + with pytest.raises(ValueError, match="not finite|cannot represent"): |
| 110 | + to_geotiff(mod, out, pack=True) |
| 111 | + |
| 112 | + |
| 113 | +# --------------------------------------------------------------------------- |
| 114 | +# No false positives: boundary and round-back-into-range values pass |
| 115 | +# --------------------------------------------------------------------------- |
| 116 | + |
| 117 | + |
| 118 | +@pytest.mark.parametrize("chunks", [None, 1], ids=["numpy", "dask"]) |
| 119 | +def test_pack_accepts_full_dtype_range(tmp_path, chunks): |
| 120 | + """Exact iinfo.min / iinfo.max packed values are representable.""" |
| 121 | + data = np.array([[-32768, 0], [100, 32767]], dtype=np.int16) |
| 122 | + da = xr.DataArray( |
| 123 | + data, |
| 124 | + dims=("y", "x"), |
| 125 | + coords={"y": [1.5, 0.5], "x": [0.5, 1.5]}, |
| 126 | + attrs={"crs": 4326, |
| 127 | + "gdal_metadata": {"SCALE": "0.1", "OFFSET": "0.0"}}, |
| 128 | + ) |
| 129 | + src = str(tmp_path / "src_bounds_3260.tif") |
| 130 | + to_geotiff(da, src) |
| 131 | + |
| 132 | + mod = _unpacked(src) |
| 133 | + if chunks is not None: |
| 134 | + mod = mod.chunk({"y": chunks}) |
| 135 | + out = str(tmp_path / "out_bounds_3260.tif") |
| 136 | + to_geotiff(mod, out, pack=True) |
| 137 | + |
| 138 | + back = open_geotiff(out) |
| 139 | + assert str(back.dtype) == "int16" |
| 140 | + np.testing.assert_array_equal(np.asarray(back.data), data) |
| 141 | + |
| 142 | + |
| 143 | +def test_pack_accepts_value_that_rounds_back_into_range(tmp_path): |
| 144 | + """The guard runs after the round: 3276.74 packs to 32767.4 which |
| 145 | + rounds to 32767 and fits.""" |
| 146 | + src = _write_scaled_int16(tmp_path / "src_round_3260.tif") |
| 147 | + mod = _unpacked(src) |
| 148 | + mod.data[0, 0] = 3276.74 |
| 149 | + out = str(tmp_path / "out_round_3260.tif") |
| 150 | + to_geotiff(mod, out, pack=True) |
| 151 | + back = open_geotiff(out) |
| 152 | + assert np.asarray(back.data)[0, 0] == 32767 |
| 153 | + |
| 154 | + |
| 155 | +def test_pack_float_target_not_range_guarded(tmp_path): |
| 156 | + """Float packed dtypes have no wrap problem; large values pass.""" |
| 157 | + data = np.array([[1.0, 2.0], [3.0, -9999.0]], dtype=np.float32) |
| 158 | + da = xr.DataArray( |
| 159 | + data, |
| 160 | + dims=("y", "x"), |
| 161 | + coords={"y": [1.5, 0.5], "x": [0.5, 1.5]}, |
| 162 | + attrs={"crs": 4326, "nodata": -9999.0, |
| 163 | + "gdal_metadata": {"SCALE": "2.0", "OFFSET": "0.0"}}, |
| 164 | + ) |
| 165 | + src = str(tmp_path / "src_float_3260.tif") |
| 166 | + to_geotiff(da, src, nodata=-9999.0) |
| 167 | + |
| 168 | + mod = _unpacked(src) |
| 169 | + mod.data[0, 0] = 1e30 |
| 170 | + out = str(tmp_path / "out_float_3260.tif") |
| 171 | + to_geotiff(mod, out, pack=True) |
| 172 | + back = open_geotiff(out) |
| 173 | + assert str(back.dtype) == "float32" |
| 174 | + # Packed value is 1e30 / SCALE = 5e29, well inside float32 range. |
| 175 | + assert np.asarray(back.data)[0, 0] == np.float32(5e29) |
| 176 | + |
| 177 | + |
| 178 | +# --------------------------------------------------------------------------- |
| 179 | +# Unit: the 64-bit exclusive upper bound is exact |
| 180 | +# --------------------------------------------------------------------------- |
| 181 | + |
| 182 | + |
| 183 | +def test_guard_rejects_two_pow_63_for_int64(): |
| 184 | + """float64 cannot hold INT64_MAX; float(iinfo.max) rounds up to 2**63. |
| 185 | + The guard's exclusive bound must reject exactly-2**63, which an |
| 186 | + inclusive ``> float(iinfo.max)`` test would let through to wrap.""" |
| 187 | + info = np.iinfo(np.int64) |
| 188 | + chunk = np.array([float(2 ** 63)]) |
| 189 | + with pytest.raises(ValueError, match="cannot represent"): |
| 190 | + _pack_guard_int_range( |
| 191 | + chunk, "int64", float(info.min), float(int(info.max) + 1)) |
| 192 | + # One ULP below 2**63 is representable in int64 and passes. |
| 193 | + ok = np.array([np.nextafter(float(2 ** 63), 0.0)]) |
| 194 | + _pack_guard_int_range( |
| 195 | + ok, "int64", float(info.min), float(int(info.max) + 1)) |
0 commit comments