{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Solid Earth tides at California, USA at 25 December 2020"
   ]
  },
  {
   "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 cartopy import crs as ccrs, feature as cfeature\n",
    "from matplotlib import pyplot as plt, ticker, dates as mdates\n",
    "from mintpy.utils import plot as pp\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"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PYSOLID: ----------------------------------------\n",
      "PYSOLID: datetime: 2020-12-25T14:07:44\n",
      "PYSOLID: SNWE: (29.11111, 43.0, -126.0, -113.499999)\n",
      "SOLID  : calculate solid Earth tides in east/north/up direction\n",
      "SOLID  : shape: (500, 450), step size: -0.0278 by 0.0278 deg\n",
      "SOLID  : calculating / writing data to txt file: /Users/yunjunz/Downloads/solid.txt\n",
      "PYSOLID: read data from text file: /Users/yunjunz/Downloads/solid.txt\n"
     ]
    }
   ],
   "source": [
    "## inputs\n",
    "dt_obj = dt.datetime(2020, 12, 25, 14, 7, 44)\n",
    "atr = {\n",
    "    'LENGTH' : 500,                # number of rows\n",
    "    'WIDTH'  : 450,                # number of columns\n",
    "    'X_FIRST': -126,               # min longitude in degree (upper left corner of the upper left pixel)\n",
    "    'Y_FIRST': 43,                 # max laitude   in degree (upper left corner of the upper left pixel)\n",
    "    'X_STEP' :  0.000925926 * 30,  # output resolution in degree\n",
    "    'Y_STEP' : -0.000925926 * 30,  # output resolution in degree\n",
    "}\n",
    "\n",
    "## call\n",
    "tide_e, tide_n, tide_u = pysolid.calc_solid_earth_tides_grid(\n",
    "    dt_obj, atr,\n",
    "    display=False,\n",
    "    verbose=True,\n",
    ")\n",
    "\n",
    "## project ENU to radar line-of-sight (LOS) with positive for motion towards satellite\n",
    "inc_angle = np.deg2rad(34)    # radian, typical value for Sentinel-1\n",
    "az_angle  = np.deg2rad(-102)  # radian, typical value for Sentinel-1 descending track\n",
    "tide_los = (  tide_e * np.sin(inc_angle) * np.sin(az_angle) * -1\n",
    "            + tide_n * np.sin(inc_angle) * np.cos(az_angle)\n",
    "            + tide_u * np.cos(inc_angle))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "plot lat/lon label in step of 10 and location of [1, 0, 0, 1]\n",
      "plot lat/lon label in step of 10 and location of [0, 0, 0, 1]\n",
      "plot lat/lon label in step of 10 and location of [0, 0, 0, 1]\n",
      "plot lat/lon label in step of 10 and location of [0, 0, 0, 1]\n",
      "save figure to file: SET_grid.png\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 153060 characters]\n",
      "text/plain": [
       "<Figure size 900x500 with 8 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# plot\n",
    "fig, axs = plt.subplots(nrows=1, ncols=4, figsize=[9, 5], sharex=True, sharey=True, subplot_kw=dict(projection=ccrs.PlateCarree()))\n",
    "\n",
    "N = float(atr['Y_FIRST'])\n",
    "W = float(atr['X_FIRST'])\n",
    "S = N + float(atr['Y_STEP']) * int(atr['LENGTH'])\n",
    "E = W + float(atr['X_STEP']) * int(atr['WIDTH'])\n",
    "kwargs = dict(cmap='RdBu', origin='upper', extent=(W,E,S,N), interpolation='nearest')\n",
    "\n",
    "tides = [tide_e, tide_n, tide_u, tide_los]\n",
    "labels = ['East [cm]', 'North [cm]', 'Up [cm]', 'Line-of-Sight [cm]']\n",
    "lalo_locs = [[1,0,0,1],\n",
    "             [0,0,0,1],\n",
    "             [0,0,0,1],\n",
    "             [0,0,0,1]]  # left, right, top, bottom\n",
    "for i in range(len(tides)):\n",
    "    ax = axs[i]\n",
    "    im = ax.imshow(tides[i]*100, **kwargs)\n",
    "\n",
    "    # axis format\n",
    "    ax.tick_params(which='both', direction='in', bottom=True, top=True, left=True, right=True)\n",
    "    ax.coastlines(resolution='10m')\n",
    "\n",
    "    states_provinces = cfeature.NaturalEarthFeature(\n",
    "        category='cultural',\n",
    "        name='admin_1_states_provinces_lines',\n",
    "        scale='10m',\n",
    "        facecolor='none')\n",
    "    ax.add_feature(cfeature.LAND)\n",
    "    ax.add_feature(cfeature.COASTLINE)\n",
    "    ax.add_feature(states_provinces, edgecolor='k', linewidth=0.5)\n",
    "\n",
    "    pp.draw_lalo_label(geo_box=(W,N,E,S), ax=ax, projection=ccrs.PlateCarree(), lalo_loc=lalo_locs[i], lalo_step=10)\n",
    "    fig.colorbar(im, ax=ax, orientation='horizontal', label=labels[i], pad=0.07, ticks=ticker.MaxNLocator(3))\n",
    "fig.suptitle('solid Earth tides at {}'.format(dt_obj.isoformat()), y=0.7)\n",
    "fig.tight_layout()\n",
    "\n",
    "# output\n",
    "out_fig = 'SET_grid.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": "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
}
