Skip to content
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

Support the new compression argument in netCDF4 > 1.6.0 #6981

Merged
merged 12 commits into from
Dec 1, 2022
Merged
Show file tree
Hide file tree
Changes from 6 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
11 changes: 10 additions & 1 deletion xarray/backends/netCDF4_.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from contextlib import suppress

import numpy as np
from packaging.version import Version

from .. import coding
from ..coding.variables import pop_to
Expand Down Expand Up @@ -242,13 +243,21 @@ def _extract_nc4_variable_encoding(
"shuffle",
"_FillValue",
"dtype",
"compression",
}
if lsd_okay:
valid_encodings.add("least_significant_digit")
if h5py_okay:
valid_encodings.add("compression")
valid_encodings.add("compression_opts")

if backend == "netCDF4" and has_netcdf4:
# if using netCDF4 check the versions are updated enough for supporting the new
# compression
if Version(netCDF4.__version__) < Version("1.6.0") or Version(
netCDF4.getlibversion().split(" ")[0]
) < Version("4.9.0"):
valid_encodings.remove("compression")
dcherian marked this conversation as resolved.
Show resolved Hide resolved

if not raise_on_invalid and encoding.get("chunksizes") is not None:
# It's possible to get encoded chunksizes larger than a dimension size
# if the original file had an unlimited dimension. This is problematic
Expand Down
15 changes: 15 additions & 0 deletions xarray/tests/test_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -4888,6 +4888,21 @@ def test_extract_nc4_variable_encoding(self):
encoding = _extract_nc4_variable_encoding(var, unlimited_dims=("x",))
assert {} == encoding

@requires_netCDF4
def test_extract_nc4_variable_encoding_netcdf4(self, monkeypatch):
# New netCDF4 1.6.0 compression argument.
var = xr.Variable(("x",), [1, 2, 3], {}, {"compression": "szlib"})
_extract_nc4_variable_encoding(var, backend="netCDF4", raise_on_invalid=True)
# Check that fails for older versions
import netCDF4

with monkeypatch.context() as m:
m.setattr(netCDF4, "__version__", "1.5.0")
with pytest.raises(ValueError):
_extract_nc4_variable_encoding(
var, backend="netCDF4", raise_on_invalid=True
)

def test_extract_h5nc_encoding(self):
# not supported with h5netcdf (yet)
var = xr.Variable(("x",), [1, 2, 3], {}, {"least_sigificant_digit": 2})
Expand Down