{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {
    "pycharm": {
     "name": "#%% Project Setup\n"
    }
   },
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "import jupyter\n",
    "import sys\n",
    "import pandas as pd\n",
    "import geopandas as gp\n",
    "import numpy as np\n",
    "from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar, AnchoredDirectionArrows\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.font_manager as fm\n",
    "import cartopy.crs as ccrs\n",
    "import contextily as ctx\n",
    "import cmocean.cm as cmo\n",
    "from shapely.geometry import Point, LineString\n",
    "\n",
    "from xarray.backends import NetCDF4DataStore\n",
    "import xarray as xr\n",
    "\n",
    "from datetime import datetime, timedelta\n",
    "from netCDF4 import num2date\n",
    "from metpy.units import units\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import cartopy.crs as ccrs\n",
    "import cartopy.feature as cfeature\n",
    "from metpy.plots import ctables\n",
    "\n",
    "from siphon.catalog import TDSCatalog"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [],
   "source": [
    "def find_time_var(var, time_basename='time'):\n",
    "    for coord_name in var.coords:\n",
    "        if coord_name.startswith(time_basename):\n",
    "            return var.coords[coord_name]\n",
    "    raise ValueError('No time variable found for ' + var.name)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%  Helper function for finding proper time variable\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "outputs": [],
   "source": [
    "hours = [0, 6, 12, 18]\n",
    "var = ['Temperature_surface', 'Wind_speed_gust_surface',\n",
    "       'u-component_of_wind_height_above_ground', 'v-component_of_wind_height_above_ground']\n",
    "var_precp = ['Total_precipitation_surface_6_Hour_Accumulation']\n",
    "\n",
    "temp_1d = []\n",
    "gust_1d = []\n",
    "wndu_1d = []\n",
    "wndv_1d = []\n",
    "prep_1d = []\n",
    "time_1d = []\n",
    "\n",
    "startdate  = datetime(year=2021, month=10, day=1, hour=0, minute=0, second=0)\n",
    "enddate    = datetime(year=2021, month=10, day=7, hour=0, minute=0, second=0)\n",
    "\n",
    "date_list = pd.date_range(startdate, enddate, freq='6H')\n",
    "\n",
    "for date in date_list:\n",
    "    # Base URL for 0.5 degree GFS data\n",
    "    best_gfs = TDSCatalog('https://www.ncei.noaa.gov/thredds/catalog/model-gfs-g4-anl-files/' +\n",
    "                        date.strftime('%Y%m') + '/' + date.strftime('%Y%m%d') + '/' + 'catalog.xml')\n",
    "\n",
    "    # Generate URLs for specific grib file\n",
    "    best_ds         = best_gfs.datasets['gfs_4_'+date.strftime('%Y%m%d_%H%M')+'_000.grb2']\n",
    "    best_ds_precp   = best_gfs.datasets['gfs_4_'+date.strftime('%Y%m%d_%H%M')+'_006.grb2']\n",
    "\n",
    "    # Format the query parameters\n",
    "    ncss  = best_ds.subset()\n",
    "    query = ncss.query()\n",
    "\n",
    "    ncss_precp  = best_ds_precp.subset()\n",
    "    query_precp = ncss_precp.query()\n",
    "\n",
    "    # Extract data from specific point\n",
    "    query.lonlat_point(-75.6972, 45.4215).time(date)\n",
    "    query.accept('netcdf')\n",
    "    query.variables(var[0], var[1], var[2], var[3])\n",
    "    query.vertical_level(0) #10 m\n",
    "\n",
    "    data = ncss.get_data(query)\n",
    "    data = xr.open_dataset(NetCDF4DataStore(data), drop_variables='height_above_ground4')\n",
    "\n",
    "    query_precp.lonlat_point(-75.6972, 45.4215).time(date + timedelta(hours=6))\n",
    "    query_precp.accept('netcdf')\n",
    "    query_precp.variables(var_precp[0])\n",
    "    query_precp.vertical_level(0) #10 m\n",
    "\n",
    "    data_precp = ncss_precp.get_data(query_precp)\n",
    "    data_precp = xr.open_dataset(NetCDF4DataStore(data_precp))\n",
    "\n",
    "    temp_3d = data[var[0]]\n",
    "    gust_3d = data[var[1]]\n",
    "    wndu_3d = data[var[2]]\n",
    "    wndv_3d = data[var[3]]\n",
    "    prep_3d = data_precp[var_precp[0]]\n",
    "\n",
    "    # Read the individual point (with units) and append to the list\n",
    "    temp_1d.append(temp_3d.metpy.unit_array.squeeze())\n",
    "    gust_1d.append(gust_3d.metpy.unit_array.squeeze())\n",
    "    wndu_1d.append(wndu_3d.metpy.unit_array.squeeze())\n",
    "    wndv_1d.append(wndv_3d.metpy.unit_array.squeeze())\n",
    "    prep_1d.append(prep_3d.metpy.unit_array.squeeze())\n",
    "    time_1d.append(find_time_var(temp_3d))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% GFS Import\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "outputs": [
    {
     "data": {
      "text/plain": "<Figure size 1080x864 with 1 Axes>",
      "image/png": "[encoded data, 62424 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig = plt.figure(figsize=(15, 12))\n",
    "fig.patch.set_facecolor('white')\n",
    "plt.plot([i.values[0] for i in time_1d], [i.m.item(0) for i in temp_1d])\n",
    "\n",
    "plt.show()\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% Create a new figure\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "pycharm": {
     "name": "#%% RBR Import Data\n"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\arey\\Anaconda3\\envs\\BairdBase\\lib\\site-packages\\openpyxl\\styles\\stylesheet.py:221: UserWarning: Workbook contains no default style, apply openpyxl's default\n",
      "  warn(\"Workbook contains no default style, apply openpyxl's default\")\n"
     ]
    }
   ],
   "source": [
    "# RBR\n",
    "RBR_QF = pd.read_excel(\"C:/Users/arey/files/Projects/West Coast/Observations3/065654_20211104_1521 Old Queens Fort.xlsx\",\n",
    "                         sheet_name='Data', skiprows=0, header=1)\n",
    "RBR_GH = pd.read_excel(\"C:/Users/arey/files/Projects/West Coast/Observations3/065654_20211104_1203  Great House.xlsx\",\n",
    "                         sheet_name='Data', skiprows=0, header=1)\n",
    "RBR_GS = pd.read_excel(\"C:/Users/arey/files/Projects/West Coast/Observations3/065654_20211104_1356 Greensleeves.xlsx\",\n",
    "                         sheet_name='Data', skiprows=0, header=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "pycharm": {
     "name": "#%% JFE Import Data\n"
    }
   },
   "outputs": [],
   "source": [
    "JFE_QF = pd.read_csv(\"C:/Users/arey/files/Projects/West Coast/Observations3/20211104_1415_ACLW-USB_0283_135438 Old Queen's Fort_A.csv\",\n",
    "                          skiprows=30)\n",
    "JFE_GH = pd.read_csv(\"C:/Users/arey/files/Projects/West Coast/Observations3/20211104_1015_ACLW-USB_0283_090208  Great House_A.csv\",\n",
    "                          skiprows=30)\n",
    "JFE_GS = pd.read_csv(\"C:/Users/arey/files/Projects/West Coast/Observations3/20211104_1215_ACLW-USB_0283_120015  Greensleeves_A.csv\",\n",
    "                          skiprows=30)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "pycharm": {
     "name": "#%% GPS Import Data\n"
    }
   },
   "outputs": [],
   "source": [
    "GPS = pd.read_csv('C:/Users/arey/files/Projects/West Coast/Observations3/export_OLDQFORT.csv',\n",
    "                          header=None, names=['Index', 'Date1', 'Time1', 'Date2', 'Time2', 'Northing', 'North', 'Easting', 'East', 'Var1', 'Var2'])\n",
    "#convert GPS data to geodataframe\n",
    "GPS_gdf = gp.GeoDataFrame(GPS, geometry=gp.points_from_xy(-GPS.Easting, GPS.Northing, crs=\"EPSG:4326\"))\n",
    "\n",
    "GPS_gdf['DateTime'] = pd.to_datetime(GPS_gdf['Date2'].astype(str) + ' ' + GPS_gdf['Time2'].astype(str))\n",
    "\n",
    "GPS_gdf.set_index('DateTime', inplace=True)\n",
    "\n",
    "# Convert to UTM\n",
    "GPS_gdf.geometry = GPS_gdf.geometry.to_crs(\"EPSG:32621\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "pycharm": {
     "name": "#%% Merge GPS to RBR\n"
    }
   },
   "outputs": [],
   "source": [
    "# Process RBR into datetime\n",
    "RBR_QF['DateTime'] = pd.to_datetime(RBR_QF['Time'])\n",
    "RBR_QF.set_index('DateTime', inplace=True)\n",
    "RBR_QF_geo = pd.merge_asof(RBR_QF, GPS_gdf,\n",
    "                             left_index=True, right_index=True,  direction='nearest', tolerance=pd.Timedelta('300s'))\n",
    "RBR_QF_geo = gp.GeoDataFrame(RBR_QF_geo, geometry=RBR_QF_geo.geometry, crs=\"EPSG:32621\")\n",
    "\n",
    "\n",
    "RBR_GH['DateTime'] = pd.to_datetime(RBR_GH['Time'])\n",
    "RBR_GH.set_index('DateTime', inplace=True)\n",
    "\n",
    "RBR_GH_geo = pd.merge_asof(RBR_GH, GPS_gdf,\n",
    "                             left_index=True, right_index=True,  direction='nearest', tolerance=pd.Timedelta('60s'))\n",
    "RBR_GH_geo = gp.GeoDataFrame(RBR_GH_geo, geometry=RBR_GH_geo.geometry, crs=\"EPSG:32621\")\n",
    "\n",
    "\n",
    "RBR_GS['DateTime'] = pd.to_datetime(RBR_GS['Time'])\n",
    "RBR_GS.set_index('DateTime', inplace=True)\n",
    "\n",
    "RBR_GS_geo = pd.merge_asof(RBR_GS, GPS_gdf,\n",
    "                             left_index=True, right_index=True,  direction='nearest', tolerance=pd.Timedelta('60s'))\n",
    "RBR_GS_geo = gp.GeoDataFrame(RBR_GS_geo, geometry=RBR_GS_geo.geometry, crs=\"EPSG:32621\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "pycharm": {
     "name": "#%% Merge GPS to JFE\n"
    }
   },
   "outputs": [],
   "source": [
    "# Process JFE into datetime\n",
    "JFE_QF['DateTime'] = pd.to_datetime(JFE_QF['Date'])\n",
    "JFE_QF.set_index('DateTime', inplace=True)\n",
    "\n",
    "JFE_QF_geo = pd.merge_asof(JFE_QF, GPS_gdf, left_index=True, right_index=True,  direction='nearest', tolerance=pd.Timedelta('60s'))\n",
    "JFE_QF_geo = gp.GeoDataFrame(JFE_QF_geo, geometry=JFE_QF_geo.geometry, crs=\"EPSG:32621\")\n",
    "\n",
    "\n",
    "JFE_GH['DateTime'] = pd.to_datetime(JFE_GH['Date'])\n",
    "JFE_GH.set_index('DateTime', inplace=True)\n",
    "\n",
    "JFE_GH_geo = pd.merge_asof(JFE_GH, GPS_gdf, left_index=True, right_index=True,  direction='nearest', tolerance=pd.Timedelta('60s'))\n",
    "JFE_GH_geo = gp.GeoDataFrame(JFE_GH_geo, geometry=JFE_GH_geo.geometry, crs=\"EPSG:32621\")\n",
    "\n",
    "\n",
    "JFE_GS['DateTime'] = pd.to_datetime(JFE_GS['Date'])\n",
    "JFE_GS.set_index('DateTime', inplace=True)\n",
    "\n",
    "JFE_GS_geo = pd.merge_asof(JFE_GS, GPS_gdf, left_index=True, right_index=True,  direction='nearest', tolerance=pd.Timedelta('60s'))\n",
    "JFE_GS_geo = gp.GeoDataFrame(JFE_GS_geo, geometry=JFE_GS_geo.geometry, crs=\"EPSG:32621\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "outputs": [
    {
     "data": {
      "text/plain": "<Figure size 720x432 with 8 Axes>",
      "image/png": "[encoded data, 125340 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": "<Figure size 720x432 with 8 Axes>",
      "image/png": "[encoded data, 131172 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": "<Figure size 720x432 with 8 Axes>",
      "image/png": "[encoded data, 101940 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "mapbox = 'https://api.mapbox.com/styles/v1/alexander0042/ckemxgtk51fgp19nybfmdcb1e/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiYWxleGFuZGVyMDA0MiIsImEiOiJjazVmdG4zbncwMHY4M2VrcThwZGUzZDFhIn0.w6oDHoo1eCeRlSBpwzwVtw'\n",
    "# mapbox = 'https://api.mapbox.com/styles/v1/alexander0042/ckekcw3pn08am19qmqbhtq8sb/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiYWxleGFuZGVyMDA0MiIsImEiOiJjazVmdG4zbncwMHY4M2VrcThwZGUzZDFhIn0.w6oDHoo1eCeRlSBpwzwVtw'\n",
    "\n",
    "siteDats  = [RBR_QF_geo, RBR_GH_geo, RBR_GS_geo]\n",
    "siteNames = ['Queens Fort', 'Great House', 'Greensleeves']\n",
    "minTimes  = ['2021-11-04 14:26:00', '2021-11-04 11:09:00', '2021-11-04 12:26:00']\n",
    "maxTimes  = ['2021-11-04 15:05:00', '2021-11-04 11:42:00', '2021-11-04 13:44:00']\n",
    "\n",
    "\n",
    "for siteIDX, siteData in enumerate(siteDats):\n",
    "    fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 6))\n",
    "    fig.patch.set_facecolor('white')\n",
    "    fig.tight_layout(pad=3)\n",
    "\n",
    "    RBRparam = ['Depth ', 'Salinity ', 'Dissolved O₂ saturation ', 'Temperature ']\n",
    "    RBRparamName = ['Depth [m]', 'Salinity [PSU]', 'Dissolved O₂ saturation [%]', 'Temperature [degC]']\n",
    "    RBRparmCmap  = [cmo.deep, 'cividis', cmo.dense, cmo.thermal]\n",
    "    paramMin = [0.0, 35.0, 32.5, 29.0]\n",
    "    paramMax = [1.0, 36.0, 33.5, 31.0]\n",
    "    minTime  = minTimes[siteIDX]\n",
    "    maxTime  = maxTimes[siteIDX]\n",
    "    axXlim = (siteData.loc[minTime:maxTime].geometry.x.min()-100,\n",
    "                     siteData.loc[minTime:maxTime].geometry.x.max()+100)\n",
    "    axYlim = (siteData.loc[minTime:maxTime].geometry.y.min()-100,\n",
    "                     siteData.loc[minTime:maxTime].geometry.y.max()+100)\n",
    "\n",
    "    fontprops = fm.FontProperties(size=9)\n",
    "    x, y, arrow_length = 0.95, 0.93, 0.20\n",
    "\n",
    "    plt.setp(axes, xlim=axXlim, ylim=axYlim)\n",
    "\n",
    "    ax = axes.flat\n",
    "    # Salinity\n",
    "    for paramIDX, param in enumerate(RBRparam):\n",
    "        siteData.loc[minTime:maxTime].plot(\n",
    "                            column=param, ax=ax[paramIDX], vmin=paramMin[paramIDX], vmax=paramMax[paramIDX],\n",
    "                            legend=True, legend_kwds={'label': RBRparamName[paramIDX]},\n",
    "                            cmap=RBRparmCmap[paramIDX], markersize=6) # Note the space in the col name\n",
    "        ctx.add_basemap(ax[paramIDX], source=mapbox, crs='EPSG:32621')\n",
    "\n",
    "        ax[paramIDX].set_title(RBRparamName[paramIDX])\n",
    "        ax[paramIDX].set_ylabel('UTM 21N [m]')\n",
    "        ax[paramIDX].set_xlabel('UTM 21N [m]')\n",
    "        ax[paramIDX].locator_params(axis='y', nbins=3)\n",
    "        ax[paramIDX].ticklabel_format(useOffset=False, style='plain', axis='both')\n",
    "\n",
    "        #Add scale-bar\n",
    "        scalebar = AnchoredSizeBar(ax[paramIDX].transData,\n",
    "                               100, '100 m', 'lower right', pad=0.5, size_vertical=10, fontproperties=fontprops)\n",
    "        ax[paramIDX].add_artist(scalebar)\n",
    "        ax[paramIDX].annotate('N', xy=(x, y), xytext=(x, y-arrow_length),\n",
    "                arrowprops=dict(facecolor='black', width=2, headwidth=6),\n",
    "                ha='center', va='center', fontsize=13,\n",
    "                xycoords=ax[paramIDX].transAxes)\n",
    "\n",
    "    plt.show()\n",
    "    fig.savefig('C:/Users/arey/files/Projects/West Coast/Figures3/RBR_' + siteNames[siteIDX] + '.pdf',\n",
    "                 bbox_inches='tight')\n",
    "\n",
    "    fig.savefig('C:/Users/arey/files/Projects/West Coast/Figures3/RBR_' + siteNames[siteIDX] + '.png',\n",
    "                 bbox_inches='tight', dpi=500)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% Plot Points\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "pycharm": {
     "name": "#%% Plot Plot JFE Points\n"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": "<Figure size 720x432 with 8 Axes>",
      "image/png": "[encoded data, 89768 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": "<Figure size 720x432 with 8 Axes>",
      "image/png": "[encoded data, 112444 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": "<Figure size 720x432 with 8 Axes>",
      "image/png": "[encoded data, 119784 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": "<Figure size 720x432 with 8 Axes>",
      "image/png": "[encoded data, 89768 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "mapbox = 'https://api.mapbox.com/styles/v1/alexander0042/ckemxgtk51fgp19nybfmdcb1e/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiYWxleGFuZGVyMDA0MiIsImEiOiJjazVmdG4zbncwMHY4M2VrcThwZGUzZDFhIn0.w6oDHoo1eCeRlSBpwzwVtw'\n",
    "# mapbox = 'https://api.mapbox.com/styles/v1/alexander0042/ckekcw3pn08am19qmqbhtq8sb/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiYWxleGFuZGVyMDA0MiIsImEiOiJjazVmdG4zbncwMHY4M2VrcThwZGUzZDFhIn0.w6oDHoo1eCeRlSBpwzwVtw'\n",
    "\n",
    "JFEDats  = [JFE_QF_geo, JFE_GH_geo, JFE_GS_geo]\n",
    "siteNames = ['Queens Fort', 'Great House', 'Greensleeves']\n",
    "minTimes  = ['2021-11-04 14:26:00', '2021-11-04 11:09:00', '2021-11-04 12:26:00']\n",
    "maxTimes  = ['2021-11-04 15:05:00', '2021-11-04 11:42:00', '2021-11-04 13:44:00']\n",
    "\n",
    "JFEparam     = ['Temp.[deg C]', 'Turb. -M[FTU]', 'Chl-a[ug/l]', 'Chl-Flu.[ppb]']\n",
    "JFEparamName = ['Temperature [degC]', 'Turbidity [FTU]', 'Chl-a [ug/l]', 'Chl-Flu. [ppb]']\n",
    "JFEparamCmp  = [cmo.thermal, cmo.turbid, cmo.algae, cmo.algae]\n",
    "paramMin = [29.0, 0.0, 0.0, 0.0]\n",
    "paramMax = [31.0, 1.0, 1.0, 1.0]\n",
    "\n",
    "for siteIDX, siteData in enumerate(JFEDats):\n",
    "    fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 6))\n",
    "    fig.patch.set_facecolor('white')\n",
    "    fig.tight_layout(pad=3)\n",
    "\n",
    "    minTime  = minTimes[siteIDX]\n",
    "    maxTime  = maxTimes[siteIDX]\n",
    "    axXlim = (siteData.loc[minTime:maxTime].geometry.x.min()-100,\n",
    "                     siteData.loc[minTime:maxTime].geometry.x.max()+100)\n",
    "    axYlim = (siteData.loc[minTime:maxTime].geometry.y.min()-100,\n",
    "                     siteData.loc[minTime:maxTime].geometry.y.max()+100)\n",
    "\n",
    "    fontprops = fm.FontProperties(size=9)\n",
    "    x, y, arrow_length = 0.95, 0.93, 0.20\n",
    "\n",
    "    plt.setp(axes, xlim=axXlim, ylim=axYlim)\n",
    "\n",
    "    ax = axes.flat\n",
    "    # Salinity\n",
    "    for paramIDX, param in enumerate(JFEparam):\n",
    "        siteData.loc[minTime:maxTime].plot(\n",
    "                            column=param, ax=ax[paramIDX], vmin=paramMin[paramIDX], vmax=paramMax[paramIDX],\n",
    "                            legend=True, legend_kwds={'label': JFEparamName[paramIDX]},\n",
    "                            cmap=JFEparamCmp[paramIDX], markersize=6) # Note the space in the col name\n",
    "        ctx.add_basemap(ax[paramIDX], source=mapbox, crs='EPSG:32621')\n",
    "\n",
    "        ax[paramIDX].set_title(JFEparamName[paramIDX])\n",
    "        ax[paramIDX].set_ylabel('UTM 21N [m]')\n",
    "        ax[paramIDX].set_xlabel('UTM 21N [m]')\n",
    "        ax[paramIDX].locator_params(axis='y', nbins=3)\n",
    "        ax[paramIDX].ticklabel_format(useOffset=False, style='plain', axis='both')\n",
    "\n",
    "        #Add scale-bar\n",
    "        scalebar = AnchoredSizeBar(ax[paramIDX].transData,\n",
    "                               100, '100 m', 'lower right', pad=0.5, size_vertical=10, fontproperties=fontprops)\n",
    "        ax[paramIDX].add_artist(scalebar)\n",
    "        ax[paramIDX].annotate('N', xy=(x, y), xytext=(x, y-arrow_length),\n",
    "                arrowprops=dict(facecolor='black', width=2, headwidth=6),\n",
    "                ha='center', va='center', fontsize=13,\n",
    "                xycoords=ax[paramIDX].transAxes)\n",
    "\n",
    "    plt.show()\n",
    "    fig.savefig('C:/Users/arey/files/Projects/West Coast/Figures3/JFE_' + siteNames[siteIDX] + '.pdf',\n",
    "                 bbox_inches='tight')\n",
    "\n",
    "    fig.savefig('C:/Users/arey/files/Projects/West Coast/Figures3/JFE_' + siteNames[siteIDX] + '.png',\n",
    "                 bbox_inches='tight', dpi=500)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "pycharm": {
     "name": "#%% Plot time series for Geo data\n"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": "<Figure size 864x1080 with 7 Axes>",
      "image/png": "[encoded data, 227948 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": "<Figure size 864x1080 with 7 Axes>",
      "image/png": "[encoded data, 211196 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": "<Figure size 864x1080 with 7 Axes>",
      "image/png": "[encoded data, 216428 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "siteDats = [RBR_QF_geo, RBR_GH_geo, RBR_GS_geo]\n",
    "JFEDats  = [JFE_QF_geo, JFE_GH_geo, JFE_GS_geo]\n",
    "siteNames = ['Queens Fort', 'Great House', 'Greensleeves']\n",
    "minTimes  = ['2021-11-04 14:26:00', '2021-11-04 11:10:00', '2021-11-04 12:26:00']\n",
    "maxTimes  = ['2021-11-04 15:05:00', '2021-11-04 11:42:00', '2021-11-04 13:44:00']\n",
    "\n",
    "RBRparam = ['Depth ', 'Salinity ', 'Dissolved O₂ saturation ', 'Temperature ']\n",
    "RBRparamName = ['Depth [m]', 'Salinity [PSU]', 'Dissolved O₂ saturation [%]', 'Temperature [degC]']\n",
    "RBRparamMin = [0.0, 34.5, 32.0, 29.0]\n",
    "RBRparamMax = [1.0, 35.5, 34.0, 31.0]\n",
    "\n",
    "JFEparam     = ['Temp.[deg C]', 'Chl-Flu.[ppb]', 'Turb. -M[FTU]']\n",
    "JFEparamName = ['Temperature [degC]', 'Chl-Flu. [ppb]', 'Turbidity [FTU]']\n",
    "JFEparamMin  = [29.0, 0.0, 0.0]\n",
    "JFEparamMax  = [31.0, 1.0, 20.0]\n",
    "\n",
    "\n",
    "for siteIDX in range(0,3):\n",
    "\n",
    "    fig, axes = plt.subplots(nrows=7, ncols=1, figsize=(12, 15))\n",
    "    fig.patch.set_facecolor('white')\n",
    "    fig.tight_layout(pad=3)\n",
    "\n",
    "    dataTable = np.zeros([7, 4, 3])\n",
    "\n",
    "    minTime = minTimes[siteIDX]\n",
    "    maxTime = maxTimes[siteIDX]\n",
    "\n",
    "    for paramIDX, param in enumerate(RBRparam):\n",
    "        siteDats[siteIDX].loc[minTime:maxTime, param].plot(\n",
    "                        ax=axes[paramIDX], label='1 Second Observations') # Note the space in the col name\n",
    "        # siteDats[siteIDX].loc[minTime:maxTime, param].rolling(\n",
    "        #         300, win_type='hann').mean().plot(\n",
    "        #         ax=axes[paramIDX], label='15 Minute Average') # Note the space in the col name\n",
    "\n",
    "        dataTable[paramIDX, 0, siteIDX] = siteDats[siteIDX].loc[minTime:maxTime, param].mean(skipna=True)\n",
    "        dataTable[paramIDX, 1, siteIDX] = siteDats[siteIDX].loc[minTime:maxTime, param].std(skipna=True)\n",
    "        dataTable[paramIDX, 2, siteIDX] = siteDats[siteIDX].loc[minTime:maxTime, param].min(skipna=True)\n",
    "        dataTable[paramIDX, 3, siteIDX] = siteDats[siteIDX].loc[minTime:maxTime, param].max(skipna=True)\n",
    "\n",
    "        axes[paramIDX].set_ylabel(RBRparamName[paramIDX])\n",
    "        axes[paramIDX].set_title('RBR: ' + RBRparamName[paramIDX])\n",
    "        axes[paramIDX].set_xlabel('')\n",
    "        axes[paramIDX].set_ylim(RBRparamMin[paramIDX], RBRparamMax[paramIDX])\n",
    "        axes[paramIDX].legend(loc='upper right')\n",
    "\n",
    "    for paramIDX, param in enumerate(JFEparam):\n",
    "        JFEDats[siteIDX].loc[minTime:maxTime, param].plot(\n",
    "                        ax=axes[paramIDX+4], label='15 Second Observations') # Note the space in the col name\n",
    "        # JFEDats[siteIDX].loc[minTime:maxTime, param].rolling(\n",
    "        #             300, win_type='gaussian',center=True).mean(std=5).plot(\n",
    "        #             ax=axes[paramIDX+4], label='15 Minute Average') # Note the space in the col name\n",
    "\n",
    "        dataTable[paramIDX+4, 0, siteIDX] = JFEDats[siteIDX].loc[minTime:maxTime, param].mean(skipna=True)\n",
    "        dataTable[paramIDX+4, 1, siteIDX] = JFEDats[siteIDX].loc[minTime:maxTime, param].std(skipna=True)\n",
    "        dataTable[paramIDX+4, 2, siteIDX] = JFEDats[siteIDX].loc[minTime:maxTime, param].min(skipna=True)\n",
    "        dataTable[paramIDX+4, 3, siteIDX] = JFEDats[siteIDX].loc[minTime:maxTime, param].max(skipna=True)\n",
    "\n",
    "        axes[paramIDX+4].set_ylabel(JFEparamName[paramIDX])\n",
    "        axes[paramIDX+4].set_title('JFE: ' + JFEparamName[paramIDX])\n",
    "        axes[paramIDX+4].set_xlabel('')\n",
    "        # Set turbidity to log\n",
    "        # if paramIDX==2:\n",
    "        #     axes[6].set_yscale('log')\n",
    "        axes[paramIDX+4].set_ylim(JFEparamMin[paramIDX], JFEparamMax[paramIDX])\n",
    "        axes[paramIDX+4].legend(loc='upper right')\n",
    "\n",
    "    axes[paramIDX+4].set_xlabel('Date (2021)')\n",
    "\n",
    "    dfOut = pd.DataFrame (dataTable[:, :, siteIDX])\n",
    "    # Change the column names\n",
    "    dfOut.columns =['Mean', 'Standard Deviation', 'Min', 'Max']\n",
    "    # Change the row indexes\n",
    "    dfOut.index = [RBRparamName + JFEparamName]\n",
    "\n",
    "\n",
    "    plt.show()\n",
    "    # dfOut.to_excel('C:/Users/arey/files/Projects/West Coast/Figures3/' + siteNames[siteIDX] + '_Stats.xlsx')\n",
    "    # fig.savefig('C:/Users/arey/files/Projects/West Coast/Figures3/TS_' + siteNames[siteIDX] + '.pdf',\n",
    "    #              bbox_inches='tight')\n",
    "    # fig.savefig('C:/Users/arey/files/Projects/West Coast/Figures3/TS_' + siteNames[siteIDX] + '.png',\n",
    "    #              bbox_inches='tight', dpi=500)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "PyCharm (Mustique)",
   "language": "python",
   "name": "pycharm-78fc648f"
  },
  "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
}