{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d1d40d88-3da1-4956-9d77-c9498876e45a",
   "metadata": {},
   "source": [
    "# Example of Gaussian plume inversion with ddeq"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "115aebbc-e699-4174-b758-7c7b222669c6",
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload \n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7dd80102-d88c-46e9-8813-98562a28eaac",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "import cartopy.crs as ccrs\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import xarray as xr\n",
    "\n",
    "# import and setup matplotlib\n",
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "plt.rcParams['figure.dpi'] = 100\n",
    "\n",
    "from ddeq.smartcarb import DOMAIN\n",
    "import ddeq\n",
    "\n",
    "CRS = ccrs.UTM(32)\n",
    "WGS84 = ccrs.PlateCarree()\n",
    "\n",
    "DATA_PATH = os.path.join(os.path.dirname(ddeq.__file__), '..', '..', 'notebooks', 'data')\n",
    "\n",
    "# list of point sources\n",
    "sources = ddeq.misc.read_point_sources()\n",
    "sources"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a0b62aa1-468a-4cde-a389-da5a0c12e764",
   "metadata": {},
   "outputs": [],
   "source": [
    "PRIORS = {\n",
    "    'Janschwalde': {\n",
    "        'CO2': {'Q': 1000.0, 'tau': 1e10},\n",
    "        'NO2': {'Q': 1.0, 'tau': 4.0},\n",
    "    },\n",
    "    'Schwarze Pumpe': {\n",
    "        'CO2': {'Q': 1000.0, 'tau': 1e10},\n",
    "        'NO2': {'Q': 1.0, 'tau': 4.0},\n",
    "    },\n",
    "    'Boxberg': {\n",
    "        'CO2': {'Q': 1000.0, 'tau': 1e10},\n",
    "        'NO2': {'Q': 1.0, 'tau': 4.0},\n",
    "    },\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a7b152dc-6d96-47da-982b-441e785ef0ad",
   "metadata": {},
   "outputs": [],
   "source": [
    "q = 0.995 # default of 0.995 for non-overlapping plumes\n",
    "         #          or 0.990 for testing overlapping plumes of Schwarze Pumpe and Boxberg (experimental)\n",
    "\n",
    "filename = 'data/Sentinel_7_CO2_2015042311_o1670_l0483.nc'\n",
    "\n",
    "data = ddeq.smartcarb.read_level2(filename, co2_noise_scenario='medium',\n",
    "                                  no2_noise_scenario='high')\n",
    "\n",
    "data = ddeq.dplume.detect_plumes(data, sources.sel(source=['Janschwalde', 'Schwarze Pumpe', 'Boxberg']),\n",
    "                                 variable='NO2', variable_std='NO2_std',\n",
    "                                 filter_type='gaussian', filter_size=0.5, q=q)\n",
    "\n",
    "ddeq.vis.visualize(data, 'NO2', gas='NO2', domain=DOMAIN, winds=None,\n",
    "                   do_zoom=True, show_clouds=True);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1ebd2da0-86c8-4cfb-aaf9-b7721f722aea",
   "metadata": {},
   "outputs": [],
   "source": [
    "data, curves = ddeq.plume_coords.compute_plume_line_and_coords(\n",
    "    data, crs=CRS, radius=25e3, pixel_size=2e3, plume_area='area')\n",
    "\n",
    "data = ddeq.emissions.prepare_data(data, 'CO2')\n",
    "data = ddeq.emissions.prepare_data(data, 'NO2')\n",
    "\n",
    "time = pd.Timestamp(data.time.values)\n",
    "winds = ddeq.wind.read(time, sources, product='SMARTCARB',\n",
    "                       data_path=DATA_PATH)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "47e3099e-9565-4285-88bc-d49d369a4eef",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time \n",
    "\n",
    "# takes a few minutes\n",
    "data, results = ddeq.gauss.estimate_emissions(data, winds, sources, curves, priors=PRIORS,\n",
    "                                              gases=['NO2', 'CO2'], fit_decay_times=[True, False])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3a1f345b-c238-4b25-b714-bac54959b891",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = ddeq.vis.plot_gauss_result(data, results, ['Janschwalde', 'Schwarze Pumpe', 'Boxberg'],\n",
    "                                 'CO2', curves, crs=CRS, vmin=-20e-3, vmax=60e-3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "082670cb-b54b-4a18-a8cc-0d7c33414d63",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = ddeq.vis.plot_gauss_result(data, results, ['Janschwalde', 'Schwarze Pumpe', 'Boxberg'],\n",
    "                                 'NO2', curves, crs=CRS, vmin=-20e-6, vmax=60e-6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3b724ddd-19a4-4cf9-9f47-998dc6b27ba5",
   "metadata": {},
   "outputs": [],
   "source": [
    "for name in ['Janschwalde', 'Schwarze Pumpe', 'Boxberg']:\n",
    "    print(name)\n",
    "    print('CO2', '%.2f Mt/a' % ddeq.misc.kgs_to_Mtyr(results.sel(source=name).CO2_estimated_emissions))\n",
    "    print('NOx', '%.2f kt/a' % ddeq.misc.kgs_to_Mtyr(1000 * results.sel(source=name).NO2_estimated_emissions))    \n",
    "    print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78d23bdc-a755-4155-80c4-21778f3adfae",
   "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.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
