# pip install mikeio xarray netcdf4
import os
import mikeio
import xarray as xr
ds = mikeio.read("../tests/testdata/oresund_sigma_z.dfsu")
ds
<mikeio.Dataset> Geometry: Dfsu3DSigmaZ (4 sigma-layers, 5 z-layers) Dimensions: (time:3, element:17118) Time: 1997-09-15 21:00:00 - 1997-09-16 03:00:00 (3 records) Items: 0: Temperature <Temperature> (degree Celsius) 1: Salinity <Salinity> (PSU)
nc = ds.geometry.node_coordinates
xn = nc[:,0]
yn = nc[:,1]
zn = nc[:,2]
ec = ds.geometry.element_coordinates
xe = ec[:,0]
ye = ec[:,1]
ze = ec[:,2]
# Time
time = ds.time
# Node based data
node_ids = list(range(len(nc)))
z_dynamic = ds._zn
xn_da = xr.DataArray(xn, coords=[node_ids], dims=["nodes"], attrs={'units': 'meter'})
yn_da = xr.DataArray(xn, coords=[node_ids], dims=["nodes"], attrs={'units': 'meter'})
zn_da = xr.DataArray(zn, coords=[node_ids], dims=["nodes"], attrs={'units': 'meter'})
z_dyn_da = xr.DataArray(z_dynamic, coords =[time,node_ids],dims=["time", "nodes"], attrs={'units': 'meter'})
# Element based data
el_ids = list(range(len(ec)))
xe_da = xr.DataArray(xe, coords=[el_ids], dims=["elements"], attrs={'units': 'meter'})
ye_da = xr.DataArray(ye, coords=[el_ids], dims=["elements"], attrs={'units': 'meter'})
ze_da = xr.DataArray(ze, coords=[el_ids], dims=["elements"], attrs={'units': 'meter'})
# Add coordinates for nodes and elements
data_dict = {'x': xn_da,
'y' :yn_da,
'z' : zn_da,
'xe' : xe_da,
'ye' : ye_da,
'ze' : ze_da,
'z_dynamic' : z_dyn_da}
# add rest of data
for da in ds:
da = xr.DataArray(da.to_numpy(),
coords = [time,el_ids],
dims=["time", "elements"],
attrs={'units': da.unit.name})
data_dict[da.name] = da
# Here are some examples of global attributes, which is useful, but in most cases not required
attributes={'title:' : "Model A.2:4",
'history': 'mikeio | xarray',
'source': 'Mike 3 FM - Oresund',
'instituion': 'DHI'}
# create an xarray dataset
xr_ds = xr.Dataset(data_dict, attrs=attributes)
xr_ds.to_netcdf("oresund_sigma_z.nc")
os.remove("oresund_sigma_z.nc")