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

Should the zarr backend support NCZarr conventions? #6374

Closed
malmans2 opened this issue Mar 17, 2022 · 18 comments · Fixed by #6420
Closed

Should the zarr backend support NCZarr conventions? #6374

malmans2 opened this issue Mar 17, 2022 · 18 comments · Fixed by #6420

Comments

@malmans2
Copy link
Contributor

malmans2 commented Mar 17, 2022

What is your issue?

As part of the CZI EOSS4 grant, at B-Open we are keen on improving xarray/zarr cross-community conventions. It looks like xarray's "zarr" backend does not support Unidata NCZarr conventions while NetCDF-c>=4.8.1 supports xarray conventions.

Currently, it is possible to open a NCZarr data source using the "netcdf4" backend only. Here is an example:

import xarray as xr
import numpy as np

ds = xr.Dataset(
    {
        "a": (("y", "x"), np.random.rand(6).reshape(2, 3)),
        "b": (("y", "x"), np.random.rand(6).reshape(2, 3)),
    },
    coords={"y": [0, 1], "x": [10, 20, 30]},
)
ds.to_netcdf("file://test.nczarr#mode=nczarr")

ds_from_nczarr = xr.open_dataset("file://test.nczarr#mode=nczarr", engine="netcdf4")
xr.testing.assert_identical(ds, ds_from_nczarr)

xr.open_dataset("test.nczarr", engine="zarr")
# KeyError: 'Zarr object is missing the attribute `_ARRAY_DIMENSIONS`, which is required for xarray to determine variable dimensions.'

Would the community benefit from a "zarr" backend compatible with NCZarr as well? @rsignell-usgs and @rabernat suggested to discuss this within the xarray community, but I don't think a dedicated issue has been opened yet.

cc: @alexamici @aurghs @joshmoore

@malmans2 malmans2 added the needs triage Issue that has not been reviewed by xarray team member label Mar 17, 2022
@dopplershift
Copy link
Contributor

Cc @WardF @DennisHeimbigner @haileyajohnson

@DennisHeimbigner
Copy link

For Unidata and netcdf, I think the situation is briefly this.

In netcdf-4, dimensions are named objects that can "reside" inside groups.
So for example we might have this:

netcdf example {
  dimensions: x=1; y=10; z=20;
  group g1 {
    dimensions: a=1; y=10; z=5;
    variables: float v(/x, /g1/y, /z);
  }
}

So base dimension names (e.g. "z") can occur in different groups and can represent different dimension objects (with different sizes).

It is possible to reference any dimension using fully-qualified-names (FQNs) such as "/g1/y".
This capability is important so that, for example, related dimensions can be isolated with a group.

NCZarr captures this information by recording fully qualified names as special keys.
This differs from XArray where fully qualified names are not supported.
From the netcdf point of view, it is as if all dimension objects were declared in the root group.

If XArray is to be extended to support the equivalent of groups and distinct sets of dimensions are going to be supported in different groups, then some equivalent of the netcdf FQN is going to be needed.

One final note. In netcdf, the dimension size is declared once and associated with a name.
In zarr/xarray, the size occurs in multiple places (via the "shape" key) and the name-size
associated is also declared multlple times via the _ARRAY_DIMENSIONS attribute.

@joshmoore
Copy link

Thanks for the details, @DennisHeimbigner. But my reading of what you outline is that for some nczarr datasets, xarray will be able to open them. Correct? If so, there were always likely to be follow-on's to this issue when/if we identify critical edge cases. Perhaps for the moment, though, we can focus here on what we want to enable and what can be done straight-forwardly.

That likely makes this more a question for @shoyer, @jhamman, @rabernat et al. (sorry, no way to @-mention all the current devs) @malmans2 is probably in a good place to start updating the existing Zarr backend to also check for the nczarr files, but if there are strong opinions against or alternatives that would be preferred, it would be good to hear about them.

@max-sixty
Copy link
Collaborator

CC @pydata/xarray

@joshmoore
Copy link

Thanks, @max-sixty! Guess it just doesn't complete for those outside the org.

@rabernat
Copy link
Contributor

My opinion is that we should not try to support the nczarr conventions directly. Xarray already supports nczarr via netCDF4. If netCDF4 can open the Zarr store, then Xarray can read it.

Supporting nczarr directly would require lots of custom logic within xarray. That's because nczarr introduces several additional metadata files that are not part of the zarr spec. These additional metadata files break the abstractions through which xarray interacts with zarr; working around this requires going under the hood, access the store object directly (rather than the zarr groups and arrays).

I would turn this question around and ask: if netCDF4 supports access to these datasets directly, what's the advantage of xarray bypassing netCDF4 and opening them directly? If there are significant performance benefits, I would be more likely to consider it worthwhile.

@DennisHeimbigner
Copy link

As the moment, NCzarr format files (as opposed to pure Zarr format files
produced by NCZarr) do not include the Xarray _ARRAY_DIMENSIONS attribute.
Now that I think about it, there is no reason not to include that attribute where it is meaningful,
so I will make that change. After that change, the situation should be as follows:

Xarray can read any nczarr format file subject to the following conditions:
1. xarray attempts to read only the root group and ignores subgroups
    * this is because xarray cannot handle subgroups.
2. the xarray implementation ignores extra dictionary keys in e.g. .zarray and .zattr
   that it does not recognize
    * this should already be the case under the principle of "read broadly, write narrowly".

@shoyer
Copy link
Member

shoyer commented Mar 23, 2022

@DennisHeimbigner I think it would be great to standardize NCZarr as a super-set of the "Xarray-Zarr" standard! I think Xarray should indeed be able to read such files. If you want to read a sub-group, you can read the sub-group in a separate call to xarray.open_zarr().

@rabernat I would not be opposed to adding support inside Xarray for reading NCZarr data, specifically to understand NCZarr's encoding of dimension names when using Zarr-Python. This wouldn't give 100% compatibility with NCZarr, but it would be very close (maybe just with incorrect dtypes for attributes) with a minimal amount of work. I don't think it would be a big deal to look for .nczvar files.

@rabernat
Copy link
Contributor

Sure, to be clear, my hesitancy is mostly just around being reluctant to maintain more complexity in our zarr interface. If there is momentum to implement and maintain this compatibility, I am definitely not opposed. 🚀

@DennisHeimbigner
Copy link

I guess I was not clear. If you are willing to lose netcdf specific metadata,
then I believe any xarray or zarr implementation should be able to read nczarr written data
with no changes needed.

@joshmoore
Copy link

rabernat commented 7 hours ago My opinion is that we should not try to support the nczarr conventions directly. Xarray already supports nczarr via netCDF4. If netCDF4 can open the Zarr store, then Xarray can read it. ... I would turn this question around and ask: if netCDF4 supports access to these datasets directly, what's the advantage of xarray bypassing netCDF4 and opening them directly?

@malmans2 can chime in with his experience, but it seems that from the user point-of-view, not needing to know if something is an xarray-zarr or a nczarr would be kinder of us. Plus as said below, I do think it puts us on the path to defining a common spec.

Supporting nczarr directly would require lots of custom logic within xarray.

Mea culpa. I wasn't clear enough about the intent from my side at least, namely to support loading ARRAY_DIMENSIONS (or some other necessary subset) from nczarr rather than its entirety.

DennisHeimbigner commented 4 hours ago this is because xarray cannot handle subgroups.

I'll add as a side that work on the subgroups (i.e. datatree) is progressing in case any consideration needs to be included now rather than later.

DennisHeimbigner added a commit to DennisHeimbigner/netcdf-c that referenced this issue Mar 24, 2022
re: pydata/xarray#6374

As a result of a discussion about Xarray (see above issue),
I decided to turn on the xarray convention for NCZarr datasets
where possible so that xarray can read a larger set of nczarr
generated datasets.

This causes the following changes:
* If the user wants to generate a pure zarr file, then the mode "zarr" must be explicitly used; it is no longer the case that "mode=xarray" or mode="noxarray"
implies "mode=zarr".
* It is still the case that "mode=noxarray" will turn off the XArray convention.

The following conditions will cause ''_ARRAY_DIMENSIONS'' to not be written.
* The variable is not in the root group,
* Any dimension referenced by the variable is not in the root group.
@dcherian dcherian added topic-backends and removed needs triage Issue that has not been reviewed by xarray team member labels Mar 24, 2022
@malmans2
Copy link
Contributor Author

Adding support for reading NCZarr in the "zarr" backend should be quite easy if xarray doesn't need to integrate the additional features in NCZarr (e.g., groups, fully qualified names, dtypes for attributes). It looks like the main difference is that the dimension names stored by xarray in .zattrs["_ARRAY_DIMENSIONS"] are stored by NCZarr in .zarray["_NCZARR_ARRAY"]["dimrefs"]. I drafted PR #6420 to explore what it would take to support reading NCZarr in xarray's "zarr" backend, and I don't think there are major changes/additions needed.
(I'm experiencing issues with Windows in PR #6420. I think they need to be explored in netcdf4-python or netcdf-c though - I've added a comment in the PR)

I'm not sure whether it is better to (i) add direct support for NCZarr in xarray or (ii) just rely on the netcdf4 backend. After playing a bit with both backends, I have a few comments if option (ii) is chosen:

  • I would change the error raised when "_ARRAY_DIMENSIONS" is not present, suggesting to try the netcdf4 backend as well. Also, I think it's worth pointing out in the documentation or in the error message where to find information on how to open/write zarr data with the netcdf4 backend. I suspect right now it's not easy to find that information for python/xarray users.
  • I would consider starting a deprecation cycle for open_zarr, so it will be more clear that zarr data can be opened using various backends.
  • If "_ARRAY_DIMENSIONS" and "_NC*" attributes will coexist in the next version of NCZarr, the zarr backend will be able to open NCZarr but will treat "_NC*" attributes as regular attributes. I think the "zarr" backend would have to handle "_NC*" attributes (e.g., drop or hide), otherwise there can be issues when writing:
TypeError: Invalid value for attr '_NCZARR_ATTR': {'types': {'Conventions': '<U1', 'title': '<U1', 'description': '<U1', 'platform': '<U1', 'references': '<U1', '_NCProperties': '<U1'}}.
For serialization to netCDF files, its value must be of one of the following types: str, Number, ndarray, number, list, tuple

@DennisHeimbigner
Copy link

dimension names stored by xarray in .zattrs["_ARRAY_DIMENSIONS"] are stored by NCZarr in .zarray["_NCZARR_ARRAY"]["dimrefs"]

I made a recent change to this so that where possible, all NCZarr files contain the
xarray _ARRAY_ATTRIBUTE. By "where possible" I mean that the array is in the root group
and the dimensions it references are "defined" in the root group (i.e. they have the simple
FQN "/XXX" where XXX is the dim name.
This means that there is sometimes a duplication of information between _ARRAY_ATTRIBUTE
and ".zarray["_NCZARR_ARRAY"]["dimrefs"].

@malmans2
Copy link
Contributor Author

Thanks! #6420 looks at .zarray["_NCZARR_ARRAY"]["dimrefs"] only if .zattrs["_ARRAY_ATTRIBUTE"] is missing.

@wankoelias
Copy link

wankoelias commented Apr 6, 2022

As it is currently it is also not possible to write a zarr which follows the GDAL ZARR driver conventions. Writing the _CRS attribute also results in a TypeError:

For serialization to netCDF files, its value must be of one of the following types: str, Number, ndarray, number, list, tuple

@shoyer
Copy link
Member

shoyer commented Apr 6, 2022

@wankoelias could you kindly open a new issue for writing GDAL ZARR?

@DennisHeimbigner
Copy link

As it is currently it is also not possible to write a zarr which follows the GDAL ZARR driver conventions. Writing the _CRS attribute also results in a TypeError:

Can you elaborate? What API are you using to do the write: python, netcdf-c, or what?

@shoyer
Copy link
Member

shoyer commented Apr 6, 2022

As it is currently it is also not possible to write a zarr which follows the GDAL ZARR driver conventions. Writing the _CRS attribute also results in a TypeError:

Can you elaborate? What API are you using to do the write: python, netcdf-c, or what?

This error message comes from Xarray and can be triggered by calling to_zarr():

raise TypeError(

I don't think netCDF-C needs to be involved at all, which is why I suggested opening a separate issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

9 participants