{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "# NCL_animate_1.py\n",
    "This script illustrates the following concepts:\n",
    "   - Creating animations using matplotlib.FuncAnimation\n",
    "\n",
    "See following URLs to see the reproduced NCL plot & script:\n",
    "   - [Original NCL script](https://www.ncl.ucar.edu/Applications/Scripts/animate_1.ncl)\n",
    "   - [Original NCL plot](https://www.ncl.ucar.edu/Applications/Images/animate_1_1_lg.png)\n",
    "\n",
    "Please note:\n",
    "   - Executing this script will not display a gif, but you have the option to uncomment a line at the bottom that will save a gif in the same directory as this script.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Import packages:\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "import cartopy.crs as ccrs\n",
    "import matplotlib.animation as animation\n",
    "import numpy as np\n",
    "import xarray as xr\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "import geocat.datafiles as gdf\n",
    "import geocat.viz as gv"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Read in data:\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "# Open a netCDF data file using xarray default engine and load the data into xarrays\n",
    "# Disable time decoding due to missing necessary metadata\n",
    "ds = xr.open_dataset(gdf.get(\"netcdf_files/meccatemp.cdf\"), decode_times=False)\n",
    "\n",
    "tas = ds.t"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create animation:\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(10, 8))\n",
    "# Generate axes using Cartopy and draw coastlines\n",
    "ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=150))\n",
    "ax.coastlines(linewidths=0.5)\n",
    "ax.set_extent([-180, 180, -90, 90], ccrs.PlateCarree())\n",
    "\n",
    "# Use geocat.viz.util convenience function to set axes limits & tick values\n",
    "gv.set_axes_limits_and_ticks(ax,\n",
    "                             xlim=(-180, 180),\n",
    "                             ylim=(-90, 90),\n",
    "                             xticks=np.linspace(-180, 180, 13),\n",
    "                             yticks=np.linspace(-90, 90, 7))\n",
    "\n",
    "# Use geocat.viz.util convenience function to add minor and major tick lines\n",
    "gv.add_major_minor_ticks(ax, labelsize=10)\n",
    "\n",
    "# Use geocat.viz.util convenience function to make latitude, longitude tick labels\n",
    "gv.add_lat_lon_ticklabels(ax)\n",
    "\n",
    "# create initial plot that establishes a colorbar\n",
    "tas[0, :, :].plot.contourf(ax=ax,\n",
    "                           transform=ccrs.PlateCarree(),\n",
    "                           vmin=195,\n",
    "                           vmax=328,\n",
    "                           levels=53,\n",
    "                           cmap=\"inferno\",\n",
    "                           cbar_kwargs={\n",
    "                               \"extendrect\": True,\n",
    "                               \"orientation\": \"horizontal\",\n",
    "                               \"ticks\": np.arange(195, 332, 9),\n",
    "                               \"label\": \"\",\n",
    "                               \"shrink\": 0.90\n",
    "                           })\n",
    "\n",
    "\n",
    "# animate function for matplotlib FuncAnimation\n",
    "def animate(i):\n",
    "    tas[i, :, :].plot.contourf(\n",
    "        ax=ax,\n",
    "        transform=ccrs.PlateCarree(),\n",
    "        vmin=195,\n",
    "        vmax=328,\n",
    "        levels=53,\n",
    "        cmap=\"inferno\",\n",
    "        add_colorbar=False,\n",
    "    )\n",
    "\n",
    "    gv.set_titles_and_labels(\n",
    "        ax,\n",
    "        maintitle=\"January Global Surface Temperature (K) - Day  \" +\n",
    "        str(tas.coords['time'].values[i])[:13],\n",
    "        xlabel=\"\",\n",
    "        ylabel=\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "### Run:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "# runs the animation initiated with the frame from init and progressed with the animate function\n",
    "anim = animation.FuncAnimation(fig, animate, frames=30, interval=200)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "### Save:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "# Uncomment this line to save the created animation\n",
    "anim.save('animate_1.gif', writer='pillow', fps=5)"
   ]
  }
 ],
 "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.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
