Deltares / xugrid

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

Add UgridDataset.from_structured method #8

Open Huite opened 2 years ago

Huite commented 2 years ago

UgridDataArray already has a from_structured constructor, but doing so for every variable of a dataset means rederiving the UGRID topology every time -- so just do it once, then figure out how to add every variable.

Huite commented 7 months ago

Some tedious details:

veenstrajelmer commented 5 months ago

This would be amazing. The cumbersome workaround code is below. Also note the rename_dims and rename_vars that are necessary until https://github.com/Deltares/xugrid/issues/9 is fixed.

import xarray as xr
import xugrid as xu
import matplotlib.pyplot as plt
plt.close("all")

def convert_struct_to_ugrid(ds):
    ds = ds.rename_dims({"longitude":"x","latitude":"y"})
    ds = ds.rename_vars({"longitude":"x","latitude":"y"})
    list_vars = []
    for var in ds.data_vars:
        uda = xu.UgridDataArray.from_structured(ds[var])
        list_vars.append(uda)
    uds = xu.UgridDataset(grids=[uda.grid])
    for var in list_vars:
        uds[var.name] = var

    return uds

file_nc = r"c:\DATA\dfm_tools\docs\notebooks\Bonaire_model\data\cmems\cmems_so_2022-11-01.nc"

ds = xr.open_dataset(file_nc)
uds = convert_struct_to_ugrid(ds)

fig,ax = plt.subplots()
ds.so.isel(time=-1, depth=0).plot()

fig,ax = plt.subplots()
uds.so.isel(time=-1, depth=0).ugrid.plot()
uds.ugrid.to_netcdf(file_nc.replace(".nc","_ugrid.nc"))