Zarr Encoding Specification¶
In implementing support for the Zarr storage format, Xarray developers made some ad hoc choices about how to store NetCDF data in Zarr. Future versions of the Zarr spec will likely include a more formal convention for the storage of the NetCDF data model in Zarr; see Zarr spec repo for ongoing discussion.
First, Xarray can only read and write Zarr groups. There is currently no support
for reading / writing individual Zarr arrays. Zarr groups are mapped to
Xarray Dataset
objects.
Second, from Xarray’s point of view, the key difference between NetCDF and Zarr is that all NetCDF arrays have dimension names while Zarr arrays do not. Therefore, in order to store NetCDF data in Zarr, Xarray must somehow encode and decode the name of each array’s dimensions.
To accomplish this, Xarray developers decided to define a special Zarr array
attribute: _ARRAY_DIMENSIONS
. The value of this attribute is a list of
dimension names (strings), for example ["time", "lon", "lat"]
. When writing
data to Zarr, Xarray sets this attribute on all variables based on the variable
dimensions. When reading a Zarr group, Xarray looks for this attribute on all
arrays, raising an error if it can’t be found. The attribute is used to define
the variable dimension names and then removed from the attributes dictionary
returned to the user.
Because of these choices, Xarray cannot read arbitrary array data, but only
Zarr data with valid _ARRAY_DIMENSIONS
or
NCZarr attributes
on each array (NCZarr dimension names are defined in the .zarray
file).
After decoding the _ARRAY_DIMENSIONS
or NCZarr attribute and assigning the variable
dimensions, Xarray proceeds to [optionally] decode each variable using its
standard CF decoding machinery used for NetCDF data (see decode_cf()
).
Finally, it’s worth noting that Xarray writes (and attempts to read)
“consolidated metadata” by default (the .zmetadata
file), which is another
non-standard Zarr extension, albeit one implemented upstream in Zarr-Python.
You do not need to write consolidated metadata to make Zarr stores readable in
Xarray, but because Xarray can open these stores much faster, users will see a
warning about poor performance when reading non-consolidated stores unless they
explicitly set consolidated=False
. See Consolidated Metadata
for more details.
As a concrete example, here we write a tutorial dataset to Zarr and then re-open it directly with Zarr:
In [1]: import os
In [2]: import xarray as xr
In [3]: import zarr
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In [3], line 1
----> 1 import zarr
ModuleNotFoundError: No module named 'zarr'
In [4]: ds = xr.tutorial.load_dataset("rasm")
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
File /build/python-xarray-Jj6azG/python-xarray-2023.05.0/xarray/tutorial.py:126, in open_dataset(name, cache, cache_dir, engine, **kws)
125 try:
--> 126 import pooch
127 except ImportError as e:
ModuleNotFoundError: No module named 'pooch'
The above exception was the direct cause of the following exception:
ImportError Traceback (most recent call last)
Cell In [4], line 1
----> 1 ds = xr.tutorial.load_dataset("rasm")
File /build/python-xarray-Jj6azG/python-xarray-2023.05.0/xarray/tutorial.py:206, in load_dataset(*args, **kwargs)
169 def load_dataset(*args, **kwargs) -> Dataset:
170 """
171 Open, load into memory, and close a dataset from the online repository
172 (requires internet).
(...)
204 load_dataset
205 """
--> 206 with open_dataset(*args, **kwargs) as ds:
207 return ds.load()
File /build/python-xarray-Jj6azG/python-xarray-2023.05.0/xarray/tutorial.py:128, in open_dataset(name, cache, cache_dir, engine, **kws)
126 import pooch
127 except ImportError as e:
--> 128 raise ImportError(
129 "tutorial.open_dataset depends on pooch to download and manage datasets."
130 " To proceed please install pooch."
131 ) from e
133 logger = pooch.get_logger()
134 logger.setLevel("WARNING")
ImportError: tutorial.open_dataset depends on pooch to download and manage datasets. To proceed please install pooch.
In [5]: ds.to_zarr("rasm.zarr", mode="w")
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In [5], line 1
----> 1 ds.to_zarr("rasm.zarr", mode="w")
File /build/python-xarray-Jj6azG/python-xarray-2023.05.0/xarray/core/dataset.py:2141, in Dataset.to_zarr(self, store, chunk_store, mode, synchronizer, group, encoding, compute, consolidated, append_dim, region, safe_chunks, storage_options, zarr_version, chunkmanager_store_kwargs)
2020 """Write dataset contents to a zarr group.
2021
2022 Zarr chunks are determined in the following way:
(...)
2137 The I/O user guide, with more details and examples.
2138 """
2139 from xarray.backends.api import to_zarr
-> 2141 return to_zarr( # type: ignore[call-overload,misc]
2142 self,
2143 store=store,
2144 chunk_store=chunk_store,
2145 storage_options=storage_options,
2146 mode=mode,
2147 synchronizer=synchronizer,
2148 group=group,
2149 encoding=encoding,
2150 compute=compute,
2151 consolidated=consolidated,
2152 append_dim=append_dim,
2153 region=region,
2154 safe_chunks=safe_chunks,
2155 zarr_version=zarr_version,
2156 chunkmanager_store_kwargs=chunkmanager_store_kwargs,
2157 )
File /build/python-xarray-Jj6azG/python-xarray-2023.05.0/xarray/backends/api.py:1672, in to_zarr(dataset, store, chunk_store, mode, synchronizer, group, encoding, compute, consolidated, append_dim, region, safe_chunks, storage_options, zarr_version, chunkmanager_store_kwargs)
1670 already_consolidated = False
1671 consolidate_on_close = consolidated or consolidated is None
-> 1672 zstore = backends.ZarrStore.open_group(
1673 store=mapper,
1674 mode=mode,
1675 synchronizer=synchronizer,
1676 group=group,
1677 consolidated=already_consolidated,
1678 consolidate_on_close=consolidate_on_close,
1679 chunk_store=chunk_mapper,
1680 append_dim=append_dim,
1681 write_region=region,
1682 safe_chunks=safe_chunks,
1683 stacklevel=4, # for Dataset.to_zarr()
1684 zarr_version=zarr_version,
1685 )
1687 if mode in ["a", "r+"]:
1688 _validate_datatypes_for_zarr_append(zstore, dataset)
File /build/python-xarray-Jj6azG/python-xarray-2023.05.0/xarray/backends/zarr.py:383, in ZarrStore.open_group(cls, store, mode, synchronizer, group, consolidated, consolidate_on_close, chunk_store, storage_options, append_dim, write_region, safe_chunks, stacklevel, zarr_version)
366 @classmethod
367 def open_group(
368 cls,
(...)
381 zarr_version=None,
382 ):
--> 383 import zarr
385 # zarr doesn't support pathlib.Path objects yet. zarr-python#601
386 if isinstance(store, os.PathLike):
ModuleNotFoundError: No module named 'zarr'
In [6]: zgroup = zarr.open("rasm.zarr")
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In [6], line 1
----> 1 zgroup = zarr.open("rasm.zarr")
NameError: name 'zarr' is not defined
In [7]: print(os.listdir("rasm.zarr"))
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In [7], line 1
----> 1 print(os.listdir("rasm.zarr"))
FileNotFoundError: [Errno 2] No such file or directory: 'rasm.zarr'
In [8]: print(zgroup.tree())
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In [8], line 1
----> 1 print(zgroup.tree())
NameError: name 'zgroup' is not defined
In [9]: dict(zgroup["Tair"].attrs)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In [9], line 1
----> 1 dict(zgroup["Tair"].attrs)
NameError: name 'zgroup' is not defined