{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "230857a7",
   "metadata": {},
   "source": [
    "---\n",
    "title: La Palma Earthquakes\n",
    "author:\n",
    "  - name: Steve Purves\n",
    "    orcid: 0000-0002-0760-5497\n",
    "    corresponding: true\n",
    "    email: steve@curvenote.com\n",
    "    roles:\n",
    "      - Investigation\n",
    "      - Project administration\n",
    "      - Software\n",
    "      - Visualization\n",
    "    affiliations:\n",
    "      - Curvenote\n",
    "  - name: Rowan Cockett\n",
    "    orcid: 0000-0002-7859-8394\n",
    "    corresponding: false\n",
    "    roles: []\n",
    "    affiliations:\n",
    "      - Curvenote\n",
    "license: CC BY-SA 4.0\n",
    "keywords:\n",
    "  - La Palma\n",
    "  - Earthquakes\n",
    "date: 2022-05-11\n",
    "abstract: |\n",
    "  In September 2021, a significant jump in seismic activity on the island of La Palma (Canary Islands, Spain) signaled the start of a volcanic crisis that still continues at the time of writing. Earthquake data is continually collected and published by the Instituto Geográphico Nacional (IGN). We have created an accessible dataset from this and completed preliminary data analysis which shows seismicity originating at two distinct depths, consistent with the model of a two reservoir system feeding the currently very active volcano.\n",
    "keypoints:\n",
    "  - You may specify 1 to 3 keypoints for this PDF template\n",
    "  - These keypoints are complete sentences and less than or equal to 140 characters\n",
    "  - They are specific to this PDF template, so they will not appear in other exports\n",
    "citation:\n",
    "  container-title: Notebooks Now!\n",
    "draft: false\n",
    "bibliography: references.bib\n",
    "---"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "8b06862f",
   "metadata": {},
   "source": [
    "## Introduction\n",
    "\n",
    "> The content of your notebook may be broken into any number of markdown or code cells. Markdown cells use Quarto markdown. Quarto markdown supports an extended version of the basic Markdown syntax originally created by John Gruber, which adds support for many common document elements including citations, figures, tables, admonitions, and more. Quarto markdown also supports the use of LaTeX for mathematical equations, advanced layout control, as well as other advanced formatting.\n",
    "\n",
    "La Palma is one of the west most islands in the Volcanic Archipelago of the Canary Islands, a Spanish territory situated is the Atlantic Ocean where at their closest point are 100km from the African coast @fig-map. The island is one of the youngest, remains active and is still in the island forming stage.\n",
    "\n",
    "> Figures may be added to your notebook using [markdown images or specifial markdown elements](https://quarto.org/docs/authoring/figures.html) ('fenced divs'). They may refer to images saved in your `images/` folder (or other folders), images from the web, or generated directly using code cells. You may embed figures produced in other notebooks using the [embed shortcode](https://quarto.org/docs/authoring/notebook-embed.html) (this embed figures, tables, or any other content from Jupyter Notebooks). Refer to figures by their label (e.g. `@fig-map`).\n",
    "\n",
    "![Map of La Palma in the Canary Islands. Image credit [NordNordWest](https://commons.wikimedia.org/w/index.php?curid=76638603)](images/la-palma-map.png){#fig-map align=\"center\" width=\"100%\"}\n",
    "\n",
    "La Palma has been constructed by various phases of volcanism, the most recent and currently active being the *Cumbre Vieja* volcano, a north-south volcanic ridge that constitutes the southern half of the island.\n",
    "\n",
    "### Eruption History\n",
    "\n",
    "A number of eruptions were recorded since the colonization of the islands by Europeans in the late 1400s, these are summarised in \\@tbl-history ['TODO: Fix table referen].\n",
    "\n",
    "> Quarto supports a number of ways to create tables using both standard markdown tables (pipe tables) and more complex markdown tables using a grid style syntax (grid tables). In addition, Quarto provides the ability to control column width, caption position, create subtables, and more. See [Quarto's table document](https://quarto.org/docs/authoring/tables.html) to learn more. Refer to tables in the text by their label (e.g. `@tbl-history`).\n",
    "\n",
    "\n",
    "| Name      | Year |\n",
    "| ----------- | ----------- |\n",
    "| Current      | 2021       |\n",
    "| Teneguía   | 1971        |\n",
    "| Nambroque   | 1949        |\n",
    "| El Charco   | 1712        |\n",
    "| Volcán San Antonio   | 1677        |\n",
    "| Volcán San Martin   | 1646        |\n",
    "| Tajuya near El Paso   | 1585        |\n",
    "| Montaña Quemada   | 1492        |\n",
    "\n",
    ": Recent historic eruptions on La Palma {#tbl-history}\n",
    "\n",
    "This equates to an eruption on average every 79 years up until the 1971 event. The probability of a future eruption can be modeled by a Poisson distribution @eq-poisson.\n",
    "\n",
    "> Numbered equations may be defined using 'dollar math' by placing equations between matching pairs of dollar signs. Learn more about Quarto's equation here: [https://quarto.org/docs/authoring/cross-references.html#equations](https://quarto.org/docs/authoring/cross-references.html#equations). Refer to equations in the text by their label (e.g. `@eq-poisson`).\n",
    "\n",
    "$$\n",
    "p(x)=\\frac{e^{-\\lambda} \\lambda^{x}}{x !}\n",
    "$$ {#eq-poisson}\n",
    "\n",
    "\n",
    "Where $\\lambda$ is the number of eruptions per year, $\\lambda=\\frac{1}{79}$ in this case. The probability of a future eruption in the next $t$ years can be calculated by:\n",
    "\n",
    "$$\n",
    "p_e = 1-\\mathrm{e}^{-t \\lambda}\n",
    "$$ {#eq-probability}\n",
    "\n",
    "So following the 1971 eruption the probability of an eruption in the following 50 years — the period ending this year — was 0.469. After the event, the number of eruptions per year moves to $\\lambda=\\frac{1}{75}$ and the probability of a further eruption within the next 50 years (2022-2071) rises to 0.487 and in the next 100 years, this rises again to 0.736.\n",
    "\n",
    "### Magma Reservoirs\n",
    "\n",
    "> You may provide the bibliography directly as a bibtex, biblatex, CSL JSON, or CSL YAML file (defined in the document front matter or `_quarto.yml` project file) then embed the citation by citation key in your text using the `[@cite]` or `@cite` for parenthetical or textual citations, respectively. The following paragraph provides an example of this. Quarto's [documentation on citations](https://quarto.org/docs/authoring/footnotes-and-citations.html) provides more details on working with bibliographies and citations.\n",
    "\n",
    "Studies of the magma systems feeding the volcano, such as @marrero2019 has proposed that there are two main magma reservoirs feeding the Cumbre Vieja volcano; one in the mantle (30-40km depth) which charges and in turn feeds a shallower crustal reservoir (10-20km depth).\n",
    "\n",
    "![Proposed model from Marrero et al](images/reservoirs.png){#fig-reservoirs align=\"center\" width=\"100%\"}\n",
    "\n",
    "In this paper, we look at recent seismicity data to see if we can see evidence of such a system action, see @fig-reservoirs.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c7a031d",
   "metadata": {},
   "source": [
    "# Dataset\n",
    "\n",
    "> All data used in the notebook should be present in the `data/` folder so notebooks may be executed in place with no additional input.\n",
    "\n",
    "The earthquake dataset used in our analysis was generated from the [IGN web portal](https://www.ign.es/web/resources/volcanologia/tproximos/canarias.html) this is public data released under a permissive license. Data recorded using the network of Seismic Monitoring Stations on the island. A web scraping script was developed to pull data into a machine-readable form for analysis. That code tool [is available on GitHub](https://github.com/stevejpurves/ign-earthquake-data) along with a copy of recently updated data."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63a26a1c",
   "metadata": {},
   "source": [
    "## Main Timeline Figure\n",
    "\n",
    "> Code cells may be seamlessly interleaved with markdown cells. There are a variety of execution options to control the behavior of code cells - learn more in [Quarto's documentation on execution options](https://quarto.org/docs/computations/execution-options.html)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "184d6123",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "import seaborn as sns\n",
    "import numpy as np\n",
    "sns.set_theme(style=\"whitegrid\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "76706a81",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "def make_category_columns(df):\n",
    "    df['Depth'] = 'Shallow (<18km)'\n",
    "    df.loc[(df['Depth(km)'] >= 18) & (df['Depth(km)'] <= 28), 'Depth'] = 'Interchange (18km>x>28km)'\n",
    "    df.loc[df['Depth(km)'] >= 28, 'Depth'] = 'Deep (>28km)'\n",
    "    \n",
    "    df['Mag'] = 0\n",
    "    df.loc[(df['Magnitude'] >= 1) & (df['Magnitude'] <= 2), 'Mag'] = 1\n",
    "    df.loc[(df['Magnitude'] >= 2) & (df['Magnitude'] <= 3), 'Mag'] = 2\n",
    "    df.loc[(df['Magnitude'] >= 3) & (df['Magnitude'] <= 4), 'Mag'] = 3\n",
    "    df.loc[(df['Magnitude'] >= 4) & (df['Magnitude'] <= 5), 'Mag'] = 4    \n",
    "    \n",
    "    return df"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3de56b46",
   "metadata": {},
   "source": [
    "## Visualising Long term earthquake data\n",
    "\n",
    "Data taken directly from the IGN Catalog\n",
    "\n",
    "> Supported cell outputs below include `pandas` dataframe, raw text output, `matplotlib` plot, and `seaborn` plot."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d4f84df5",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Event</th>\n",
       "      <th>Date</th>\n",
       "      <th>Time</th>\n",
       "      <th>Latitude</th>\n",
       "      <th>Longitude</th>\n",
       "      <th>Depth(km)</th>\n",
       "      <th>Intensity</th>\n",
       "      <th>Magnitude</th>\n",
       "      <th>Type Mag</th>\n",
       "      <th>Location</th>\n",
       "      <th>DateTime</th>\n",
       "      <th>Timestamp</th>\n",
       "      <th>Swarm</th>\n",
       "      <th>Phase</th>\n",
       "      <th>Depth</th>\n",
       "      <th>Mag</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>es2017eugju</td>\n",
       "      <td>2017-03-09</td>\n",
       "      <td>23:44:06</td>\n",
       "      <td>28.5346</td>\n",
       "      <td>-17.8349</td>\n",
       "      <td>26.0</td>\n",
       "      <td></td>\n",
       "      <td>1.6</td>\n",
       "      <td>4</td>\n",
       "      <td>NE FUENCALIENTE DE LA PALMA.IL</td>\n",
       "      <td>2017-03-09 23:44:06</td>\n",
       "      <td>1489103046000000000</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0</td>\n",
       "      <td>Interchange (18km&gt;x&gt;28km)</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>es2017euhlh</td>\n",
       "      <td>2017-03-10</td>\n",
       "      <td>00:16:10</td>\n",
       "      <td>28.5491</td>\n",
       "      <td>-17.8459</td>\n",
       "      <td>27.0</td>\n",
       "      <td></td>\n",
       "      <td>2.0</td>\n",
       "      <td>4</td>\n",
       "      <td>N FUENCALIENTE DE LA PALMA.ILP</td>\n",
       "      <td>2017-03-10 00:16:10</td>\n",
       "      <td>1489104970000000000</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0</td>\n",
       "      <td>Interchange (18km&gt;x&gt;28km)</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>es2017cpaoh</td>\n",
       "      <td>2017-03-10</td>\n",
       "      <td>00:16:11</td>\n",
       "      <td>28.5008</td>\n",
       "      <td>-17.8863</td>\n",
       "      <td>20.0</td>\n",
       "      <td></td>\n",
       "      <td>2.1</td>\n",
       "      <td>4</td>\n",
       "      <td>W LOS CANARIOS.ILP</td>\n",
       "      <td>2017-03-10 00:16:11</td>\n",
       "      <td>1489104971000000000</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0</td>\n",
       "      <td>Interchange (18km&gt;x&gt;28km)</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>es2017eunnk</td>\n",
       "      <td>2017-03-10</td>\n",
       "      <td>03:20:26</td>\n",
       "      <td>28.5204</td>\n",
       "      <td>-17.8657</td>\n",
       "      <td>30.0</td>\n",
       "      <td></td>\n",
       "      <td>1.6</td>\n",
       "      <td>4</td>\n",
       "      <td>NW FUENCALIENTE DE LA PALMA.IL</td>\n",
       "      <td>2017-03-10 03:20:26</td>\n",
       "      <td>1489116026000000000</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0</td>\n",
       "      <td>Deep (&gt;28km)</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>es2017kajei</td>\n",
       "      <td>2017-08-21</td>\n",
       "      <td>02:06:55</td>\n",
       "      <td>28.5985</td>\n",
       "      <td>-17.7156</td>\n",
       "      <td>0.0</td>\n",
       "      <td></td>\n",
       "      <td>1.6</td>\n",
       "      <td>4</td>\n",
       "      <td>E EL PUEBLO.ILP</td>\n",
       "      <td>2017-08-21 02:06:55</td>\n",
       "      <td>1503281215000000000</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0</td>\n",
       "      <td>Shallow (&lt;18km)</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          Event        Date      Time  Latitude  Longitude  Depth(km)  \\\n",
       "0   es2017eugju  2017-03-09  23:44:06   28.5346   -17.8349       26.0   \n",
       "1   es2017euhlh  2017-03-10  00:16:10   28.5491   -17.8459       27.0   \n",
       "2   es2017cpaoh  2017-03-10  00:16:11   28.5008   -17.8863       20.0   \n",
       "3   es2017eunnk  2017-03-10  03:20:26   28.5204   -17.8657       30.0   \n",
       "4   es2017kajei  2017-08-21  02:06:55   28.5985   -17.7156        0.0   \n",
       "\n",
       "      Intensity  Magnitude  Type Mag                        Location  \\\n",
       "0                      1.6         4  NE FUENCALIENTE DE LA PALMA.IL   \n",
       "1                      2.0         4  N FUENCALIENTE DE LA PALMA.ILP   \n",
       "2                      2.1         4              W LOS CANARIOS.ILP   \n",
       "3                      1.6         4  NW FUENCALIENTE DE LA PALMA.IL   \n",
       "4                      1.6         4                 E EL PUEBLO.ILP   \n",
       "\n",
       "              DateTime            Timestamp  Swarm  Phase  \\\n",
       "0  2017-03-09 23:44:06  1489103046000000000    0.0      0   \n",
       "1  2017-03-10 00:16:10  1489104970000000000    0.0      0   \n",
       "2  2017-03-10 00:16:11  1489104971000000000    0.0      0   \n",
       "3  2017-03-10 03:20:26  1489116026000000000    0.0      0   \n",
       "4  2017-08-21 02:06:55  1503281215000000000    0.0      0   \n",
       "\n",
       "                       Depth  Mag  \n",
       "0  Interchange (18km>x>28km)    1  \n",
       "1  Interchange (18km>x>28km)    2  \n",
       "2  Interchange (18km>x>28km)    2  \n",
       "3               Deep (>28km)    1  \n",
       "4            Shallow (<18km)    1  "
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#| output: false\n",
    "\n",
    "df_ign = pd.read_csv('./data/lapalma_ign.csv')\n",
    "df_ign = make_category_columns(df_ign)\n",
    "df_ign.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "41ccbc48",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "df_ign['DateTime'] = pd.to_datetime(df_ign['Date'] + ' ' + df_ign['Time'])\n",
    "df_ign['DateTime'];"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "a3816f99",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "df_ign_early = df_ign[df_ign['DateTime'] < '2021-09-11']\n",
    "df_ign_pre = df_ign[(df_ign['DateTime'] >= '2021-09-11')&(df_ign['DateTime'] < '2021-09-19 14:13:00')]\n",
    "df_ign_phase1 = df_ign[(df_ign['DateTime'] >= '2021-09-19 14:13:00')&(df_ign['DateTime'] < '2021-10-01')]\n",
    "df_ign_phase2 = df_ign[(df_ign['DateTime'] >= '2021-10-01')&(df_ign['DateTime'] < '2021-12-01')]\n",
    "df_ign_phase3 = df_ign[(df_ign['DateTime'] >= '2021-12-01')&(df_ign['DateTime'] <= '2021-12-31')]\n",
    "\n",
    "df_erupt = df_ign[(df_ign['Date'] < '2022-01-01') & (df_ign['Date'] > '2021-09-11')]\n",
    "\n",
    "df_erupt_1 = df_erupt[df_erupt['Magnitude'] < 1.0]\n",
    "df_erupt_2 = df_erupt[(df_erupt['Magnitude'] >= 1.0)&(df_erupt['Magnitude'] < 2.0)]\n",
    "df_erupt_3 = df_erupt[(df_erupt['Magnitude'] >= 2.0)&(df_erupt['Magnitude'] < 3.0)]\n",
    "df_erupt_4 = df_erupt[(df_erupt['Magnitude'] >= 3.0)&(df_erupt['Magnitude'] < 4.0)]\n",
    "df_erupt_5 = df_erupt[df_erupt['Magnitude'] > 4.0]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "9bd70552",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "tab20_colors = (\n",
    "    (0.12156862745098039, 0.4666666666666667,  0.7058823529411765  ),  # 1f77b4\n",
    "    (0.6823529411764706,  0.7803921568627451,  0.9098039215686274  ),  # aec7e8\n",
    "    (1.0,                 0.4980392156862745,  0.054901960784313725),  # ff7f0e\n",
    "    (1.0,                 0.7333333333333333,  0.47058823529411764 ),  # ffbb78\n",
    "    (0.17254901960784313, 0.6274509803921569,  0.17254901960784313 ),  # 2ca02c\n",
    "    (0.596078431372549,   0.8745098039215686,  0.5411764705882353  ),  # 98df8a\n",
    "    (0.8392156862745098,  0.15294117647058825, 0.1568627450980392  ),  # d62728\n",
    "    (1.0,                 0.596078431372549,   0.5882352941176471  ),  # ff9896\n",
    "    (0.5803921568627451,  0.403921568627451,   0.7411764705882353  ),  # 9467bd\n",
    "    (0.7725490196078432,  0.6901960784313725,  0.8352941176470589  ),  # c5b0d5\n",
    "    (0.5490196078431373,  0.33725490196078434, 0.29411764705882354 ),  # 8c564b\n",
    "    (0.7686274509803922,  0.611764705882353,   0.5803921568627451  ),  # c49c94\n",
    "    (0.8901960784313725,  0.4666666666666667,  0.7607843137254902  ),  # e377c2\n",
    "    (0.9686274509803922,  0.7137254901960784,  0.8235294117647058  ),  # f7b6d2\n",
    "    (0.4980392156862745,  0.4980392156862745,  0.4980392156862745  ),  # 7f7f7f\n",
    "    (0.7803921568627451,  0.7803921568627451,  0.7803921568627451  ),  # c7c7c7\n",
    "    (0.7372549019607844,  0.7411764705882353,  0.13333333333333333 ),  # bcbd22\n",
    "    (0.8588235294117647,  0.8588235294117647,  0.5529411764705883  ),  # dbdb8d\n",
    "    (0.09019607843137255, 0.7450980392156863,  0.8117647058823529  ),  # 17becf\n",
    "    (0.6196078431372549,  0.8549019607843137,  0.8980392156862745),    # 9edae5\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "d7910f53",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 1098184 characters]",
      "text/plain": [
       "<Figure size 2400x1200 with 3 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#| label: fig-timeline\n",
    "#| fig-cap: Earthquake data over time (n=5465) to understand their distributions spatially, by depth, by magnitude and in time.\n",
    "\n",
    "from matplotlib.patches import Rectangle\n",
    "\n",
    "import datetime as dt\n",
    "from matplotlib.dates import date2num, num2date\n",
    "\n",
    "matplotlib.rcParams['font.sans-serif'] = \"Helvetica\"\n",
    "matplotlib.rcParams['font.family'] = \"sans-serif\"\n",
    "matplotlib.rcParams['xtick.labelsize'] = 14\n",
    "matplotlib.rcParams['ytick.labelsize'] = 14\n",
    "matplotlib.rcParams['ytick.labelleft'] = True\n",
    "matplotlib.rcParams['ytick.labelright'] = True\n",
    "\n",
    "%matplotlib inline\n",
    "fig = matplotlib.pyplot.figure(figsize=(24,12))\n",
    "fig.tight_layout()\n",
    "# Creating axis\n",
    "# add_axes([xmin,ymin,dx,dy])\n",
    "ax_min = fig.add_axes([0.01, 0.01, 0.01, 0.01])\n",
    "ax_min.axis('off')\n",
    "ax_max = fig.add_axes([0.99, 0.99, 0.01, 0.01])\n",
    "ax_max.axis('off')\n",
    "\n",
    "ax_timeline = fig.add_axes([0.04, 0.1, 0.92, 0.85])\n",
    "ax_timeline.spines[\"top\"].set_visible(False)\n",
    "ax_timeline.spines[\"right\"].set_visible(False)\n",
    "ax_timeline.spines[\"left\"].set_visible(False)\n",
    "ax_timeline.grid(axis='x')\n",
    "\n",
    "\n",
    "ax_timeline.axvline(x=dt.datetime(2021, 9, 19, 14, 13), ymin=0.075, ymax=0.98, color='r', linewidth=3)\n",
    "\n",
    "\n",
    "def make_scatter(df, c, alpha=0.8):\n",
    "    M = 3*np.exp2(1.3*df['Magnitude'])\n",
    "    return ax_timeline.scatter(df['DateTime'], df['Depth(km)'], s=M, c=c, alpha=alpha, edgecolor='black', linewidth=0.5, zorder=2);\n",
    "\n",
    "# make_scatter(df_erupt, c=tab20c_colors[-1])\n",
    "points_1 = make_scatter(df_erupt_1, c=[tab20_colors[12]], alpha=0.3)\n",
    "points_2 = make_scatter(df_erupt_2, c=[tab20_colors[16]], alpha=0.4)\n",
    "points_3 = make_scatter(df_erupt_3, c=[tab20_colors[4]], alpha=0.5)\n",
    "points_4 = make_scatter(df_erupt_4, c=[tab20_colors[2]], alpha=0.6)\n",
    "points_5 = make_scatter(df_erupt_5, c=[tab20_colors[6]], alpha=0.8)\n",
    "\n",
    "ax_timeline.tick_params(axis='x', labelrotation=0, bottom=True)\n",
    "ax_timeline.set_ylabel('')\n",
    "ax_timeline.yaxis.set_ticks_position('both')\n",
    "ax_timeline.yaxis.set_ticks_position('both')\n",
    "\n",
    "xticks = ax_timeline.get_xticks()\n",
    "new_xticks = [date2num(pd.to_datetime('2021-09-11')),\n",
    "    date2num(pd.to_datetime('2021-09-19 14:13:00'))]\n",
    "new_xticks = np.append(new_xticks, xticks[2:-1])\n",
    "ax_timeline.set_xticks(new_xticks)\n",
    "\n",
    "ax_timeline.invert_yaxis()\n",
    "ax_timeline.spines['bottom'].set_position(('data', 45))\n",
    "ax_timeline.margins(tight=True, x=0)\n",
    "ax_timeline.legend(\n",
    "    [points_1, points_2, points_3, points_4, points_5],\n",
    "    ['0 < M <= 1','1 < M <= 2','2 < M <= 3','3 < M <= 4','M > 4'],\n",
    "    loc='lower left', bbox_to_anchor=(0.01, 0.1, 0.15, 0.1), fancybox=True,\n",
    "    borderpad=1.0, labelspacing=1, mode=\"expand\", title=\"Event Magnitude (M)\",\n",
    "    fontsize=14, title_fontsize=14, framealpha=1)\n",
    "\n",
    "ax_timeline.set_ylim(ax_timeline.get_ylim()[0], -9)\n",
    "\n",
    "plt.annotate('ERUPTION', (0.055, 0.42), rotation=90, xycoords='axes fraction', fontweight='bold', fontsize=20, color='r')\n",
    "plt.annotate('Pre\\nEruptive\\nSwarm', (0.035, 0.88), rotation=0, xycoords='axes fraction', fontweight='bold', fontsize=20, color='b', horizontalalignment='center')\n",
    "plt.annotate('Early Eruptive\\nPhase', (0.12, 0.9), rotation=0, xycoords='axes fraction', fontweight='bold', fontsize=20, color='orange', horizontalalignment='center')\n",
    "plt.annotate('Main Eruptive Phase\\n(sustained gas and lava ejection)', (0.45, 0.9), rotation=0, xycoords='axes fraction', fontweight='bold', fontsize=20, color='green', horizontalalignment='center')\n",
    "plt.annotate('Final Eruptive Phase\\n(reducing gas and lava ejection)', (0.86, 0.9), rotation=0, xycoords='axes fraction', fontweight='bold', fontsize=20, color='r', horizontalalignment='center')\n",
    "\n",
    "ax_timeline.add_patch(Rectangle((date2num(pd.to_datetime('2021-09-11')), -8), date2num(pd.to_datetime('2021-09-19 14:13:00'))-date2num(pd.to_datetime('2021-09-11')), 53, color=tab20_colors[0], zorder=1, alpha=0.1))\n",
    "ax_timeline.add_patch(Rectangle((date2num(pd.to_datetime('2021-09-19 14:13:00')), -8), date2num(pd.to_datetime('2021-10-01'))-date2num(pd.to_datetime('2021-09-19 14:13:00')), 53, color=tab20_colors[2], zorder=1, alpha=0.1))\n",
    "ax_timeline.add_patch(Rectangle((date2num(pd.to_datetime('2021-10-01')), -8), date2num(pd.to_datetime('2021-12-01'))-date2num(pd.to_datetime('2021-10-01')), 53, color=tab20_colors[4], zorder=1, alpha=0.1))\n",
    "ax_timeline.add_patch(Rectangle((date2num(pd.to_datetime('2021-12-01')), -8), date2num(pd.to_datetime('2021-12-31'))-date2num(pd.to_datetime('2021-12-01'))+1, 53, color=tab20_colors[6], zorder=1, alpha=0.1));\n",
    "\n",
    "ax_timeline.set_title(\"Recorded seismicity during the La Palma eruption 11 September - 15 December 2021 (INVOLCAN Dataset)\", dict(fontsize=24), pad=20)\n",
    "ax_timeline.set_ylabel(\"Depth (km)\", dict(fontsize=20), labelpad=20)\n",
    "ax_timeline.set_xlabel(\"Eruption Timeline\", dict(fontsize=20), labelpad=20);\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6014701a",
   "metadata": {},
   "source": [
    "## Cumulative Distribution Plots"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "d0ea08d9",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "def cumulative_events_mag_depth(df, hue='Depth', kind='scatter', ax=None, dpi=100, palette=None, kde=True):\n",
    "    matplotlib.rcParams['ytick.labelright'] = False\n",
    "    g = sns.jointplot(x=\"Magnitude\", y=\"Depth(km)\", data=df,\n",
    "                      kind=kind, hue=hue, height=10, space=0.1, marginal_ticks=False, ratio=8, alpha=0.6,\n",
    "                      hue_order=['Shallow (<18km)', 'Interchange (18km>x>28km)', 'Deep (>28km)'],\n",
    "                      ax=ax, palette=palette, ylim=(-2,50), xlim=(0.3,5.6), edgecolor=\".2\", marginal_kws=dict(bins=20, hist_kws={'edgecolor': 'black'}))\n",
    "    if kde:\n",
    "        g.plot_joint(sns.kdeplot, color=\"b\", zorder=1, levels=15, ax=ax)\n",
    "    g.fig.axes[0].invert_yaxis();\n",
    "    g.fig.set_dpi(dpi)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "7609bbb1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 1453732 characters]",
      "text/plain": [
       "<Figure size 2000x2000 with 3 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#| label: fig-cumulative\n",
    "#| fig-cap: Cumulative earthquake data over time (n=5465) to understand their distributions spatially, by depth and magnitude.\n",
    "import warnings\n",
    "\n",
    "with warnings.catch_warnings():\n",
    "    warnings.simplefilter(\"ignore\")\n",
    "    cumulative_events_mag_depth(df_ign, hue=None, dpi=200)\n",
    "    plt.suptitle('Cumulative Events 01-01-2017 to 01-01-2022', y=1.01);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a8eb85c8",
   "metadata": {},
   "source": [
    "# Results\n",
    "\n",
    "The dataset was loaded into this Jupyter notebook and filtered down to La Palma events only. This results in 5465 data points which we then visualized to understand their distributions spatially, by depth, by magnitude and in time.\n",
    "\n",
    "From our analysis above, we can see 3 different systems in play.\n",
    "\n",
    "Firstly, the shallow earthquake swarm leading up to the eruption on 19th September, related to significant surface deformation and shallow magma intrusion.\n",
    "\n",
    "After the eruption, continuous shallow seismicity started at 10-15km corresponding to magma movement in the crustal reservoir.\n",
    "\n",
    "Subsequently, high magnitude events begin occurring at 30-40km depths corresponding to changes in the mantle reservoir. These are also continuous but occur with a lower frequency than in the crustal reservoir."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f0774682",
   "metadata": {},
   "source": [
    "# Conclusions\n",
    "\n",
    "From the analysis of the earthquake data collected and published by IGN for the period of 11 September through to 9 November 2021. Visualization of the earthquake events at different depths appears to confirm the presence of both mantle and crustal reservoirs as proposed by @marrero2019."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e445a1b1",
   "metadata": {
    "part": "availability"
   },
   "source": [
    "> Data availability statement should be specified in a separate cell with metadata `\"part\": \"availability\"`, similar to the abstract.\n",
    ">\n",
    "> AGU requires an Availability Statement for the underlying data needed to understand, evaluate, and build upon the reported research at the time of peer review and publication.\n",
    "\n",
    "A web scraping script was developed to pull data into a machine-readable form for analysis. That code tool [is available on GitHub](https://github.com/stevejpurves/ign-earthquake-data) along with a copy of recently updated data."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "411eb897-43aa-4fe6-b9df-ed24ef2581c3",
   "metadata": {},
   "source": [
    "## References {.unnumbered}\n",
    "\n",
    ":::{#refs}\n",
    "\n",
    ":::"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Edit 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.11.2"
  },
  "vscode": {
   "interpreter": {
    "hash": "b0fa6594d8f4cbf19f97940f81e996739fb7646882a419484c72d19e05852a7e"
   }
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
