{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f0545a60-ae40-4e22-817a-2738a64430d1",
   "metadata": {},
   "source": [
    "# Example: Compare different methods for a single plume"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf6b9b1c-3cf6-4b93-98c1-96f509e28380",
   "metadata": {},
   "source": [
    "In this example, we compare how the different methods are applied to a single emission plume. The example uses synthetic CO2 and NO2 observations of the Jänschwalde power plant plume from the SMARTCARB dataset. The focus is generating figures demonstrating how the methods are applied to the plume."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4fd0b59d-4ec0-4cdc-b516-3b19d71dd8bd",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import cartopy.crs as ccrs\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import shapely.geometry\n",
    "import xarray as xr\n",
    "\n",
    "%matplotlib inline\n",
    "%config InlineBackend.print_figure_kwargs = {'bbox_inches': 'tight'}\n",
    "plt.rcParams['figure.dpi'] = 100\n",
    "\n",
    "import ddeq\n",
    "import ucat\n",
    "\n",
    "# A small domain around Jänschwalde power plant\n",
    "DOMAIN = ddeq.misc.Domain('JAE', 14, 51.4, 16, 52.2)\n",
    "CRS = ccrs.UTM(32)\n",
    "\n",
    "# Path to test dataset incl in ddeq\n",
    "DATA_PATH = os.path.join(os.path.dirname(ddeq.__file__), '..', '..', 'notebooks', 'data')\n",
    "\n",
    "# Load list of point source locations\n",
    "sources = ddeq.misc.read_point_sources().sel(source=['Janschwalde'])\n",
    "\n",
    "# Rough priors for source strength (in kg/s) and decay time (in hours) used by some methods.\n",
    "PRIORS = {\n",
    "    'Janschwalde': {\n",
    "        'CO2': {'Q': 1000.0, 'tau': 1e10},\n",
    "        'NO2': {'Q': 1.0, 'tau': 4.0},\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b804f19f-724d-4615-8fcc-918872a0ae04",
   "metadata": {},
   "source": [
    "Read and visualize SMARTCARB example file"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f29f2fe-1715-4a17-bf2b-0969f7d428c8",
   "metadata": {},
   "outputs": [],
   "source": [
    "filename = os.path.join(DATA_PATH, 'Sentinel_7_CO2_2015042311_o1670_l0483.nc')\n",
    "data = ddeq.smartcarb.read_level2(filename, co2_noise_scenario='medium',\n",
    "                                            no2_noise_scenario='high')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3be7ed86-4a9d-4ad4-8fd4-7733583e5d51",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = ddeq.vis.visualize(data, 'CO2', gas='CO2', sources=sources,\n",
    "                         domain=DOMAIN, draw_gridlines=True)\n",
    "\n",
    "# use bbox_inches='tight' to include lon/lat labels in saved image\n",
    "plt.savefig('test.png', bbox_inches='tight')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb4a91f8-b441-4ff0-b4bd-2c577ce89cf4",
   "metadata": {},
   "source": [
    "Read wind speed at sources used by CSF, IME and GP and 2D wind field used by LCSF"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e1959d5c-4a5e-4a34-95ec-0b322feb52c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "time = pd.Timestamp(data.time.to_pandas())\n",
    "winds = ddeq.wind.read(time, sources, radius=0.05, product='SMARTCARB',\n",
    "                       data_path=DATA_PATH)\n",
    "\n",
    "wind_field = ddeq.wind.read_field(os.path.join(DATA_PATH, 'SMARTCARB_winds_2015042311.nc'), product='SMARTCARB')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d2e0a96d-59ed-4fda-a2b8-1d1b38f2d60a",
   "metadata": {},
   "source": [
    "Plume detection and pre-processing (for CSF, IME and GP method)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee698e3c-6689-4f04-8d19-9e944643ee72",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = ddeq.dplume.detect_plumes(data, sources,\n",
    "                                 variable='NO2', variable_std='NO2_std',\n",
    "                                 filter_type='gaussian', filter_size=0.5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f7657b5e-192b-4bca-a41a-9b6f4a3e8c0c",
   "metadata": {},
   "outputs": [],
   "source": [
    "data, curves = ddeq.plume_coords.compute_plume_line_and_coords(\n",
    "    data, crs=CRS, radius=25e3, plume_area='area'\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2ee2d0a8-0c66-4d67-a8ad-54118c74745e",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = ddeq.emissions.prepare_data(data, 'CO2')\n",
    "data = ddeq.emissions.prepare_data(data, 'NO2')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79b204ae-298c-412f-b09d-2ade5700b6b8",
   "metadata": {},
   "source": [
    "## LCSF\n",
    "Run LCSF method and visualize plume."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e53a433-7231-4c2a-b5f0-1f1ba179b92e",
   "metadata": {},
   "outputs": [],
   "source": [
    "lcsf_results = ddeq.lcsf.estimate_emissions(data, wind_field, sources, ['CO2'], priors=PRIORS, all_diags=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f08f08a5-5a87-4fd2-80ba-ed23e81ad619",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = ddeq.vis.visualize_lcsf_plume(data, lcsf_results, 'CO2', sources, source_name='Janschwalde',\n",
    "                                    domain=DOMAIN, do_zoom=False, line_color='b')\n",
    "#plt.savefig('lcsf-example.png', bbox_inches='tight')\n",
    "#plt.savefig('lcsf-example.pdf', bbox_inches='tight')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17c33279-f29f-4c13-a0f8-7554f51c058b",
   "metadata": {},
   "source": [
    "## Gauss\n",
    "Run GP method and visualize the result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f38102e-f2e8-4e8f-99f0-e6e29ad1255c",
   "metadata": {},
   "outputs": [],
   "source": [
    "data, gp_results = ddeq.gauss.estimate_emissions(data, winds, sources, curves, ['NO2', 'CO2'], priors=PRIORS)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35be8b50-7e42-4efd-aed9-ebf0ad4768c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# convert from kg m-2 to ppmv\n",
    "gauss_fit = ucat.convert_columns(data['CO2_plume_model_mass'] + gp_results['CO2_background'], 'kg m-2', 'ppmv', molar_mass='CO2')[:,:,0]\n",
    "gauss_fit += data.CO2_estimated_background"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "25843690-64ae-4413-82e5-5238f77dd1d2",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = ddeq.vis.show_detected_plumes(\n",
    "    data, {}, data['CO2'], gas='CO2', domain=DOMAIN, winds=winds,\n",
    "    do_zoom=False, crs=CRS, zoom_on=\"Janschwalde\", add_polygons=False\n",
    ")\n",
    "\n",
    "s = slice(450,550), slice(40, None)\n",
    "fig.axes[0].contour(data.lon[s], data.lat[s], gauss_fit[s], transform=ccrs.PlateCarree(), colors='b', levels=np.arange(403, 407, 0.5))\n",
    "\n",
    "#plt.savefig('gp-example.png', bbox_inches='tight')\n",
    "#plt.savefig('gp-example.pdf', bbox_inches='tight')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3f2addc-3575-4aea-bf7c-2fabcae1eec3",
   "metadata": {},
   "source": [
    "## CSF\n",
    "Visualize the CSF method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bfed10b2-0a02-4346-9c55-7c2689639f0d",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = ddeq.vis.show_detected_plumes(\n",
    "    data, curves, data['CO2'], gas='CO2', domain=DOMAIN, winds=winds,\n",
    "    do_zoom=False, crs=CRS, polygon_color='blue'\n",
    ")\n",
    "#plt.savefig('csf-example.png', bbox_inches='tight')\n",
    "#plt.savefig('csf-example.pdf', bbox_inches='tight')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20735f01-fddd-482f-9466-804199c60e1a",
   "metadata": {},
   "source": [
    "## IME\n",
    "Visualize IME method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d048c5b7-eb00-4f2c-9513-83332f6f8678",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = ddeq.vis.show_detected_plumes(\n",
    "    data, curves, data['CO2'], gas='CO2', domain=DOMAIN, winds=winds,\n",
    "    do_zoom=False, crs=CRS, add_polygons=False,\n",
    ")\n",
    "\n",
    "# calculate integration area and convert to convex hull line for visualization\n",
    "this = data.sel(source='Janschwalde')\n",
    "area = this['plume_area']\n",
    "L = np.max(this['xp'].values[area]) - 10e3\n",
    "area = (0 <= this['xp']) & (this['xp'] <= L) & area\n",
    "lon, lat = this.lon.values[area], this.lat.values[area]\n",
    "pts = shapely.geometry.MultiPoint(np.transpose([lon.flatten(), lat.flatten()]))\n",
    "x,y = np.transpose(pts.convex_hull.exterior.coords[:])\n",
    "\n",
    "fig.axes[0].plot(x.flatten(), y.flatten(), 'b-', ms=1, transform=ccrs.PlateCarree())\n",
    "#plt.savefig('ime-example.png', bbox_inches='tight')\n",
    "#plt.savefig('ime-example.pdf', bbox_inches='tight')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eab3ec7c-5cef-4708-9af3-91ff61b782ac",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "51320abf-f61e-4ded-9cf3-73bf5f98a666",
   "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
}
