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
In [4]: ds = xr.tutorial.load_dataset("rasm")
In [5]: ds.to_zarr("rasm.zarr", mode="w")
Out[5]: <xarray.backends.zarr.ZarrStore at 0x7f68c0515000>
In [6]: zgroup = zarr.open("rasm.zarr")
In [7]: print(os.listdir("rasm.zarr"))
['time', 'xc', 'yc', 'zarr.json', 'Tair']
In [8]: print(zgroup.tree())
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
File /usr/lib/python3/dist-packages/zarr/core/_tree.py:9
8 try:
----> 9 import rich
10 import rich.console
ModuleNotFoundError: No module named 'rich'
The above exception was the direct cause of the following exception:
ImportError Traceback (most recent call last)
Cell In[8], line 1
----> 1 print(zgroup.tree())
File /usr/lib/python3/dist-packages/zarr/core/group.py:2300, in Group.tree(self, expand, level)
2281 def tree(self, expand: bool | None = None, level: int | None = None) -> Any:
2282 """
2283 Return a tree-like representation of a hierarchy.
2284
(...)
2298 A pretty-printable object displaying the hierarchy.
2299 """
-> 2300 return self._sync(self._async_group.tree(expand=expand, level=level))
File /usr/lib/python3/dist-packages/zarr/core/sync.py:208, in SyncMixin._sync(self, coroutine)
205 def _sync(self, coroutine: Coroutine[Any, Any, T]) -> T:
206 # TODO: refactor this to to take *args and **kwargs and pass those to the method
207 # this should allow us to better type the sync wrapper
--> 208 return sync(
209 coroutine,
210 timeout=config.get("async.timeout"),
211 )
File /usr/lib/python3/dist-packages/zarr/core/sync.py:163, in sync(coro, loop, timeout)
160 return_result = next(iter(finished)).result()
162 if isinstance(return_result, BaseException):
--> 163 raise return_result
164 else:
165 return return_result
File /usr/lib/python3/dist-packages/zarr/core/sync.py:119, in _runner(coro)
114 """
115 Await a coroutine and return the result of running it. If awaiting the coroutine raises an
116 exception, the exception will be returned.
117 """
118 try:
--> 119 return await coro
120 except Exception as ex:
121 return ex
File /usr/lib/python3/dist-packages/zarr/core/group.py:1550, in AsyncGroup.tree(self, expand, level)
1531 async def tree(self, expand: bool | None = None, level: int | None = None) -> Any:
1532 """
1533 Return a tree-like representation of a hierarchy.
1534
(...)
1548 A pretty-printable object displaying the hierarchy.
1549 """
-> 1550 from zarr.core._tree import group_tree_async
1552 if expand is not None:
1553 raise NotImplementedError("'expand' is not yet implemented.")
File /usr/lib/python3/dist-packages/zarr/core/_tree.py:13
11 import rich.tree
12 except ImportError as e:
---> 13 raise ImportError("'rich' is required for Group.tree") from e
16 class TreeRepr:
17 """
18 A simple object with a tree-like repr for the Zarr Group.
19
20 Note that this object and it's implementation isn't considered part
21 of Zarr's public API.
22 """
ImportError: 'rich' is required for Group.tree
In [9]: dict(zgroup["Tair"].attrs)
Out[9]:
{'units': 'C',
'long_name': 'Surface air temperature',
'type_preferred': 'double',
'time_rep': 'instantaneous',
'coordinates': 'yc xc',
'_FillValue': 'AAAAAAAAnkc='}