#!/usr/bin/env python # coding: utf-8 # # DFS2 - Export to NetCDF # In[1]: # pip install mikeio xarray netcdf4 # In[2]: import mikeio import xarray as xr import numpy as np # In[3]: ds = mikeio.read("../tests/testdata/gebco_sound.dfs2") # In[4]: ds.Elevation.plot(); # The simplest approach is to use the `Dataset.to_xarray()` or `DataArray.to_xarray()` method, if no custom information is neeeded. # In[5]: xr_ds = ds.to_xarray() xr_ds # In[6]: xr_da = ds.Elevation.to_xarray() xr_da # Save it as a NetCDF file: # In[7]: xr_da.to_netcdf("gebco_std.nc") # ## Customized NetCDF # 1. Time-invariant file -> remove time dimension # 2. Rename y, x to lat, lon # 3. Lowercase names # 4. Add other metadata # In[8]: x = ds.geometry.x y = ds.geometry.y # In[9]: res = {} spdims = ["lat", "lon"] if len(ds.time) > 1: dims = ["t"] + spdims coords = {"t": ds.time} else: dims = spdims coords = {} coords["lon"] = xr.DataArray(x, dims="lon", attrs={"standard_name" : "longitude", "units" : "degrees_east"}) coords["lat"] = xr.DataArray(y, dims="lat", attrs={"standard_name" : "latitude", "units" : "degrees_north"}) for da in ds: name = da.name.lower() res[name] = xr.DataArray(np.squeeze(da.to_numpy()), dims=dims, attrs={'name': name, # TODO add standard name from https://cfconventions.org/standard-names.html 'units': da.unit.name, 'eumType' : da.type, 'eumUnit' : da.unit}) xr_ds = xr.Dataset(res, coords=coords, attrs={'title': 'Converted from Dfs2 by MIKE IO'}) # In[10]: xr_ds # In[11]: xr_ds.elevation.plot(); # In[12]: xr_ds.to_netcdf("gebco.nc") # # Clean up # In[13]: import os os.remove("gebco_std.nc") os.remove("gebco.nc")