|
| 1 | +"""Refuse non-numeric ``nodata=`` / ``attrs['_FillValue']`` (#1973). |
| 2 | +
|
| 3 | +The writer compares the resolved nodata against pixel values via |
| 4 | +``np.isnan`` and casts it to the array dtype. A non-numeric value |
| 5 | +used to fall through ``_resolve_nodata_attr`` (returned verbatim) or |
| 6 | +the ``nodata=`` kwarg path and then crash inside NumPy with |
| 7 | +``ufunc 'isnan' not supported``. Both the entry point and the attr |
| 8 | +resolution path now refuse non-numeric values up front with a clear |
| 9 | +error. |
| 10 | +""" |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +import importlib.util |
| 14 | +import io |
| 15 | + |
| 16 | +import numpy as np |
| 17 | +import pytest |
| 18 | +import xarray as xr |
| 19 | + |
| 20 | +from xrspatial.geotiff import to_geotiff |
| 21 | +from xrspatial.geotiff._attrs import _resolve_nodata_attr |
| 22 | +from xrspatial.geotiff._validation import _validate_nodata_arg |
| 23 | + |
| 24 | + |
| 25 | +def _gpu_available() -> bool: |
| 26 | + if importlib.util.find_spec("cupy") is None: |
| 27 | + return False |
| 28 | + try: |
| 29 | + import cupy |
| 30 | + return bool(cupy.cuda.is_available()) |
| 31 | + except Exception: |
| 32 | + return False |
| 33 | + |
| 34 | + |
| 35 | +_HAS_GPU = _gpu_available() |
| 36 | +_gpu_only = pytest.mark.skipif(not _HAS_GPU, reason="cupy + CUDA required") |
| 37 | + |
| 38 | + |
| 39 | +def _nan_square(): |
| 40 | + return xr.DataArray( |
| 41 | + np.full((4, 4), np.nan, dtype=np.float32), |
| 42 | + coords={'y': np.arange(4.0), 'x': np.arange(4.0)}, |
| 43 | + dims=('y', 'x'), |
| 44 | + ) |
| 45 | + |
| 46 | + |
| 47 | +@pytest.mark.parametrize("bad", ['missing', object(), [1, 2]]) |
| 48 | +def test_validate_nodata_arg_rejects_non_numeric(bad): |
| 49 | + with pytest.raises(ValueError, match="nodata must be numeric"): |
| 50 | + _validate_nodata_arg(bad) |
| 51 | + |
| 52 | + |
| 53 | +@pytest.mark.parametrize("ok", [None, 0, -9999, 1.5, np.float32(-1), np.int64(0)]) |
| 54 | +def test_validate_nodata_arg_accepts_numeric_and_none(ok): |
| 55 | + _validate_nodata_arg(ok) |
| 56 | + |
| 57 | + |
| 58 | +def test_resolve_nodata_attr_rejects_non_numeric_fillvalue(): |
| 59 | + with pytest.raises(ValueError, match="_FillValue"): |
| 60 | + _resolve_nodata_attr({'_FillValue': 'missing'}) |
| 61 | + |
| 62 | + |
| 63 | +def test_resolve_nodata_attr_rejects_non_numeric_nodata_attr(): |
| 64 | + with pytest.raises(ValueError, match=r"attrs\['nodata'\]"): |
| 65 | + _resolve_nodata_attr({'nodata': 'missing'}) |
| 66 | + |
| 67 | + |
| 68 | +def test_resolve_nodata_attr_skips_non_numeric_in_nodatavals(): |
| 69 | + # nodatavals (rioxarray's per-band tuple) keeps its skip-on-non-numeric |
| 70 | + # behaviour: those values often come from arbitrary upstream pipelines |
| 71 | + # and a single bad entry should not block writing. |
| 72 | + assert _resolve_nodata_attr({'nodatavals': ('NaN ', -9999.0)}) == -9999.0 |
| 73 | + |
| 74 | + |
| 75 | +def test_resolve_nodata_attr_still_accepts_numeric_fillvalue(): |
| 76 | + assert _resolve_nodata_attr({'_FillValue': -9999}) == -9999 |
| 77 | + |
| 78 | + |
| 79 | +def test_resolve_nodata_attr_returns_none_for_nan_fillvalue(): |
| 80 | + assert _resolve_nodata_attr({'_FillValue': float('nan')}) is None |
| 81 | + |
| 82 | + |
| 83 | +def test_to_geotiff_rejects_non_numeric_nodata_kwarg(): |
| 84 | + buf = io.BytesIO() |
| 85 | + with pytest.raises(ValueError, match="nodata must be numeric"): |
| 86 | + to_geotiff(_nan_square(), buf, nodata='missing') |
| 87 | + |
| 88 | + |
| 89 | +def test_to_geotiff_rejects_non_numeric_fillvalue_attr(): |
| 90 | + da = _nan_square() |
| 91 | + da.attrs['_FillValue'] = 'missing' |
| 92 | + buf = io.BytesIO() |
| 93 | + with pytest.raises(ValueError, match="_FillValue"): |
| 94 | + to_geotiff(da, buf) |
| 95 | + |
| 96 | + |
| 97 | +def test_to_geotiff_vrt_path_rejects_non_numeric_nodata(tmp_path): |
| 98 | + vrt_path = str(tmp_path / "tmp_1973_vrt.vrt") |
| 99 | + with pytest.raises(ValueError, match="nodata must be numeric"): |
| 100 | + to_geotiff(_nan_square(), vrt_path, nodata='missing') |
| 101 | + |
| 102 | + |
| 103 | +def test_to_geotiff_accepts_numeric_nodata_kwarg(): |
| 104 | + buf = io.BytesIO() |
| 105 | + to_geotiff(_nan_square(), buf, nodata=-9999) |
| 106 | + assert buf.getbuffer().nbytes > 0 |
| 107 | + |
| 108 | + |
| 109 | +# --------------------------------------------------------------------------- |
| 110 | +# Bool rejection: ``nodata=True`` / ``nodata=False`` must raise TypeError at |
| 111 | +# all three writer entry points (eager, GPU, VRT). The eager path already |
| 112 | +# rejected bools for #1911 but the GPU/VRT validators previously routed bool |
| 113 | +# through ``float(True) == 1.0`` and silently coerced. The shared validator |
| 114 | +# now refuses bools so all three paths behave the same. |
| 115 | +# --------------------------------------------------------------------------- |
| 116 | + |
| 117 | + |
| 118 | +@pytest.mark.parametrize("bad", [True, False]) |
| 119 | +def test_validate_nodata_arg_rejects_bool(bad): |
| 120 | + with pytest.raises(TypeError, match="nodata must be numeric"): |
| 121 | + _validate_nodata_arg(bad) |
| 122 | + |
| 123 | + |
| 124 | +def test_validate_nodata_arg_rejects_numpy_bool(): |
| 125 | + with pytest.raises(TypeError, match="nodata must be numeric"): |
| 126 | + _validate_nodata_arg(np.bool_(True)) |
| 127 | + |
| 128 | + |
| 129 | +def test_to_geotiff_eager_rejects_bool_nodata(): |
| 130 | + buf = io.BytesIO() |
| 131 | + with pytest.raises(TypeError, match="nodata must be numeric"): |
| 132 | + to_geotiff(_nan_square(), buf, nodata=True) |
| 133 | + |
| 134 | + |
| 135 | +def test_to_geotiff_vrt_rejects_bool_nodata(tmp_path): |
| 136 | + vrt_path = str(tmp_path / "tmp_1973_bool_vrt.vrt") |
| 137 | + with pytest.raises(TypeError, match="nodata must be numeric"): |
| 138 | + to_geotiff(_nan_square(), vrt_path, nodata=True) |
| 139 | + |
| 140 | + |
| 141 | +@_gpu_only |
| 142 | +def test_write_geotiff_gpu_rejects_bool_nodata(tmp_path): |
| 143 | + import cupy |
| 144 | + |
| 145 | + from xrspatial.geotiff import write_geotiff_gpu |
| 146 | + |
| 147 | + da_cpu = _nan_square() |
| 148 | + da_gpu = da_cpu.copy(data=cupy.asarray(da_cpu.values)) |
| 149 | + out = str(tmp_path / "tmp_1973_bool_gpu.tif") |
| 150 | + with pytest.raises(TypeError, match="nodata must be numeric"): |
| 151 | + write_geotiff_gpu(da_gpu, out, nodata=True) |
| 152 | + |
| 153 | + |
| 154 | +# --------------------------------------------------------------------------- |
| 155 | +# All-non-numeric ``attrs['nodatavals']``: warn but still return None and |
| 156 | +# fall through. A tuple where every entry is non-numeric is almost certainly |
| 157 | +# a user error rather than a legitimate "no sentinel" signal. |
| 158 | +# --------------------------------------------------------------------------- |
| 159 | + |
| 160 | + |
| 161 | +def test_resolve_nodata_attr_warns_when_nodatavals_all_non_numeric(): |
| 162 | + with pytest.warns(UserWarning, match="nodatavals"): |
| 163 | + result = _resolve_nodata_attr({'nodatavals': ('foo', 'bar')}) |
| 164 | + assert result is None |
| 165 | + |
| 166 | + |
| 167 | +def test_resolve_nodata_attr_no_warning_when_nodatavals_has_usable_entry(): |
| 168 | + # First entry is non-numeric, second is a real sentinel. The loop |
| 169 | + # returns -9999.0 before reaching the warn site, so no warning fires. |
| 170 | + import warnings as _warnings |
| 171 | + with _warnings.catch_warnings(): |
| 172 | + _warnings.simplefilter("error") |
| 173 | + assert _resolve_nodata_attr({'nodatavals': ('foo', -9999.0)}) == -9999.0 |
| 174 | + |
| 175 | + |
| 176 | +def test_resolve_nodata_attr_no_warning_when_nodatavals_all_nan(): |
| 177 | + # NaN entries are skipped (they signal "the float NaN is the sentinel", |
| 178 | + # which doesn't need a GDAL_NODATA tag) but they ARE numeric, so the |
| 179 | + # all-non-numeric warning must not fire for an all-NaN tuple. |
| 180 | + import warnings as _warnings |
| 181 | + with _warnings.catch_warnings(): |
| 182 | + _warnings.simplefilter("error") |
| 183 | + assert _resolve_nodata_attr({'nodatavals': (float('nan'),)}) is None |
0 commit comments