Skip to content

ENH: Add default fill values for decode_cf #5680

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion xarray/coding/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,20 @@
from ..core.pycompat import is_duck_dask_array
from ..core.variable import Variable

NP_TO_NC_TYPE = {
"S1": "\x00",
"i1": -127,
"u1": 255,
"i2": -32767,
"u2": 65535,
"i4": -2147483647,
"u4": 4294967295,
"i8": -9223372036854775806,
"u8": 18446744073709551614,
"f4": 9.969209968386869e36,
"f8": 9.969209968386869e36,
}


class SerializationWarning(RuntimeWarning):
"""Warnings about encoding/decoding issues in serialization."""
Expand Down Expand Up @@ -183,6 +197,14 @@ def decode(self, variable, name=None):
pop_to(attrs, encoding, attr, name=name)
for attr in ("missing_value", "_FillValue")
]
try:
default_fillvalue = NP_TO_NC_TYPE[np.dtype(variable.dtype).str[1:]]
raw_fill_values.append(default_fillvalue)
except KeyError:
warnings.warn(
f"A default fill value for dtype {variable.dtype} could not be found"
)

if raw_fill_values:
encoded_fill_values = {
fv
Expand All @@ -209,7 +231,6 @@ def decode(self, variable, name=None):
dtype=dtype,
)
data = lazy_elemwise_func(data, transform, dtype)

return Variable(dims, data, attrs, encoding)


Expand Down
7 changes: 7 additions & 0 deletions xarray/tests/test_conventions.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,13 @@ def test_decode_cf_with_multiple_missing_values(self):
assert_identical(expected, actual)
assert "has multiple fill" in str(w[0].message)

def test_decode_standard_missing_value(self):

original = Variable(["t"], [coding.variables.NP_TO_NC_TYPE["f8"], 1, 2], {})
expected = Variable(["t"], [np.nan, 1, 2], {})
actual = conventions.decode_cf_variable("t", original)
assert_identical(expected, actual)

def test_decode_cf_with_drop_variables(self):
original = Dataset(
{
Expand Down