You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
nsw-2016-storm-impact/notebooks/07_longshore_plotting.ipynb

349 lines
11 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Longshore plots of each beach\n",
"- Need to create a longshore plot of each beach to see how the variables change alongshore."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup notebook"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Enable autoreloading of our modules. \n",
"# Most of the code will be located in the /src/ folder, \n",
"# and then called from the notebook.\n",
"%matplotlib inline\n",
"%reload_ext autoreload\n",
"%autoreload"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from IPython.core.debugger import set_trace\n",
"\n",
"import pandas as pd\n",
"import numpy as np\n",
"import os\n",
"import decimal\n",
"import plotly\n",
"import plotly.graph_objs as go\n",
"import plotly.plotly as py\n",
"import plotly.tools as tls\n",
"import plotly.figure_factory as ff\n",
"from plotly import tools\n",
"import plotly.io as pio\n",
"from scipy import stats\n",
"import math\n",
"import matplotlib\n",
"from matplotlib import cm\n",
"import colorlover as cl\n",
"from tqdm import tqdm_notebook\n",
"from ipywidgets import widgets, Output\n",
"from IPython.display import display, clear_output, Image, HTML\n",
"from scipy import stats\n",
"from sklearn.metrics import confusion_matrix\n",
"import matplotlib.pyplot as plt\n",
"from scipy.interpolate import interp1d\n",
"from pandas.api.types import CategoricalDtype"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Matplot lib default settings\n",
"plt.rcParams[\"figure.figsize\"] = (10,6)\n",
"plt.rcParams['axes.grid']=True\n",
"plt.rcParams['grid.alpha'] = 0.5\n",
"plt.rcParams['grid.color'] = \"grey\"\n",
"plt.rcParams['grid.linestyle'] = \"--\"\n",
"plt.rcParams['axes.grid']=True\n",
"\n",
"# https://stackoverflow.com/a/20709149\n",
"matplotlib.rcParams['text.usetex'] = True\n",
"\n",
"matplotlib.rcParams['text.latex.preamble'] = [\n",
" r'\\usepackage{siunitx}', # i need upright \\micro symbols, but you need...\n",
" r'\\sisetup{detect-all}', # ...this to force siunitx to actually use your fonts\n",
" r'\\usepackage{helvet}', # set the normal font here\n",
" r'\\usepackage{amsmath}',\n",
" r'\\usepackage{sansmath}', # load up the sansmath so that math -> helvet\n",
" r'\\sansmath', # <- tricky! -- gotta actually tell tex to use!\n",
"] "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Import data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def df_from_csv(csv, index_col, data_folder='../data/interim'):\n",
" print('Importing {}'.format(csv))\n",
" return pd.read_csv(os.path.join(data_folder,csv), index_col=index_col)\n",
"\n",
"df_waves = df_from_csv('waves.csv', index_col=[0, 1])\n",
"df_tides = df_from_csv('tides.csv', index_col=[0, 1])\n",
"df_profiles = df_from_csv('profiles.csv', index_col=[0, 1, 2])\n",
"df_sites = df_from_csv('sites.csv', index_col=[0])\n",
"df_profile_features_crest_toes = df_from_csv('profile_features_crest_toes.csv', index_col=[0,1])\n",
"\n",
"# Note that the forecasted data sets should be in the same order for impacts and twls\n",
"impacts = {\n",
" 'forecasted': {\n",
" 'foreshore_slope_sto06': df_from_csv('impacts_forecasted_foreshore_slope_sto06.csv', index_col=[0]),\n",
" 'mean_slope_sto06': df_from_csv('impacts_forecasted_mean_slope_sto06.csv', index_col=[0]),\n",
" },\n",
" 'observed': df_from_csv('impacts_observed.csv', index_col=[0])\n",
" }\n",
"\n",
"\n",
"twls = {\n",
" 'forecasted': {\n",
" 'foreshore_slope_sto06': df_from_csv('twl_foreshore_slope_sto06.csv', index_col=[0, 1]),\n",
" 'mean_slope_sto06':df_from_csv('twl_mean_slope_sto06.csv', index_col=[0, 1]),\n",
" }\n",
"}\n",
"print('Done!')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Generate plot for each beach"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"beach = 'NARRA'\n",
"\n",
"# Get the dataframe\n",
"df = impacts['forecasted']['mean_slope_sto06']\n",
"df = df.rename(columns={'storm_regime': 'forecasted_regime'})\n",
"\n",
"df_beach = df.loc[df.index.str.contains(beach)]\n",
"\n",
"# Add information about hydrodynamics at max(R_high) time\n",
"df_beach = df_beach.merge(\n",
" twls['forecasted']['mean_slope_sto06'].drop(columns=['R_high', 'R_low']),\n",
" left_on=['site_id', 'datetime'],\n",
" right_on=['site_id', 'datetime'])\n",
"\n",
"# Add information about observed impacts\n",
"obs_impacts = impacts['observed'].rename(columns={\n",
" 'storm_regime': 'observed_regime'\n",
"}).observed_regime.to_frame()\n",
"df_beach = df_beach.merge(obs_impacts, left_on='site_id', right_on='site_id')\n",
"\n",
"# Convert storm regimes to categorical datatype\n",
"cat_type = CategoricalDtype(\n",
" categories=['swash', 'collision', 'overwash', 'inundation'], ordered=True)\n",
"df_beach.forecasted_regime = df_beach.forecasted_regime.astype(cat_type)\n",
"df_beach.observed_regime = df_beach.observed_regime.astype(cat_type)\n",
"\n",
"# Get index\n",
"n = [x for x in range(len(df_beach))][::-1]\n",
"n_sites = [x for x in df_beach.index][::-1]\n",
"\n",
"f, (ax1, ax2, ax3, ax4, ax5, ax6, ax7, ax8) = plt.subplots(\n",
" 1,\n",
" 8,\n",
" sharey=True,\n",
" figsize=(14, 8),\n",
" gridspec_kw={'width_ratios': [4, 4, 2, 2, 2, 2,2,2]})\n",
"\n",
"# Specify colors for storm regimes\n",
"cmap = {\n",
" 'swash': '#1a9850',\n",
" 'collision': '#fee08b',\n",
" 'overwash': '#d73027'\n",
"}\n",
"\n",
"colors = [cmap.get(x) for x in df_beach.observed_regime]\n",
"colors = ['#d73027' if c is None else c for c in colors]\n",
"\n",
"# Plot forecasted and observed storm regime\n",
"ax1.scatter(\n",
" df_beach.observed_regime.cat.codes.replace(-1,np.NaN),\n",
" n,\n",
" color=colors,\n",
" marker='o',\n",
" label='Observed regime')\n",
"\n",
"ax1.scatter(\n",
" df_beach.forecasted_regime.cat.codes.replace(-1,np.NaN),\n",
" n,\n",
" color='b',\n",
" marker='o',\n",
" edgecolors='black',\n",
" facecolors='none',\n",
" label='Forecasted regime')\n",
"\n",
"ax1.set_title('Storm\\nregime')\n",
"ax1.set_xticks([0,1,2,3])\n",
"ax1.set_xticklabels(['swash','collision','overwash','inundation'])\n",
"ax1.tick_params(axis='x', rotation=45)\n",
"ax1.legend(loc='center', bbox_to_anchor=(0.5, -0.15))\n",
"\n",
"# Replace yticks with site_ids\n",
"yticks = ax1.get_yticks().tolist()\n",
"yticks = [n_sites[int(y)] if 0 <= y <= len(n_sites) else y for y in yticks ]\n",
"ax1.set_yticklabels(yticks)\n",
"\n",
"# Water levels\n",
"ax2.plot(df_beach.R_high, n, color='#2c7bb6')\n",
"ax2.plot(df_beach.R_low, n, color='#2c7bb6')\n",
"ax2.fill_betweenx(\n",
" n, df_beach.R_low, df_beach.R_high, alpha=0.2, color='#2c7bb6', label='$R_{low}$ to $R_{high}$')\n",
"\n",
"# Dune elevations\n",
"ax2.plot(df_beach.dune_crest_z, n, color='#fdae61')\n",
"ax2.plot(df_beach.dune_toe_z, n, color='#fdae61')\n",
"ax2.fill_betweenx(\n",
" n, df_beach.dune_toe_z, df_beach.dune_crest_z, alpha=0.2, color='#fdae61', label='$D_{low}$ to $D_{high}$')\n",
"\n",
"ax2.set_title('TWL \\& Dune\\nElevations')\n",
"ax2.legend(loc='center',bbox_to_anchor=(0.5,-0.15))\n",
"ax2.set_xlabel('Elevation (m AHD)')\n",
"\n",
"# Plot R_high - D_low\n",
"ax3.plot(df_beach.R_high - df_beach.dune_toe_z,n,color='#999999')\n",
"ax3.axvline(x=0,color='black',linestyle=':')\n",
"ax3.set_title('$R_{high}$ - $D_{low}$')\n",
"ax3.set_xlabel('Height (m)')\n",
"ax3.set_xlim([-2,2])\n",
"\n",
"# Wave height, wave period, beach slope\n",
"ax4.plot(df_beach.Hs0, n,color='#377eb8')\n",
"ax4.set_title('$H_{s0}$')\n",
"ax4.set_xlabel('Sig. wave height (m)')\n",
"ax4.set_xlim([3,5])\n",
"\n",
"ax5.plot(df_beach.Tp, n,color='#e41a1c')\n",
"ax5.set_title('$T_{p}$')\n",
"ax5.set_xlabel('Peak wave period (s)')\n",
"ax5.set_xlim([8,14])\n",
"\n",
"ax6.plot(df_beach.tide, n,color='#a6cee3')\n",
"ax6.set_title('Tide')\n",
"ax6.set_xlabel('Elevation (m AHD)')\n",
"ax6.set_xlim([0,2])\n",
"\n",
"ax7.plot(df_beach.beta, n,color='#4daf4a')\n",
"ax7.set_title(r'$\\beta$')\n",
"ax7.set_xlabel('Mean prestorm\\nbeach slope')\n",
"ax7.set_xlim([0,0.15])\n",
"\n",
"ax8.plot(df_beach.R2, n,color='#6a3d9a')\n",
"ax8.set_title(r'$R_{2\\%}$')\n",
"ax8.set_xlabel('Height (m)')\n",
"\n",
"plt.tight_layout()\n",
"f.subplots_adjust(top=0.88)\n",
"f.suptitle(beach)\n",
"\n",
"\n",
"# Print to figure\n",
"plt.savefig('07-{}.png'.format(beach), dpi=600, bbox_inches='tight') \n",
"\n",
"plt.show()\n",
"plt.close()"
]
}
],
"metadata": {
"hide_input": false,
"kernelspec": {
"display_name": "Python 3",
"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.6.6"
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": true,
"sideBar": true,
"skip_h1_title": false,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": false
},
"varInspector": {
"cols": {
"lenName": 16,
"lenType": 16,
"lenVar": 40
},
"kernels_config": {
"python": {
"delete_cmd_postfix": "",
"delete_cmd_prefix": "del ",
"library": "var_list.py",
"varRefreshCmd": "print(var_dic_list())"
},
"r": {
"delete_cmd_postfix": ") ",
"delete_cmd_prefix": "rm(",
"library": "var_list.r",
"varRefreshCmd": "cat(var_dic_list()) "
}
},
"types_to_exclude": [
"module",
"function",
"builtin_function_or_method",
"instance",
"_Feature"
],
"window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 2
}