From a2b1712afd957deaf189c9b1a04e469596d853c9 Mon Sep 17 00:00:00 2001 From: Mathias Hauser Date: Fri, 15 Jan 2021 19:19:55 +0100 Subject: [PATCH] fix decode for scale/ offset list (#4802) * fix decode for scale/ offset list * typo --- doc/whats-new.rst | 2 ++ xarray/coding/variables.py | 4 ++-- xarray/tests/test_coding.py | 14 +++++++++++++- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 51b16d65a62..88994a5bfc0 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -75,6 +75,8 @@ Bug fixes - Add ``missing_dims`` parameter to transpose (:issue:`4647`, :pull:`4767`). By `Daniel Mesejo `_. - Resolve intervals before appending other metadata to labels when plotting (:issue:`4322`, :pull:`4794`). By `Justus Magin `_. +- Fix regression when decoding a variable with a ``scale_factor`` and ``add_offset`` given + as a list of length one (:issue:`4631`) by `Mathias Hauser `_. - Expand user directory paths (e.g. ``~/``) in :py:func:`open_mfdataset` and :py:meth:`Dataset.to_zarr` (:issue:`4783`, :pull:`4795`). By `Julien Seguinot `_. diff --git a/xarray/coding/variables.py b/xarray/coding/variables.py index 80277e9cd4e..b035ff82086 100644 --- a/xarray/coding/variables.py +++ b/xarray/coding/variables.py @@ -270,9 +270,9 @@ def decode(self, variable, name=None): add_offset = pop_to(attrs, encoding, "add_offset", name=name) dtype = _choose_float_dtype(data.dtype, "add_offset" in attrs) if np.ndim(scale_factor) > 0: - scale_factor = scale_factor.item() + scale_factor = np.asarray(scale_factor).item() if np.ndim(add_offset) > 0: - add_offset = add_offset.item() + add_offset = np.asarray(add_offset).item() transform = partial( _scale_offset_decoding, scale_factor=scale_factor, diff --git a/xarray/tests/test_coding.py b/xarray/tests/test_coding.py index 0f191049284..e0df7782aa7 100644 --- a/xarray/tests/test_coding.py +++ b/xarray/tests/test_coding.py @@ -8,7 +8,7 @@ from xarray.coding import variables from xarray.conventions import decode_cf_variable, encode_cf_variable -from . import assert_equal, assert_identical, requires_dask +from . import assert_allclose, assert_equal, assert_identical, requires_dask with suppress(ImportError): import dask.array as da @@ -105,3 +105,15 @@ def test_scaling_converts_to_float32(dtype): roundtripped = coder.decode(encoded) assert_identical(original, roundtripped) assert roundtripped.dtype == np.float32 + + +@pytest.mark.parametrize("scale_factor", (10, [10])) +@pytest.mark.parametrize("add_offset", (0.1, [0.1])) +def test_scaling_offset_as_list(scale_factor, add_offset): + # test for #4631 + encoding = dict(scale_factor=scale_factor, add_offset=add_offset) + original = xr.Variable(("x",), np.arange(10.0), encoding=encoding) + coder = variables.CFScaleOffsetCoder() + encoded = coder.encode(original) + roundtripped = coder.decode(encoded) + assert_allclose(original, roundtripped)