Deltares / xugrid

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

consider prevent `UgridDataset` type if no grid present #180

Open veenstrajelmer opened 9 months ago

veenstrajelmer commented 9 months ago

When loading a non-ugrid dataset with xugrid, it is converted to a UgridDataset anyway. This is a bit inconvenient, since checking whether it is really a dataset with ugrid, can only be done by checking if it has a "grid".

import xugrid as xu
import xarray as xr

file_nc = "test.nc"
ds = xr.tutorial.open_dataset("air_temperature")
ds.to_netcdf(file_nc)

uds = xu.open_dataset(file_nc)

print(type(uds)) # xugrid.core.wrap.UgridDataset
uds.ugrid # works
uds.grid # fails, zero grids
Huite commented 9 months ago

You could check the xarray object too, there's an xarray accessor (via .ugrid_roles): https://deltares.github.io/xugrid/api.html#ugrid-roles-accessor

uds = xu.data.disk()
ds = uds.ugrid.to_dataset()
print(ds.ugrid_roles.topology)  # ["mesh2d"]

# If there's no UGRID stuff in there, the list is empty, so you could do:
if ds.ugrid_roles.topology:
    uds = xu.UgridDataset(ds)
veenstrajelmer commented 9 months ago

Ok, but the ugrid roles from a UgridDataset are None, since the grid part is under the grid accessor (if it is present)

This issue also relates to grid preservation with operations: https://github.com/Deltares/xugrid/issues/181

Huite commented 9 months ago

When loading a non-ugrid dataset with xugrid, it is converted to a UgridDataset anyway.

I guess I should've asked to start with: why are you reading non-UGRID data with xugrid anyway?

Just like you should use pandas to read CSV's rather than xarray, you should use xarray to read non-UGRID datasets. So is the actual question: what's the proper way to check whether a UgridDataset is really a proper UGRID thing?

Maybe related, what I have been thinking about: if the work on xarray's explicit indexes is done, we would get rid of UgridDataset and UgridDataArray, and .ugrid would be an ordinary xarray accessor. That means that typechecking for UgridDataset/UgridDataArray will no longer work. Instead we would add a .ugrid.is_ugrid property (or something) instead -- not quite relevant now, but maybe it does the thing you're after anyway?