Deltares / xugrid

Xarray and unstructured grids
https://deltares.github.io/xugrid/
MIT License
64 stars 8 forks source link

(De)serialization of UgridDataset results in UgridDatasets with 0 grids #223

Closed Tjalling-dejong closed 5 months ago

Tjalling-dejong commented 5 months ago

For the mesh component of HydroMT I was writing some tests involving writing and reading UgridDatasets. HydroMT converts UgridDatasets to xarray.Datasets before writing in order to preserve crs. I wanted to check if XUgrid preserves crs when writing to file. This resulted in an unexpected error. I expected the crs to be None but got an UgridDataset with 0 grids.

Reproducible example:

import xugrid as xu
data = xu.data.elevation_nl().to_dataset()
data.grid.set_crs(28992)
data.to_netcdf("test.nc")
data2 = xu.open_dataset("test.nc")
data2.grid.crs == data.grid.crs 

This will give a TypeError because grids is 0.

Huite commented 5 months ago

I think the problem is that you omitted the .ugrid accessor on the to_netcdf call.

If you change it to this:

data.ugrid.to_netcdf("test.nc")

It'll work as expected.

Without the ugrid accessor it'll just call the regular xarray method which is topology unaware.

(With a bit of luck, the ordinary method might also work once xarray has implemented explicit indexes.)

Tjalling-dejong commented 5 months ago

Thanks Huite, that worked. Is there a way that the crs can be preserved when writing to netcdf?

Huite commented 5 months ago

Not at the moment :(

These issues are related:

42

187

189

The first one is most relevant. I haven't found the time to implement this. PRs are -- obviously! -- welcome.

Tjalling-dejong commented 5 months ago

Thanks again, I'm closing this issue since the original issue is not an issue anymore.