# pip install mikeio xarray netcdf4
Dfsu - Export to netcdf
NetCDF
- Read data from dfsu file
- Convert to xarray dataset
- Write to netcdf file
import os
import mikeio
import xarray as xr
= mikeio.read("../tests/testdata/oresund_sigma_z.dfsu")
ds 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)
= ds.geometry.node_coordinates
nc = nc[:,0]
xn = nc[:,1]
yn = nc[:,2]
zn
= ds.geometry.element_coordinates
ec = ec[:,0]
xe = ec[:,1]
ye = ec[:,2] ze
# Time
= ds.time
time
# Node based data
= list(range(len(nc)))
node_ids = ds._zn
z_dynamic = xr.DataArray(xn, coords=[node_ids], dims=["nodes"], attrs={'units': 'meter'})
xn_da = xr.DataArray(xn, coords=[node_ids], dims=["nodes"], attrs={'units': 'meter'})
yn_da = xr.DataArray(zn, coords=[node_ids], dims=["nodes"], attrs={'units': 'meter'})
zn_da = xr.DataArray(z_dynamic, coords =[time,node_ids],dims=["time", "nodes"], attrs={'units': 'meter'})
z_dyn_da
# Element based data
= list(range(len(ec)))
el_ids = xr.DataArray(xe, coords=[el_ids], dims=["elements"], attrs={'units': 'meter'})
xe_da = xr.DataArray(ye, coords=[el_ids], dims=["elements"], attrs={'units': 'meter'})
ye_da = xr.DataArray(ze, coords=[el_ids], dims=["elements"], attrs={'units': 'meter'}) ze_da
# Add coordinates for nodes and elements
= {'x': xn_da,
data_dict '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:
= xr.DataArray(da.to_numpy(),
da = [time,el_ids],
coords =["time", "elements"],
dims={'units': da.unit.name})
attrs
= da
data_dict[da.name]
# Here are some examples of global attributes, which is useful, but in most cases not required
={'title:' : "Model A.2:4",
attributes'history': 'mikeio | xarray',
'source': 'Mike 3 FM - Oresund',
'instituion': 'DHI'}
# create an xarray dataset
= xr.Dataset(data_dict, attrs=attributes) xr_ds
"oresund_sigma_z.nc") xr_ds.to_netcdf(
Clean up
import os
"oresund_sigma_z.nc") os.remove(