{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\nWork with Weather in aWherePy\n=============================\n\nLearn how to get weather norms and observed weather with aWherePy.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Get Historical Norms and Observed Weather Data with aWherePy\n------------------------------------------------------------\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>The example below will show you how to use the ``get_weather_norms()`` and\n   ``get_weather_observed()`` functions to obtain weather data from the\n   aWhere weather API.</p></div>\n\nIn this vignette, you will use a single aWhere grid cell centroid near Rocky\nMountain National Park, Colorado to get weather norms and observed weather\nfor May 4 - May 13. Weather norms are data aggregated over many years and do\nnot reference a specific year. The observed weather for this example is from\n2014. In addition, you will plot a comparison of the historical weather norms\nto the observed data in 2014.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Import Packages\n---------------\n\nIn order to use the functionality in this example, the following packages\nneed to be imported.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import os\nimport matplotlib.pyplot as plt\nimport awherepy.grids as awg\nimport awherepy.weather as aww"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Prerequisites\n-------------\n\nIn order to make calls to any aWhere API, you must provide a valid API key\nand secret. The key and secret used in this example are stored as\nenvironment variables.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Define aWhere API key and secret\nawhere_api_key = os.environ.get(\"AWHERE_API_KEY\")\nawhere_api_secret = os.environ.get(\"AWHERE_API_SECRET\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Extract Centroids from an aWhere Grid and Isolate a Centroid for Analysis\n-------------------------------------------------------------------------\n\nIn order to use an aWhere grid cell centroid, you must first create an aWhere\ngrid from a shapefile, extract all centroids, and isolate a single centroid.\nThis functionality is found in the ``awherepy.grid module``.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Define path to Rocky Mountain National Park, Colorado boundary\nrmnp_bound_path = os.path.join(\n    \"..\", \"awherepy\", \"example-data\", \"colorado_rmnp_boundary.shp\"\n)\n\n# Create aWhere grid and EPSG 4326 boudary for RMNP, CO\nrmnp_grid, rmnp_bound_4326 = awg.create_grid(\n    rmnp_bound_path, buffer_distance=0.12\n)\n\n# Plot RMNP grid and boundary - optional\nfig, ax = awg.plot_grid(\n    rmnp_grid,\n    rmnp_bound_4326,\n    plot_title=\"Rocky Mountain National Park, Colorado aWhere Grid\",\n    data_source=\"U.S. Department of the Interior\",\n)\n\n# Extract RMNP grid centroids to list\nrmnp_grid_centroids = awg.extract_centroids(rmnp_grid)\n\n# Get first centroid\nanalysis_centroid = rmnp_grid_centroids[0]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Get aWhere Weather Norms Data\n-----------------------------\n\nGet aWhere weather norms data by calling the ``get_weather_norms()``\nfunction, with optional keyword arguments to use values outside the default.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Define RMNP norms kwargs\nrmnp_weather_norms_kwargs = {\n    \"location\": (analysis_centroid[0], analysis_centroid[1]),\n    \"start_date\": \"05-04\",\n    \"end_date\": \"05-13\",\n}\n\n# Get RMNP weather norms, 05-04 to 05-13\nrmnp_weather_norms = aww.get_weather_norms(\n    awhere_api_key, awhere_api_secret, kwargs=rmnp_weather_norms_kwargs\n)\n\n# Get precipitation average from weather norms data\nrmnp_precip_norms = rmnp_weather_norms[[\"precip_avg_mm\"]]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Get aWhere Weather Observed Data\n--------------------------------\n\nGet aWhere weather observed data by calling the ``get_weather_observed()``\nfunction, with optional keyword arguments to use values outside the default.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Define RMNP observed kwargs\nrmnp_weather_observed_kwargs = {\n    \"location\": (analysis_centroid[0], analysis_centroid[1]),\n    \"start_date\": \"2014-05-04\",\n    \"end_date\": \"2014-05-13\",\n}\n\n# Get observed weather\nrmnp_weather_observed = aww.get_weather_observed(\n    awhere_api_key, awhere_api_secret, kwargs=rmnp_weather_observed_kwargs\n)\n\n# Get precipitation amount from observed weather\nrmnp_precip_observed = rmnp_weather_observed[[\"precip_amount_mm\"]]\n\n# Change date (YYYY-MM-DD) to day (MM-DD) for plotting\ndays = [value[5:] for value in rmnp_precip_observed.index.values]\nrmnp_precip_observed.insert(1, \"day\", days, True)\nrmnp_precip_observed.set_index(\"day\", inplace=True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Combine aWhere Weather Norms and Observed Data Subsets for Plotting\n-------------------------------------------------------------------\n\nMerge the weather data subsets for precipitation into a single dataframe for\nuse with plotting and visualiztion.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Merge precipitation components (norms and observed)\nrmnp_precip_may_2014 = rmnp_precip_observed.merge(rmnp_precip_norms, on=\"day\")\n\n# Add column for difference between observed and norms\nrmnp_precip_may_2014[\"precip_diff_mm\"] = (\n    rmnp_precip_may_2014.precip_amount_mm - rmnp_precip_may_2014.precip_avg_mm\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot a Comparison between the aWhere Norms and Observed Data for RMNP, CO\n-------------------------------------------------------------------------\n\nPlot the norms and observed data on the same subplot and also the difference\nbetween the data on a second subplot to see which days in the May 4 - May 13\ntemporal extent showed higher or lower precipatation compared to the historic\nnorms.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Plot daily precip comparison\nwith plt.style.context(\"dark_background\"):\n\n    # Create figure and axes\n    fig, ax = plt.subplots(1, 2, figsize=(20, 10))\n\n    # Set overall title\n    plt.suptitle(\n        (\n            \"Rocky Mountain National Park, CO\\nLongitude: \"\n            f\"{round(analysis_centroid[0], 4)}, Latitude: \"\n            f\"{round(analysis_centroid[1], 4)}\\nPrecipitation, May 2014\"\n        ),\n        fontsize=24,\n    )\n\n    # Set spacing\n    plt.subplots_adjust(top=0.8)\n\n    # Subplot 1 - Observed and Historic Precipitation\n    # Add grid\n    ax[0].grid(zorder=1)\n\n    # Add daily observed total (line)\n    ax[0].plot(\n        rmnp_precip_may_2014.precip_amount_mm,\n        label=\"Observed\",\n        marker=\"o\",\n        color=\"#7fc97f\",\n        markersize=8,\n        linewidth=2,\n        linestyle=\"--\",\n        zorder=2,\n    )\n\n    # Add daily average total (line)\n    ax[0].plot(\n        rmnp_precip_may_2014.precip_avg_mm,\n        label=\"Historic Average\",\n        marker=\"o\",\n        color=\"#beaed4\",\n        markersize=8,\n        linewidth=2,\n        linestyle=\"--\",\n        zorder=3,\n    )\n\n    # Configure axes\n    ax[0].set_xlabel(\"Date\", fontsize=16)\n    ax[0].set_ylabel(\"Precipitation (mm)\", fontsize=16)\n    ax[0].set_title(\"Daily Total Precipitation\", fontsize=20)\n    ax[0].tick_params(axis=\"both\", which=\"major\", labelsize=16)\n    plt.setp(ax[0].xaxis.get_majorticklabels(), rotation=45)\n\n    # Add legend\n    ax[0].legend(borderpad=0.75, edgecolor=\"w\", fontsize=16, shadow=True)\n\n    # Subplot 2 - Precipitation Difference\n    # Add grid\n    ax[1].grid(zorder=1)\n\n    # Add difference (observed - norms)\n    ax[1].bar(\n        rmnp_precip_may_2014.index.values,\n        rmnp_precip_may_2014.precip_diff_mm,\n        label=\"Daily Total Difference\",\n        zorder=2,\n        edgecolor=\"#ff7f00\",\n        color=\"#fdc086\",\n        linewidth=1,\n    )\n\n    # Configure axes\n    ax[1].set_xlabel(\"Date\", fontsize=16)\n    ax[1].set_ylabel(\"Precipitation Difference (mm)\", fontsize=16)\n    ax[1].set_title(\n        \"Precipitation Difference (Observed - Average)\", fontsize=20\n    )\n    ax[1].tick_params(axis=\"both\", which=\"major\", labelsize=16)\n    plt.setp(ax[1].xaxis.get_majorticklabels(), rotation=45)\n\n    # Add legend\n    ax[1].legend(borderpad=0.75, edgecolor=\"w\", fontsize=16, shadow=True)\n\n    plt.show()"
      ]
    }
  ],
  "metadata": {
    "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.8.3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}