{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 9 — Decay and source fitting\n", "\n", "**Theme:** extracting physical rates from a concentration peak.\n", "\n", "When a source runs in a room and then stops, the concentration rises and then\n", "decays away. Fitting that shape recovers quantities you cannot read off the\n", "plot: how strong the source was, and how fast the room cleared it.\n", "\n", "The decay combines ventilation and deposition to surfaces, so the fitted loss\n", "rate is the **total** removal rate." ], "id": "cell-00" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "import aerosoltools as at\n", "\n", "ns = at.load_ns_file(\"../../tests/data/Sample_NS.csv\")\n", "\n", "fig, ax = ns.plot_total_conc()\n", "ax.set_title(\"A single release with a clean decay\")" ], "id": "cell-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is the shape the fit expects: a flat background, a sharp rise while the\n", "source runs, and a smooth decay once it stops." ], "id": "cell-02" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tc = ns.total_concentration\n", "print(f\"background : ~{tc.iloc[:20].mean():,.0f} {ns.unit}\")\n", "print(f\"peak : {tc.max():,.0f} {ns.unit} at {tc.idxmax()}\")\n", "print(f\"enhancement: {tc.max() / tc.iloc[:20].mean():.1f}x above background\")" ], "id": "cell-03" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Fitting the peak\n", "\n", "`fit_decay` takes the window containing the event — as a `(start, end)` pair or\n", "the name of a marked activity. The window should start before the rise and end\n", "while the decay is still visible above the noise." ], "id": "cell-04" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "window = (\"2023-09-11 14:45:00\", \"2023-09-11 15:35:00\")\n", "\n", "fit = ns.fit_decay(period=window, metric=\"PNC\")\n", "\n", "print(\"model :\", fit.model)\n", "print(\"points fitted :\", fit.n_points)\n", "print(f\"R^2 (whole) : {fit.r_squared:.4f}\")\n", "print(f\"R^2 (decay) : {fit.decay_r_squared:.4f}\")" ], "id": "cell-05" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Two R² values are reported because the curve has two stages. The decay stage is\n", "usually the better-determined one — the rise depends on exactly when the source\n", "started and stopped, which is often uncertain.\n", "\n", "## Seeing the fit\n", "\n", "`decay_curve` rebuilds the modelled curve from `model` and `model_popt`, so the\n", "fit can be drawn over the data it came from." ], "id": "cell-06" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "measured = ns.total_concentration.loc[window[0]:window[1]]\n", "seconds = (measured.index - fit.window_start).total_seconds()\n", "\n", "t = np.linspace(0, seconds.max(), 500)\n", "modelled = at.decay_curve(fit.model, t, fit.model_popt)\n", "\n", "fig, ax = plt.subplots(figsize=(10, 5))\n", "ax.plot(seconds / 60, measured.values, \"o\", ms=4, color=\"tab:blue\",\n", " label=\"measured\")\n", "ax.plot(t / 60, modelled, \"-\", lw=2, color=\"firebrick\", label=\"fitted model\")\n", "ax.set_xlabel(\"Minutes from start of window\")\n", "ax.set_ylabel(f\"PNC [{fit.unit}]\")\n", "ax.legend()\n", "ax.set_title(\"Emission + decay model fitted to the release\")" ], "id": "cell-07" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What the fit found\n", "\n", "The fit splits the curve into a background, an emission phase and a decay, and\n", "reports where each begins." ], "id": "cell-08" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(f\"background : {fit.background:>12,.0f} {fit.unit}\")\n", "print(f\"modelled peak : {fit.peak_concentration:>12,.0f} {fit.unit}\")\n", "print(f\"peak excess : {fit.peak_excess:>12,.0f} {fit.unit}\")\n", "print()\n", "print(f\"emission starts at : {fit.emission_start_s / 60:>6.1f} min into the window\")\n", "print(f\"emission lasts : {fit.emission_duration_s / 60:>6.1f} min\")\n", "print(f\"peak reached at : {fit.peak_time_s / 60:>6.1f} min ({fit.peak_time})\")" ], "id": "cell-09" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Marking those on the plot shows what each number refers to." ], "id": "cell-10" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots(figsize=(11, 5.5))\n", "\n", "ax.plot(seconds / 60, measured.values, \"o\", ms=4, color=\"tab:blue\", label=\"measured\")\n", "ax.plot(t / 60, modelled, \"-\", lw=2, color=\"firebrick\", label=\"fitted model\")\n", "\n", "# background level\n", "ax.axhline(fit.background, ls=\"--\", color=\"gray\", lw=1.2, label=\"background\")\n", "\n", "# the emission phase\n", "ax.axvspan(fit.emission_start_s / 60,\n", " (fit.emission_start_s + fit.emission_duration_s) / 60,\n", " color=\"tab:orange\", alpha=0.18, label=\"emission phase\")\n", "\n", "# the decay phase\n", "ax.axvspan(fit.peak_time_s / 60, seconds.max() / 60,\n", " color=\"tab:green\", alpha=0.12, label=\"decay phase\")\n", "\n", "# the peak\n", "ax.plot(fit.peak_time_s / 60, fit.peak_concentration, \"*\", ms=18,\n", " color=\"darkred\", label=\"modelled peak\", zorder=5)\n", "\n", "ax.annotate(\n", " f\"peak excess\\n{fit.peak_excess:,.0f} {fit.unit}\",\n", " xy=(fit.peak_time_s / 60, fit.peak_concentration),\n", " xytext=(fit.peak_time_s / 60 + 6, fit.peak_concentration * 0.85),\n", " arrowprops=dict(arrowstyle=\"->\", color=\"darkred\"),\n", " color=\"darkred\",\n", ")\n", "\n", "ax.set_xlabel(\"Minutes from start of window\")\n", "ax.set_ylabel(f\"PNC [{fit.unit}]\")\n", "ax.legend(loc=\"upper right\")\n", "ax.set_title(\"What the fit identifies\")\n", "plt.tight_layout()" ], "id": "cell-11" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The decay rate\n", "\n", "The decay rate is the physically interesting output: how quickly the room\n", "removes particles, by ventilation and deposition together." ], "id": "cell-12" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(f\"decay rate : {fit.decay_rate:.6f} per second\")\n", "print(f\" : {fit.decay_rate_per_hour:.3f} per hour\")\n", "print(f\"half-life : {fit.half_life_hours * 60:.1f} minutes\")" ], "id": "cell-13" }, { "cell_type": "markdown", "metadata": {}, "source": [ "On a log scale a first-order decay is a straight line, which is the quickest\n", "visual check that the model is appropriate." ], "id": "cell-14" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "after_peak = seconds > fit.peak_time_s\n", "\n", "fig, ax = plt.subplots(figsize=(9, 4.5))\n", "ax.semilogy(seconds[after_peak] / 60,\n", " measured.values[after_peak] - fit.background,\n", " \"o\", ms=4, color=\"tab:blue\", label=\"measured excess\")\n", "\n", "t_decay = t[t > fit.peak_time_s]\n", "ax.semilogy(t_decay / 60,\n", " at.decay_curve(fit.model, t_decay, fit.model_popt) - fit.background,\n", " \"-\", lw=2, color=\"firebrick\", label=\"fitted decay\")\n", "\n", "ax.set_xlabel(\"Minutes from start of window\")\n", "ax.set_ylabel(f\"Excess over background [{fit.unit}]\")\n", "ax.legend()\n", "ax.set_title(f\"Straight on a log axis: first-order decay, R^2 = {fit.decay_r_squared:.4f}\")" ], "id": "cell-15" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Source strength\n", "\n", "An emission rate in concentration per second only becomes a *source strength*\n", "once you know the volume it filled — the same source in a smaller room drives a\n", "larger concentration. Supply `volume` in cubic metres." ], "id": "cell-16" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fit_v = ns.fit_decay(period=window, metric=\"PNC\", volume=30.0)\n", "\n", "print(f\"emission rate : {fit_v.emission_rate:,.1f} {fit_v.emission_rate_unit}\")\n", "print(f\"source strength: {fit_v.source_strength:.3e} particles/s\")\n", "print(f\"total emitted : {fit_v.total_emitted:.3e} particles\")" ], "id": "cell-17" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Separating ventilation from deposition\n", "\n", "The fitted decay lumps together air exchange and losses to surfaces. Given the\n", "air exchange rate independently — from a tracer-gas measurement, or the\n", "ventilation setpoint — the wall-loss term is reported separately." ], "id": "cell-18" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "split = ns.fit_decay(period=window, metric=\"PNC\", volume=30.0,\n", " air_exchange_rate=2.0)\n", "\n", "print(f\"total decay : {split.decay_rate_per_hour:.3f} per hour\")\n", "print(f\"air exchange : 2.000 per hour (given)\")\n", "print(f\"wall loss : {split.wall_loss_rate_per_hour:.3f} per hour\")" ], "id": "cell-19" }, { "cell_type": "markdown", "metadata": {}, "source": [ "The split is arithmetic, not fitted — the model cannot tell the two apart from\n", "the decay alone, so the air exchange rate you supply is taken at face value.\n", "\n", "## The window matters\n", "\n", "Extending the window into the noise, or cutting it short, changes the answer.\n", "Compare three choices:" ], "id": "cell-20" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for start, end in [(\"2023-09-11 14:45:00\", \"2023-09-11 15:35:00\"),\n", " (\"2023-09-11 14:45:00\", \"2023-09-11 15:15:00\"),\n", " (\"2023-09-11 14:45:00\", \"2023-09-11 15:55:00\")]:\n", " f = ns.fit_decay(period=(start, end), metric=\"PNC\")\n", " print(f\"{start[-8:]} - {end[-8:]} \"\n", " f\"decay {f.decay_rate_per_hour:6.3f} /h \"\n", " f\"decay R^2 {f.decay_r_squared:.4f} n={f.n_points}\")" ], "id": "cell-21" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Fitting a marked activity\n", "\n", "If the event is already marked, pass the activity name instead of a time pair." ], "id": "cell-22" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ns.mark_activities({\"Release\": [window]})\n", "\n", "by_name = ns.fit_decay(period=\"Release\", metric=\"PNC\")\n", "print(f\"decay {by_name.decay_rate_per_hour:.3f} per hour, \"\n", " f\"R^2 {by_name.decay_r_squared:.4f}\")" ], "id": "cell-23" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Fitting a different metric\n", "\n", "`metric` accepts anything `summarize_exposure` accepts. Mass-based metrics\n", "decay faster than number, because they are dominated by larger particles that\n", "settle out." ], "id": "cell-24" }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for metric in [\"PNC\", \"PM1\", \"PM10\"]:\n", " f = ns.fit_decay(period=window, metric=metric)\n", " print(f\"{metric:5s} decay {f.decay_rate_per_hour:6.3f} /h \"\n", " f\"half-life {f.half_life_hours * 60:5.1f} min\")" ], "id": "cell-25" }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "\n", "**Next:** [10a — Correlation and agreement](10a-correlation-and-agreement.ipynb)." ], "id": "cell-26" } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.11" } }, "nbformat": 4, "nbformat_minor": 5 }