{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Solid Earth tides at Los Angeles, USA from 2001-2021"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Go to directory /Users/yunjunz/Downloads\n"
     ]
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "import os\n",
    "import datetime as dt\n",
    "import numpy as np\n",
    "from scipy import signal\n",
    "from matplotlib import pyplot as plt, ticker, dates as mdates\n",
    "import pysolid\n",
    "plt.rcParams.update({'font.size': 12})\n",
    "\n",
    "work_dir = os.path.expanduser('~/Downloads')\n",
    "os.chdir(work_dir)\n",
    "print('Go to directory', work_dir)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Calculate SET"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PYSOLID: calculate solid Earth tides in east/north/up direction\n",
      "PYSOLID: lot/lon: 34.0/-118.0 degree\n",
      "PYSOLID: start UTC: 2001-01-01T04:00:00\n",
      "PYSOLID: end   UTC: 2021-01-01T02:00:00\n",
      "PYSOLID: time step: 600 seconds\n"
     ]
    }
   ],
   "source": [
    "# inputs\n",
    "lat, lon = 34.0, -118.0 # Los Angles, CA\n",
    "step_sec = 60 * 10\n",
    "dt0 = dt.datetime(2001,1,1,4,0,0)\n",
    "#dt0 = dt.datetime(2020,1,1,4,0,0)\n",
    "dt1 = dt.datetime(2021,1,1,2,0,0)\n",
    "\n",
    "# run\n",
    "dt_out, tide_e, tide_n, tide_u = pysolid.calc_solid_earth_tides_point(\n",
    "    lat, lon, dt0, dt1,\n",
    "    step_sec=step_sec,\n",
    "    display=False,\n",
    "    verbose=False,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plot - time-series of SET up components"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "save figure to file: SET_TS_Up.png\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 87176 characters]\n",
      "text/plain": [
       "<Figure size 864x216 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# plot\n",
    "fig, ax = plt.subplots(nrows=1, ncols=1, figsize=[12, 3])\n",
    "ax.plot(dt_out, tide_u*100, lw=1.5)\n",
    "\n",
    "# axis format\n",
    "ax.tick_params(which='both', direction='out', bottom=True, top=False, left=True, right=True)\n",
    "ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))\n",
    "ax.xaxis.set_major_locator(mdates.MonthLocator())\n",
    "ax.xaxis.set_minor_locator(mdates.DayLocator())\n",
    "ax.set_ylabel('Displacement Up [cm]')\n",
    "ax.set_title(r'solid Earth tides at Los Angeles (N34$^\\circ$, E-118$^\\circ$)')\n",
    "ax.set_xlim(dt.datetime(2020,8,27), dt.datetime(2020,12,5))\n",
    "fig.tight_layout()\n",
    "\n",
    "# output\n",
    "out_fig = 'SET_TS_Up.png'\n",
    "print('save figure to file:', out_fig)\n",
    "#fig.savefig(out_fig, bbox_inches='tight', transparent=True, dpi=600)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plot - power spectrum\n",
    "\n",
    "The same code as:\n",
    "```python\n",
    "pysolid.plot_power_spectral_density4tides(tide_u, sample_spacing=step_sec, out_fig='SET_PSD.png', fig_dpi=600, min_psd=1500)\n",
    "```\n",
    "\n",
    "### Semi-diurnal period and diurnal period"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "save figure to file: /Users/yunjunz/Downloads/SET_PSD.png\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 19340 characters]\n",
      "text/plain": [
       "<Figure size 576x216 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "## calc PSD\n",
    "freq, psd = signal.periodogram(tide_u, fs=1/step_sec, scaling='density')\n",
    "# get rid of zero in the first element\n",
    "psd = psd[1:]\n",
    "freq = freq[1:]\n",
    "period = 1./3600./freq   # period (hour)\n",
    "\n",
    "## plot\n",
    "fig, axs = plt.subplots(nrows=1, ncols=2, figsize=[8,3], sharey=True)\n",
    "for ax in axs:\n",
    "    ax.plot(period, psd, '.', ms=16, mfc='none', mew=2)\n",
    "\n",
    "# axis format\n",
    "for ax in axs:\n",
    "    ax.tick_params(which='both', direction='out', bottom=True, top=True, left=True, right=True)\n",
    "    ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())\n",
    "    ax.set_xlabel('Period [hour]')\n",
    "axs[0].set_xlim(11.3, 13.2)\n",
    "axs[1].set_xlim(22.0, 28.0)\n",
    "ax = axs[0]\n",
    "ax.set_ylabel('Power Spectral Density\\n'+r'[$m^2/Hz$]')\n",
    "ax.set_ylim(0, ymax=axs[0].get_ylim()[1] * 1.1)\n",
    "#plt.yscale('log')\n",
    "#ax.yaxis.set_major_locator(ticker.FixedLocator([0,50e3,100e3,150e3]))\n",
    "#ax.set_yticklabels(['0','50k','100k','150k'])\n",
    "fig.tight_layout()\n",
    "\n",
    "# Tidal constituents\n",
    "for ax in axs:\n",
    "    pysolid.point.add_tidal_constituents(ax, period, psd, min_psd=0.02e6)\n",
    "axs[0].annotate('semi-diurnal', xy=(0.05,0.85), xycoords='axes fraction')\n",
    "axs[1].annotate('diurnal',      xy=(0.05,0.85), xycoords='axes fraction')\n",
    "\n",
    "# output\n",
    "out_fig = 'SET_PSD.png'\n",
    "if out_fig:\n",
    "    print('save figure to file:', os.path.abspath(out_fig))\n",
    "    fig.savefig(out_fig, bbox_inches='tight', transparent=True, dpi=600)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Short period"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "save figure to file: /Users/yunjunz/Downloads/SET_PSD_short.png\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 15756 characters]\n",
      "text/plain": [
       "<Figure size 288x216 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = plt.subplots(nrows=1, ncols=1, figsize=[4,3], sharey=True)\n",
    "ax.plot(period, psd, '.', ms=16, mfc='none', mew=2)\n",
    "\n",
    "# axis format\n",
    "ax.tick_params(which='both', direction='out', bottom=True, top=True, left=True, right=True)\n",
    "ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())\n",
    "ax.set_xlabel('Period [hour]')\n",
    "ax.set_ylabel('Power Spectral Density\\n'+r'[$m^2/Hz$]')\n",
    "ax.set_xlim(7.8, 8.7)\n",
    "plt.yscale('log')\n",
    "fig.tight_layout()\n",
    "\n",
    "# output\n",
    "out_fig = 'SET_PSD_short.png'\n",
    "if out_fig:\n",
    "    print('save figure to file:', os.path.abspath(out_fig))\n",
    "    fig.savefig(out_fig, bbox_inches='tight', transparent=True, dpi=600)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Long period"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "save figure to file: /Users/yunjunz/Downloads/SET_PSD_long.png\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 13004 characters]\n",
      "text/plain": [
       "<Figure size 288x216 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# get period in days\n",
    "period = 1./(3600.*24.)/freq   # period (hour)\n",
    "\n",
    "fig, ax = plt.subplots(nrows=1, ncols=1, figsize=[4,3], sharey=True)\n",
    "ax.plot(period, psd, '.', ms=16, mfc='none', mew=2)\n",
    "\n",
    "# axis format\n",
    "ax.tick_params(which='both', direction='out', bottom=True, top=True, left=True, right=True)\n",
    "ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())\n",
    "ax.set_xlabel('Period [day]')\n",
    "ax.set_xlim(50, 450)\n",
    "ax.set_ylabel('Power Spectral Density\\n'+r'[$m^2/Hz$]')\n",
    "plt.yscale('log')\n",
    "fig.tight_layout()\n",
    "\n",
    "# output\n",
    "out_fig = 'SET_PSD_long.png'\n",
    "if out_fig:\n",
    "    print('save figure to file:', os.path.abspath(out_fig))\n",
    "    fig.savefig(out_fig, bbox_inches='tight', transparent=True, dpi=600)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
