oceanmodeling / xarray-selafin

An xarray engine for opening Selafin files (TELEMAC)
https://pypi.org/project/xarray-selafin/
The Unlicense
4 stars 2 forks source link

serialization as netcdf throws an exception #42

Open pmav99 opened 4 months ago

pmav99 commented 4 months ago

I am not sure if xarray-selafin, wants to support exporting selafin files as netcdfs, but the way the xarray attributes are currently being utilized is not compatible with netcdf. For example:

ds = xr.open_dataset("tests/data/r2d_tidal_flats.slf")
ds.to_netcdf("/tmp/out.nc")

results in:

TypeError: Invalid value for attr 'variables': {'U': ('VELOCITY U', 'M/S'), 'V': ('VELOCITY V', 'M/S'), 'H': ('WATER DEPTH', 'M'), 'S': ('FREE SURFACE', 'M'), 'B': ('BOTTOM', 'M')}. For serialization to netCDF files, its value must be of one of the following types: str, Number, ndarray, number, list, tuple
tomsail commented 1 month ago

Here is the implementation in io_test.py

def write_netcdf(ds, nc_out):
    # Remove dict and multi-dimensional arrays not supported in netCDF
    del ds.attrs["variables"]
    del ds.attrs["ikle2"]
    try:
        del ds.attrs["ikle3"]
    except KeyError:
        pass
    # Write netCDF file
    ds.to_netcdf(nc_out)

both variables and ikle2 (and ikle3 for 3d outputs) need to be deleted to to write to netcdf.