{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Dfsu - Export to netcdf\n",
    "* Read data from dfsu file\n",
    "* Convert to xarray dataset\n",
    "* Write to netcdf file"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# pip install mikeio xarray netcdf4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import mikeio\n",
    "import xarray as xr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<mikeio.Dataset>\n",
       "Geometry: Dfsu3DSigmaZ (4 sigma-layers, 5 z-layers)\n",
       "Dimensions: (time:3, element:17118)\n",
       "Time: 1997-09-15 21:00:00 - 1997-09-16 03:00:00 (3 records)\n",
       "Items:\n",
       "  0:  Temperature <Temperature> (degree Celsius)\n",
       "  1:  Salinity <Salinity> (PSU)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ds = mikeio.read(\"../tests/testdata/oresund_sigma_z.dfsu\")\n",
    "ds"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "nc = ds.geometry.node_coordinates\n",
    "xn = nc[:,0]\n",
    "yn = nc[:,1]\n",
    "zn = nc[:,2]\n",
    "\n",
    "ec = ds.geometry.element_coordinates\n",
    "xe = ec[:,0]\n",
    "ye = ec[:,1]\n",
    "ze = ec[:,2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Time\n",
    "time = ds.time\n",
    "\n",
    "# Node based data\n",
    "node_ids = list(range(len(nc)))\n",
    "z_dynamic = ds._zn\n",
    "xn_da = xr.DataArray(xn, coords=[node_ids], dims=[\"nodes\"], attrs={'units': 'meter'})\n",
    "yn_da = xr.DataArray(xn, coords=[node_ids], dims=[\"nodes\"], attrs={'units': 'meter'})\n",
    "zn_da = xr.DataArray(zn, coords=[node_ids], dims=[\"nodes\"], attrs={'units': 'meter'})\n",
    "z_dyn_da = xr.DataArray(z_dynamic, coords =[time,node_ids],dims=[\"time\", \"nodes\"], attrs={'units': 'meter'})\n",
    "\n",
    "# Element based data\n",
    "el_ids = list(range(len(ec)))\n",
    "xe_da = xr.DataArray(xe, coords=[el_ids], dims=[\"elements\"], attrs={'units': 'meter'})\n",
    "ye_da = xr.DataArray(ye, coords=[el_ids], dims=[\"elements\"], attrs={'units': 'meter'})\n",
    "ze_da = xr.DataArray(ze, coords=[el_ids], dims=[\"elements\"], attrs={'units': 'meter'})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Add coordinates for nodes and elements\n",
    "data_dict = {'x': xn_da,\n",
    "             'y' :yn_da,\n",
    "             'z' : zn_da,\n",
    "             'xe' : xe_da,\n",
    "             'ye' : ye_da,\n",
    "             'ze' : ze_da,\n",
    "             'z_dynamic' : z_dyn_da}\n",
    "\n",
    "# add rest of data\n",
    "for da in ds:\n",
    "        da = xr.DataArray(da.to_numpy(), \n",
    "                          coords = [time,el_ids],\n",
    "                          dims=[\"time\", \"elements\"],\n",
    "                          attrs={'units': da.unit.name})\n",
    "\n",
    "        data_dict[da.name] = da\n",
    "\n",
    "\n",
    "# Here are some examples of global attributes, which is useful, but in most cases not required\n",
    "attributes={'title:' : \"Model A.2:4\",\n",
    "            'history': 'mikeio | xarray',\n",
    "            'source': 'Mike 3 FM - Oresund',\n",
    "            'instituion': 'DHI'}\n",
    "\n",
    "# create an xarray dataset\n",
    "xr_ds = xr.Dataset(data_dict, attrs=attributes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "xr_ds.to_netcdf(\"oresund_sigma_z.nc\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Clean up"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "os.remove(\"oresund_sigma_z.nc\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}