{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Vertical interpolation - Extrapolation options"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import nes\n",
    "import matplotlib.pyplot as plt\n",
    "from datetime import datetime\n",
    "import numpy as np\n",
    "\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "ascendant = True"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Creating base"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "var_name = 'var1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "lat_orig = 33.0\n",
    "lon_orig = -15.0\n",
    "inc_lat = 1.0\n",
    "inc_lon = 1.0\n",
    "n_lat = 13\n",
    "n_lon = 25\n",
    "\n",
    "nessy = nes.create_nes(info=False, projection='regular', \n",
    "                       lat_orig=lat_orig, lon_orig=lon_orig, \n",
    "                       inc_lat=inc_lat, inc_lon=inc_lon, \n",
    "                       n_lat=n_lat, n_lon=n_lon)\n",
    "\n",
    "nessy.set_time([datetime(year=1986, month=11, day=29)])\n",
    "nessy.set_levels({'data': (np.linspace(0, 2*np.pi, 10) * 10) + 100, 'units': 'm'})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "if not ascendant:\n",
    "    nessy.lev['data'] = np.flip(nessy.lev['data'] )\n",
    "    print(nessy.lev)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "nessy.variables[var_name] = {'data': None,\n",
    "                             'units': 'kg.m-2',\n",
    "                             'description': 'new variable from scratch',\n",
    "                             'short_name': 'newvar2',\n",
    "                            }\n",
    "\n",
    "# Fill the data\n",
    "shape = (len(nessy.time), len(nessy.lev['data']), nessy.lat['data'].shape[0], nessy.lon['data'].shape[-1])\n",
    "nessy.variables[var_name]['data'] = np.zeros(shape)\n",
    "\n",
    "for y in range(nessy.lat['data'].shape[0]):\n",
    "    for x in range(nessy.lon['data'].shape[-1]):\n",
    "        nessy.variables[var_name]['data'][0,:,y,x] = np.sin(nessy.lev['data'] -100) +1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 35456 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig = plt.figure()\n",
    "ax = fig.add_subplot(111)\n",
    "\n",
    "ax.plot(nessy.variables[var_name]['data'][0, :, 5, 5], \n",
    "        nessy.lev['data'], \n",
    "        color='black', marker='o', linestyle='--')\n",
    "\n",
    "ax.xaxis.tick_top()\n",
    "ax.set_ylabel(\"Vertical Levels ({0})\".format(nessy.lev['units']))\n",
    "ax.set_xlabel(var_name + \" ({0})\".format(nessy.variables[var_name]['units']))\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Extrapolation options"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Do extrapolation below and avobe\n",
    "# extrapolate = True  \n",
    "# extrapolate = ('extrapolate', 'extrapolate')\n",
    "\n",
    "# Do not extrapolate -> below (bottom); avobe (top)\n",
    "# extrapolate = False\n",
    "# extrapolate = ('bottom', 'top')  # Same behaviour as extrapolate = False\n",
    "\n",
    "# Only avobe extrapolation:\n",
    "extrapolate = ('bottom', 'extrapolate')  # (False, True)\n",
    "# extrapolate = (False, True)\n",
    "# extrapolate = (np.nan, 'extrapolate')  # (None, True)\n",
    "# extrapolate = (None, True)\n",
    "# extrapolate = (0, 'extrapolate')\n",
    "\n",
    "# Only below extrapolation:\n",
    "# extrapolate = ('extrapolate', 'top')  # (True, False)\n",
    "# extrapolate = ('extrapolate', np.nan)  # (True, None)\n",
    "# extrapolate = ('extrapolate', 0)\n",
    "\n",
    "# No extrapolation\n",
    "# extrapolate = 0  # (0, 0)\n",
    "# extrapolate = np.nan  # (np.nan, np.nan)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  0,  10,  20,  30,  40,  50,  60,  70,  80,  90, 100, 110, 120,\n",
       "       130, 140, 150, 160, 170, 180, 190, 200])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "level_list = np.arange(0, 210, 10)\n",
    "if not ascendant:\n",
    "    level_list = np.flip(level_list)\n",
    "level_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "interp_linear = nessy.interpolate_vertical(level_list, kind='linear', extrapolate=extrapolate)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 36 ms, sys: 95 µs, total: 36.1 ms\n",
      "Wall time: 35.9 ms\n"
     ]
    }
   ],
   "source": [
    "%time interp_quad = nessy.interpolate_vertical(level_list, kind='quadratic', extrapolate=extrapolate)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 37712 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig = plt.figure()\n",
    "ax = fig.add_subplot(111)\n",
    "\n",
    "ax.plot(nessy.variables[var_name]['data'][0, :, 5, 5], \n",
    "        nessy.lev['data'], \n",
    "        color='black', marker='o', linestyle='--', label='original')\n",
    "\n",
    "ax.plot(interp_linear.variables[var_name]['data'][0, :, 5, 5], \n",
    "        level_list, \n",
    "        color='green', marker='o', label = 'linear')\n",
    "\n",
    "ax.plot(interp_quad.variables[var_name]['data'][0, :, 5, 5], \n",
    "        level_list, \n",
    "        color='yellow', marker='o', label = 'quadratic')\n",
    "\n",
    "ax.xaxis.tick_top()\n",
    "ax.set_ylabel(\"Vertical Levels ({0})\".format(nessy.lev['units']))\n",
    "ax.set_xlabel(var_name + \" ({0})\".format(nessy.variables[var_name]['units']))\n",
    "\n",
    "ax.legend()\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.9.16"
  },
  "toc-autonumbering": true,
  "vscode": {
   "interpreter": {
    "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
