{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#import jupyter\n",
    "import os\n",
    "import pandas as pd\n",
    "import geopandas as gpd\n",
    "import netCDF4 as nc\n",
    "import math\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from scipy.interpolate import LinearNDInterpolator, interp1d\n",
    "\n",
    "from dfm_tools.get_nc import get_netdata, get_ncmodeldata, plot_netmapdata\n",
    "from dfm_tools.get_nc_helpers import get_timesfromnc\n",
    "import cartopy.crs as ccrs\n",
    "import contextily as ctx\n",
    "from dfm_tools.regulargrid import scatter_to_regulargrid\n",
    "\n",
    "from pathlib import Path"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "pycharm": {
     "name": "#%% Read Model Log\n"
    }
   },
   "outputs": [],
   "source": [
    "runLog = pd.read_excel('C:/Users/arey/files\\Projects/Newtown/Model Log NTC.xlsx', 'ModelLog')\n",
    "\n",
    "dataPath = \"FlowFM_map.nc\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "pycharm": {
     "name": "#%% Import Model results\n"
    }
   },
   "outputs": [],
   "source": [
    "#modelPlot = [3, 5, 6, 7, 8]\n",
    "#modelPlot  = [2, 4, 5, 6, 7, 8]\n",
    "modelPlot  = [8, 9, 10]\n",
    "\n",
    "modelX       = [None] * (max(modelPlot)+1)\n",
    "modelY       = [None] * (max(modelPlot)+1)\n",
    "modelZ       = [None] * (max(modelPlot)+1)\n",
    "modelData    = [None] * (max(modelPlot)+1)\n",
    "modelBathy   = [None] * (max(modelPlot)+1)\n",
    "modelDataMag = [None] * (max(modelPlot)+1)\n",
    "modelDataWl  = [None] * (max(modelPlot)+1)\n",
    "\n",
    "\n",
    "\n",
    "for i in modelPlot:\n",
    "    modelPath    = Path(runLog['Python Path'][i] + \"/FlowFM/output/\") / dataPath\n",
    "\n",
    "    ncDFM = nc.Dataset(modelPath)\n",
    "    tStep = ncDFM.dimensions['time'].size\n",
    "\n",
    "    modelX[i] = ncDFM['mesh2d_face_x'][:]\n",
    "    modelY[i] = ncDFM['mesh2d_face_y'][:]\n",
    "    modelZ[i] = ncDFM['mesh2d_layer_sigma'][:]\n",
    "\n",
    "    modelData[i]    = ncDFM['mesh2d_ucmaga'][[tStep-1], :]\n",
    "    modelBathy[i]   = ncDFM['mesh2d_flowelem_bl'][:]\n",
    "    modelDataMag[i] = ncDFM['mesh2d_ucmag'][tStep-1,:, :]\n",
    "    modelDataWl[i]  = ncDFM['mesh2d_waterdepth'][tStep-1, :]\n",
    "\n",
    "    ncDFM.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "pycharm": {
     "name": "#%% Process centerline\n"
    }
   },
   "outputs": [],
   "source": [
    "ctlINUSSP = gpd.read_file(\"C:\\\\Users\\\\arey\\\\OneDrive - W.F. Baird & Associates Coastal Engineers Ltd\\\\Projects\\\\Newtown\\GIS\\\\Centerline_Dense50.shp\")\n",
    "ctlPTS = ctlINUSSP.geometry.iloc[0].coords\n",
    "\n",
    "distTick    = 0\n",
    "distTick2   = 1\n",
    "ctrlPTfiltX = []\n",
    "ctrlPTfiltY = []\n",
    "ctrlDist    = []\n",
    "\n",
    "ctrlDist.append(0)\n",
    "ctrlPTfiltX.append(ctlPTS[0][0])\n",
    "ctrlPTfiltY.append(ctlPTS[0][1])\n",
    "\n",
    "for i in range(1,len(ctlPTS)):\n",
    "    distTick = distTick + math.sqrt((ctlPTS[i-1][0]-ctlPTS[i][0])**2 + (ctlPTS[i-1][1]-ctlPTS[i][1]))\n",
    "\n",
    "    if distTick > 2:\n",
    "        ctrlPTfiltX.append(ctlPTS[i][0])\n",
    "        ctrlPTfiltY.append(ctlPTS[i][1])\n",
    "\n",
    "        ctrlDist.append(ctrlDist[-1] + distTick)\n",
    "\n",
    "        distTick = 0\n",
    "\n",
    "vertBins = np.arange(-9, 5, 0.05)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "pycharm": {
     "name": "#%% Interpolate along centerline\n"
    }
   },
   "outputs": [],
   "source": [
    "modelX2  = [None] * (max(modelPlot)+1)\n",
    "modelY2  = [None] * (max(modelPlot)+1)\n",
    "modelZ2  = [None] * (max(modelPlot)+1)\n",
    "\n",
    "ctrlMag = np.zeros((len(ctrlDist), 10, max(modelPlot)+1))\n",
    "ctrlItr = np.zeros((len(ctrlDist), len(vertBins), max(modelPlot)+1))\n",
    "\n",
    "for i in modelPlot:\n",
    "    modelX2[i] = np.zeros((10, modelX[i].shape[0]))\n",
    "    modelY2[i] = np.zeros((10, modelY[i].shape[0]))\n",
    "    modelZ2[i] = np.zeros((10, modelY[i].shape[0]))\n",
    "\n",
    "    cellDz = modelDataWl[i]/10\n",
    "\n",
    "    modelX2[i][0, :] = modelX[i]\n",
    "    modelY2[i][0, :] = modelY[i]\n",
    "    modelZ2[i][0, :] = modelBathy[i] + cellDz*0.5\n",
    "\n",
    "    for j in range(1, 10):\n",
    "        modelX2[i][j, :] = modelX[i]\n",
    "        modelY2[i][j, :] = modelY[i]\n",
    "        modelZ2[i][j, :] = modelZ2[i][j-1, :] + cellDz\n",
    "\n",
    "    ctrlBathInterp = LinearNDInterpolator(np.transpose(np.array((modelX[i], modelY[i]))), np.array(modelBathy[i]))\n",
    "    ctrlBath       = ctrlBathInterp(np.transpose(np.array((ctrlPTfiltX, ctrlPTfiltY))))\n",
    "\n",
    "    ctrlWLInterp   = LinearNDInterpolator(np.transpose(np.array((modelX[i], modelY[i]))), np.array(modelDataWl[i]))\n",
    "    ctrlWL          = ctrlWLInterp(np.transpose(np.array((ctrlPTfiltX, ctrlPTfiltY))))\n",
    "\n",
    "    ctrlDzInterp   = LinearNDInterpolator(np.transpose(np.array((modelX[i], modelY[i]))), np.array(cellDz))\n",
    "    ctrlDZ         = ctrlDzInterp(np.transpose(np.array((ctrlPTfiltX, ctrlPTfiltY))))\n",
    "\n",
    "    cellBins       = np.linspace(ctrlBath + ctrlDZ*0.5, ctrlBath + ctrlWL - ctrlDZ*0.5, 10)\n",
    "\n",
    "    ctrlMagInterp  = LinearNDInterpolator(np.transpose(np.array((np.transpose(modelX2[i]).reshape(-1),\n",
    "                            np.transpose(modelY2[i]).reshape(-1),\n",
    "                            np.transpose(modelZ2[i]).reshape(-1)))),\n",
    "                            np.transpose(np.array(modelDataMag[i]).reshape(-1)))\n",
    "\n",
    "    for v in range(0, len(ctrlDist)):\n",
    "        ctrlMag[v, :, i] = np.array(ctrlMagInterp(np.transpose(np.array((np.ones((10)) * ctrlPTfiltX[v], np.ones((10)) * ctrlPTfiltY[v], cellBins[:, v])))))\n",
    "\n",
    "        f = interp1d(np.concatenate((ctrlBath[v], cellBins[:, v], ctrlBath[v] + ctrlWL[v]), axis=None),\n",
    "                     np.concatenate((ctrlMag[v, 0, i], ctrlMag[v, :, i], ctrlMag[v, 9, i]), axis=None),\n",
    "                     bounds_error=False)\n",
    "\n",
    "        ctrlItr[v, :, i] = f(vertBins)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "pycharm": {
     "name": "#%% Plotting\n"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": "<Figure size 612x360 with 4 Axes>",
      "image/png": "[encoded data, 58976 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plotCount = 0\n",
    "fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(8.5, 5))\n",
    "fig.patch.set_facecolor('white')\n",
    "\n",
    "fig.tight_layout(pad=1.0)\n",
    "ax = axes.flat\n",
    "\n",
    "for i in modelPlot:\n",
    "    pltDat = ax[plotCount].pcolormesh(ctrlDist, vertBins, np.transpose(ctrlItr[:, :, i]),\n",
    "                shading='auto', vmin=0, vmax=0.10)\n",
    "    ax[plotCount].set_ylim(-9, 2)\n",
    "    ax[plotCount].set_xlim(3300, 3500)\n",
    "    ax[plotCount].set_title(runLog['Plotting Legend Entry'][i])\n",
    "    ax[plotCount].get_xaxis().set_visible(False)\n",
    "    plotCount = plotCount + 1\n",
    "\n",
    "ax[plotCount-1].get_xaxis().set_visible(True)\n",
    "plt.xlabel('Distance Along Transect [m]')\n",
    "plt.ylabel('Elevation [mNAVD88]')\n",
    "cbar = fig.colorbar(pltDat, ax=axes.ravel().tolist(), shrink=0.95)\n",
    "cbar.set_label('Horizontal Velocity [m/s]')\n",
    "\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "outputs": [
    {
     "data": {
      "text/plain": "<Figure size 864x360 with 3 Axes>",
      "image/png": "[encoded data, 165000 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 5))\n",
    "fig.patch.set_facecolor('white')\n",
    "\n",
    "fig.tight_layout(pad=1.0)\n",
    "ax = axes.flat\n",
    "\n",
    "plotCount = 0\n",
    "for i in modelPlot:\n",
    "\n",
    "    pltDat = ax[plotCount].scatter(modelX[i], modelY[i], c = modelData[i],\n",
    "                vmin=0, vmax=0.1)\n",
    "    ax[plotCount].set_xlim(305900, 306400)\n",
    "    ax[plotCount].set_ylim(61500, 62200)\n",
    "\n",
    "    plotCount = plotCount + 1\n",
    "\n",
    "plt.show()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% Plot 2D Spatial Map\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "reading time dimension: reconstruct array\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "analyzing netdata from domain 0000 of 0000 (counting max number of facenodes)\n",
      "processing netdata from domain 0000 of 0000\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "varname: mesh2d_ucmaga  (17, 31259)  ('time', 'mesh2d_nFaces'), coordinates=(mesh2d_face_x mesh2d_face_y)\n",
      "varname: mesh2d_face_x  (31259,)  ('mesh2d_nFaces',), coordinates=(None)\n",
      "varname: mesh2d_face_y  (31259,)  ('mesh2d_nFaces',), coordinates=(None)\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "varname: mesh2d_ucxa  (17, 31259)  ('time', 'mesh2d_nFaces'), coordinates=(mesh2d_face_x mesh2d_face_y)\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "varname: mesh2d_ucya  (17, 31259)  ('time', 'mesh2d_nFaces'), coordinates=(mesh2d_face_x mesh2d_face_y)\n",
      "reading time dimension: reconstruct array\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "analyzing netdata from domain 0000 of 0000 (counting max number of facenodes)\n",
      "processing netdata from domain 0000 of 0000\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "varname: mesh2d_ucmaga  (49, 11096)  ('time', 'mesh2d_nFaces'), coordinates=(mesh2d_face_x mesh2d_face_y)\n",
      "varname: mesh2d_face_x  (11096,)  ('mesh2d_nFaces',), coordinates=(None)\n",
      "varname: mesh2d_face_y  (11096,)  ('mesh2d_nFaces',), coordinates=(None)\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "varname: mesh2d_ucxa  (49, 11096)  ('time', 'mesh2d_nFaces'), coordinates=(mesh2d_face_x mesh2d_face_y)\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "varname: mesh2d_ucya  (49, 11096)  ('time', 'mesh2d_nFaces'), coordinates=(mesh2d_face_x mesh2d_face_y)\n",
      "reading time dimension: reconstruct array\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "analyzing netdata from domain 0000 of 0000 (counting max number of facenodes)\n",
      "processing netdata from domain 0000 of 0000\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "varname: mesh2d_ucmaga  (49, 12616)  ('time', 'mesh2d_nFaces'), coordinates=(mesh2d_face_x mesh2d_face_y)\n",
      "varname: mesh2d_face_x  (12616,)  ('mesh2d_nFaces',), coordinates=(None)\n",
      "varname: mesh2d_face_y  (12616,)  ('mesh2d_nFaces',), coordinates=(None)\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "varname: mesh2d_ucxa  (49, 12616)  ('time', 'mesh2d_nFaces'), coordinates=(mesh2d_face_x mesh2d_face_y)\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "reading time dimension: only requested indices\n",
      "retrieving original timezone succeeded, no conversion to UTC/GMT applied\n",
      "varname: mesh2d_ucya  (49, 12616)  ('time', 'mesh2d_nFaces'), coordinates=(mesh2d_face_x mesh2d_face_y)\n"
     ]
    }
   ],
   "source": [
    "ugrid_all           = [None] * (max(modelPlot)+1)\n",
    "data_frommap_wl     = [None] * (max(modelPlot)+1)\n",
    "X                   = [None] * (max(modelPlot)+1)\n",
    "Y                   = [None] * (max(modelPlot)+1)\n",
    "U                   = [None] * (max(modelPlot)+1)\n",
    "V                   = [None] * (max(modelPlot)+1)\n",
    "facex               = [None] * (max(modelPlot)+1)\n",
    "facey               = [None] * (max(modelPlot)+1)\n",
    "ux_mean             = [None] * (max(modelPlot)+1)\n",
    "uy_mean             = [None] * (max(modelPlot)+1)\n",
    "\n",
    "for i in modelPlot:\n",
    "    file_nc_map         = os.path.join(runLog['Python Path'][i],'FlowFM','output','FlowFM_map.nc')\n",
    "\n",
    "    tSteps              = get_timesfromnc(file_nc=file_nc_map, varname='time')\n",
    "    tStep               = len(tSteps)-1\n",
    "\n",
    "    ugrid_all[i]        = get_netdata(file_nc=file_nc_map)#,multipart=False)\n",
    "    data_frommap_wl[i]  = get_ncmodeldata(file_nc=file_nc_map, varname='mesh2d_ucmaga', timestep=tStep)\n",
    "    facex[i]            = get_ncmodeldata(file_nc=file_nc_map, varname='mesh2d_face_x')\n",
    "    facey[i]            = get_ncmodeldata(file_nc=file_nc_map, varname='mesh2d_face_y')\n",
    "    ux_mean[i]          = get_ncmodeldata(file_nc=file_nc_map, varname='mesh2d_ucxa', timestep=tStep)\n",
    "    uy_mean[i]          = get_ncmodeldata(file_nc=file_nc_map, varname='mesh2d_ucya', timestep=tStep)\n",
    "\n",
    "    X[i],Y[i],U[i] = scatter_to_regulargrid(xcoords=facex[i], ycoords=facey[i],\n",
    "                                            ncellx=500, ncelly=500, values=ux_mean[i][0, :], maskland_dist=10)\n",
    "    X[i],Y[i],V[i] = scatter_to_regulargrid(xcoords=facex[i], ycoords=facey[i],\n",
    "                                            ncellx=500, ncelly=500, values=uy_mean[i][0, :], maskland_dist=10)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% Import using DFM functions\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "outputs": [
    {
     "data": {
      "text/plain": "<Figure size 864x360 with 6 Axes>",
      "image/png": "[encoded data, 369096 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, axes = plt.subplots(nrows=1, ncols=3,subplot_kw={'projection': ccrs.epsg(32118)}, figsize=(12, 5))\n",
    "fig.patch.set_facecolor('white')\n",
    "\n",
    "ax = axes.flat\n",
    "\n",
    "fig.tight_layout(pad=3.0)\n",
    "plotCount = 0\n",
    "\n",
    "for i in modelPlot:\n",
    "    pc = plot_netmapdata(ugrid_all[i].verts, values=data_frommap_wl[i][0,:],\n",
    "                         ax=ax[plotCount], linewidth=0.5, cmap=\"viridis\")\n",
    "\n",
    "    ax[plotCount].set_xlim(305900, 306400)\n",
    "    ax[plotCount].set_ylim(61500, 62200)\n",
    "\n",
    "    ax[plotCount].quiver(X[i], Y[i], U[i], V[i], color='w', scale=1.00)\n",
    "\n",
    "    mapbox = 'https://api.mapbox.com/styles/v1/alexander0042/ckemxgtk51fgp19nybfmdcb1e/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiYWxleGFuZGVyMDA0MiIsImEiOiJjazVmdG4zbncwMHY4M2VrcThwZGUzZDFhIn0.w6oDHoo1eCeRlSBpwzwVtw'\n",
    "    ctx.add_basemap(ax[plotCount], source=mapbox, crs='EPSG:32118')\n",
    "\n",
    "    extent = ax[plotCount].get_extent()\n",
    "    ax[plotCount].set_xticks(np.linspace(extent[0], extent[1], 4))\n",
    "    ax[plotCount].set_yticks(np.linspace(extent[2], extent[3], 4))\n",
    "\n",
    "    pc.set_clim([0, 0.1])\n",
    "    cbar = fig.colorbar(pc, ax=ax[plotCount], shrink=0.95)\n",
    "    cbar.set_label('Depth Averaged Velocity [m/s]')\n",
    "\n",
    "    plotCount = plotCount + 1\n",
    "\n",
    "plt.show()\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% Plot using DFM functions\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "PyCharm (NTC_DFM)",
   "language": "python",
   "name": "pycharm-b2185061"
  },
  "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.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}