{ "cells": [ { "cell_type": "markdown", "id": "0", "metadata": {}, "source": [ "# Multiband parametric fit: RAINBOW model\n", "\n", "[`RainbowFit`](../api/rainbow/#light_curve.RainbowFit) fits a physical **blackbody + bolometric-light-curve** model to multi-band\n", "photometric time series. It is designed for extragalactic transients such as supernovae,\n", "kilonovae, or tidal disruption events, where the SED is well approximated by a Planck\n", "function whose temperature and luminosity evolve with time.\n", "\n", "The method is described in [Russeil et al. 2024](https://ui.adsabs.harvard.edu/abs/2024A%26A...683A.251R/abstract).\n", "\n", "## Prerequisites\n", "\n", "[`RainbowFit`](../api/rainbow/#light_curve.RainbowFit) requires [`iminuit`](https://iminuit.readthedocs.io/) ≥ 2.21.\n", "Install it together with all optional dependencies or separately.\n", "We would also need `matplotlib` for plotting, but of course it is not needed for the fitting itself." ] }, { "cell_type": "code", "execution_count": null, "id": "1", "metadata": {}, "outputs": [], "source": [ "# %pip install \"light-curve[full]\" matplotlib\n", "# OR\n", "# %pip install light-curve iminuit matplotlib" ] }, { "cell_type": "code", "execution_count": null, "id": "2", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "from light_curve import RainbowFit" ] }, { "cell_type": "markdown", "id": "3", "metadata": {}, "source": [ "## Generating synthetic supernova data\n", "\n", "We simulate a Bazin-shaped bolometric light curve with a sigmoid temperature evolution,\n", "observed in four LSST-like bands (*g r i z*). Observations are flux densities — not\n", "magnitudes — because `RainbowFit` works in linear flux space.\n", "\n", "The sigmoid temperature is parametrized by the **mid temperature** `T` = $(T_\\text{min}+T_\\text{max})/2$\n", "and a dimensionless **relative amplitude** `T_amplitude` = $(T_\\text{max}-T_\\text{min})/(T_\\text{max}+T_\\text{min})$,\n", "so $T_\\text{max} = T(1 + \\texttt{T\\_amplitude})$ and $T_\\text{min} = T(1 - \\texttt{T\\_amplitude})$. Here the\n", "source cools between 15 000 K and 5 000 K, i.e. `T` = 10 000 K and `T_amplitude` = 0.5.\n", "\n", "### Physical parameters\n", "\n", "| Parameter | Symbol | Value |\n", "|-----------|--------|-------|\n", "| Peak time | $t_0$ | 60 000 (MJD) |\n", "| Amplitude | $A$ | 1.0 |\n", "| Rise time | $t_\\text{rise}$ | 5 d |\n", "| Fall time | $t_\\text{fall}$ | 30 d |\n", "| Mid temperature | $T = (T_\\text{min}+T_\\text{max})/2$ | 10 000 K |\n", "| Relative amplitude | $T_\\text{amplitude} = \\frac{T_\\text{max}-T_\\text{min}}{T_\\text{max}+T_\\text{min}}$ | 0.5 (i.e. $T_\\text{min}$ = 5 000 K, $T_\\text{max}$ = 15 000 K) |\n", "| Colour timescale | $t_\\text{color}$ | 10 d |" ] }, { "cell_type": "code", "execution_count": null, "id": "4", "metadata": {}, "outputs": [], "source": [ "rng = np.random.default_rng(0)\n", "\n", "# Effective wavelengths in Angstrom for griz\n", "band_wave_aa = {\"g\": 4770.0, \"r\": 6231.0, \"i\": 7625.0, \"z\": 9134.0}\n", "\n", "# True parameters\n", "reference_time = 60_000.0\n", "amplitude = 1.0\n", "rise_time = 5.0\n", "fall_time = 30.0\n", "Tmax = 15_000.0 # hot (early) temperature\n", "Tmin = 5_000.0 # cool (late) floor\n", "t_color = 10.0\n", "\n", "# Sigmoid temperature fit parameters: mid temperature and relative amplitude\n", "T_mid = 0.5 * (Tmin + Tmax) # = 10 000 K\n", "T_amplitude = (Tmax - Tmin) / (Tmax + Tmin) # = 0.5\n", "\n", "# Per-band baseline flux (constant offset)\n", "baselines = {b: 0.3 * amplitude + rng.exponential(scale=0.3 * amplitude) for b in band_wave_aa}\n", "\n", "# Build the feature object first so we can use .model() to generate data\n", "feature = RainbowFit.from_angstrom(\n", " band_wave_aa,\n", " with_baseline=True,\n", " bolometric=\"bazin\",\n", " temperature=\"sigmoid\",\n", ")\n", "\n", "# True parameter vector, in feature.names order:\n", "# common + bolometric + temperature + baselines + chi2_placeholder\n", "true_params = [\n", " reference_time, amplitude, rise_time, fall_time, # Bazin bolometric\n", " T_mid, T_amplitude, t_color, # sigmoid temperature: T (mid), T_amplitude, t_color\n", " *baselines.values(), # per-band baselines\n", " 1.0, # reduced chi^2 placeholder\n", "]\n", "\n", "# Random observation times covering ±3 rise/fall windows\n", "n_obs = 1000\n", "t = np.sort(rng.uniform(reference_time - 3 * rise_time, reference_time + 3 * fall_time, n_obs))\n", "band = rng.choice(list(band_wave_aa), size=n_obs)\n", "\n", "# True model flux\n", "flux = feature.model(t, band, *true_params)\n", "\n", "# Poisson-like noise: S/N=10 at minimum flux\n", "flux_err = np.sqrt(flux * np.min(flux)) / 10.0\n", "flux = flux + rng.normal(0.0, flux_err)\n", "\n", "print(f\"Generated {n_obs} observations in bands {list(band_wave_aa)}\")" ] }, { "cell_type": "markdown", "id": "5", "metadata": {}, "source": [ "## Fitting the light curve\n", "\n", "Call `feature(t, flux, sigma=flux_err, band=band)`. The result is a NumPy array of\n", "fit parameters followed by the **reduced χ²** of the fit." ] }, { "cell_type": "code", "execution_count": null, "id": "6", "metadata": {}, "outputs": [], "source": [ "result = feature(t, flux, sigma=flux_err, band=band)\n", "\n", "# Parameter names are stored in feature.names\n", "print(\"Parameter names:\", feature.names)\n", "print()\n", "for name, val, true in zip(feature.names, result, true_params):\n", " print(f\" {name:25s} fitted={val:10.3f} true={true:10.3f}\")" ] }, { "cell_type": "markdown", "id": "7", "metadata": {}, "source": [ "## Visualising the fit\n", "\n", "Plot the data and the best-fit model curve for each band." ] }, { "cell_type": "code", "execution_count": null, "id": "8", "metadata": {}, "outputs": [], "source": [ "colors = {\"g\": \"#2ca02c\", \"r\": \"#d62728\", \"i\": \"#9467bd\", \"z\": \"#8c564b\"}\n", "\n", "fig, ax = plt.subplots(figsize=(9, 4))\n", "\n", "t_grid = np.linspace(t.min(), t.max(), 400)\n", "\n", "for b in band_wave_aa:\n", " mask = band == b\n", " ax.errorbar(\n", " t[mask], flux[mask], yerr=flux_err[mask],\n", " fmt=\".\", color=colors[b], alpha=0.4, label=f\"{b} data\",\n", " )\n", " band_grid = np.full(len(t_grid), b)\n", " ax.plot(t_grid, feature.model(t_grid, band_grid, *result), color=colors[b], lw=2)\n", "\n", "ax.set_xlabel(\"Time (MJD)\")\n", "ax.set_ylabel(\"Flux density\")\n", "ax.set_title(\"RainbowFit — Bazin bolometric, sigmoid temperature\")\n", "ax.legend(ncol=2, fontsize=8)\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "9", "metadata": {}, "source": [ "## Parameter uncertainties\n", "\n", "`fit_and_get_errors` returns a `(params, errors)` tuple. The errors are estimated by\n", "`iminuit` from the Hessian of the chi-squared surface." ] }, { "cell_type": "code", "execution_count": null, "id": "10", "metadata": {}, "outputs": [], "source": [ "params, errors = feature.fit_and_get_errors(t, flux, sigma=flux_err, band=band)\n", "\n", "print(f\"{'Parameter':25s} {'Value':>10s} {'Error':>10s} {'True':>10s}\")\n", "print(\"-\" * 62)\n", "for name, val, err, true in zip(feature.names, params, errors, true_params):\n", " print(f\"{name:25s} {val:10.3f} {err:10.3f} {true:10.3f}\")" ] }, { "cell_type": "markdown", "id": "11", "metadata": {}, "source": [ "## Peak time\n", "\n", "The bolometric peak time can differ from `reference_time` for asymmetric light curves.\n", "`feature.peak_time(params)` computes it analytically from the bolometric term." ] }, { "cell_type": "code", "execution_count": null, "id": "12", "metadata": {}, "outputs": [], "source": [ "t_peak = feature.peak_time(params)\n", "print(f\"Fitted peak time : {t_peak:.2f} MJD\")\n", "print(f\"True peak time : {feature.peak_time(np.array(true_params)):.2f} MJD\")" ] }, { "cell_type": "markdown", "id": "13", "metadata": {}, "source": [ "## Choosing different models\n", "\n", "`RainbowFit` accepts pluggable **bolometric**, **temperature**, and **spectral** terms.\n", "\n", "### Bolometric terms\n", "\n", "| Name | Parameters | Description |\n", "|------|-----------|-------------|\n", "| `'bazin'` (default) | `reference_time, amplitude, rise_time, fall_time` | Bazin 2011 rise-and-fall |\n", "| `'sigmoid'` | `reference_time, amplitude, rise_time` | Logistic rise only |\n", "| `'linexp'` | `reference_time, amplitude, rise_time` | Linear rise, exponential decay |\n", "| `'doublexp'` | `reference_time, amplitude, time1, time2, p` | Exponential rise, decay with two exponentials |\n", "\n", "### Temperature terms\n", "\n", "The sigmoid terms use the mid temperature `T` = $(T_\\text{min}+T_\\text{max})/2$ and a relative\n", "amplitude `T_amplitude` = $(T_\\text{max}-T_\\text{min})/(T_\\text{max}+T_\\text{min})$\n", "(`T_amplitude` = 0 is a constant temperature; a weak prior anchors it there unless the data demand a\n", "temperature change). Strictly positive temperature corresponds to the independent box `T > 0`,\n", "`-1 < T_amplitude < 1`.\n", "\n", "| Name | Parameters | Description |\n", "|------|-----------|-------------|\n", "| `'sigmoid'` (default) | `T, T_amplitude, t_color` | Temperature drops sigmoidally between $T(1+\\texttt{T\\_amplitude})$ and $T(1-\\texttt{T\\_amplitude})$ |\n", "| `'constant'` | `T` | Fixed temperature |\n", "| `'delayed_sigmoid'` | `T, T_amplitude, t_color, t_delay` | Sigmoid delayed relative to the bolometric peak |\n", "\n", "### Spectral terms\n", "\n", "`'planck'` is a pure blackbody. The other terms describe SEDs that *deviate* from a blackbody\n", "(UV blanketing or power-law spectra); each reduces to Planck at a **null** parameter value and\n", "carries a weak Gaussian prior anchoring it there, so a true blackbody is recovered unbiased.\n", "\n", "| Name | Parameters | Description |\n", "|------|-----------|-------------|\n", "| `'planck'` (default) | *(none)* | Standard blackbody $B_\\nu(T)$ — no extra parameters |\n", "| `'blanketed'` | `lambda_scale` | UV-extincted blackbody $B_\\nu(T)\\,e^{-\\tau}$, $\\tau = I\\,e^{-\\lambda/\\lambda_s}$; the extinction reach $\\lambda_s$ is anchored to the characteristic temperature `T` (shared with the temperature term) so the blanketing depth stays fixed as the source cools |\n", "| `'modified_bb'` | `beta` | Planck tilted by a power law, $B_\\nu(T)\\,(\\lambda/\\lambda_\\text{ref})^{\\beta}$; $\\beta = 0 \\Rightarrow$ Planck |\n", "| `'logparabola'` | `sp_a, sp_b` | Planck × $e^{a L + b L^2}$, $L = \\ln(\\lambda/\\lambda_\\text{ref})$; $a = b = 0 \\Rightarrow$ Planck |\n", "| `'genwien'` | `spec_k` | Generalized Wien $B_\\nu \\propto \\nu^3 e^{-x^{\\,\\texttt{spec\\_k}}}$, $x = h\\nu/k_B T$; $\\texttt{spec\\_k} = 1 \\Rightarrow$ Wien tail |\n", "\n", "Both backends accept an `optimizer` argument: `\"iminuit\"` (default, robust Migrad) or\n", "`\"least_squares\"` (scipy Trust Region Reflective, sharing the same analytic Jacobian — usually\n", "faster, with an automatic fall-back to iminuit when needed)." ] }, { "cell_type": "code", "execution_count": null, "id": "14", "metadata": {}, "outputs": [], "source": [ "# Constant temperature — fewer parameters, useful for bluer transients\n", "feature_const_T = RainbowFit.from_angstrom(\n", " band_wave_aa,\n", " with_baseline=False,\n", " bolometric=\"bazin\",\n", " temperature=\"constant\",\n", ")\n", "result_const = feature_const_T(t, flux, sigma=flux_err, band=band)\n", "print(\"Parameters (constant T model):\")\n", "for name, val in zip(feature_const_T.names, result_const):\n", " print(f\" {name:25s} {val:.3f}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "15", "metadata": {}, "outputs": [], "source": [ "# Blanketed blackbody — adds UV extinction parameters: lambda_scale\n", "feature_blanketed = RainbowFit.from_angstrom(\n", " band_wave_aa,\n", " with_baseline=False,\n", " bolometric=\"bazin\",\n", " temperature=\"sigmoid\",\n", " spectral=\"blanketed\",\n", ")\n", "result_blanketed = feature_blanketed(t, flux, sigma=flux_err, band=band)\n", "print(\"Parameters (blanketed spectral model):\")\n", "for name, val in zip(feature_blanketed.names, result_blanketed):\n", " print(f\" {name:25s} {val:.3f}\")" ] }, { "cell_type": "markdown", "id": "16", "metadata": {}, "source": [ "### Non-blackbody SED terms and the fast optimizer\n", "\n", "Beyond `'blanketed'`, the spectral terms `'modified_bb'`, `'logparabola'`, and `'genwien'`\n", "describe SEDs that depart from a pure blackbody (a power-law tilt, a log-parabola, or a\n", "generalized-Wien blue cutoff). Each reduces to Planck at a *null* parameter value\n", "(`beta = 0`, `sp_a = sp_b = 0`, `spec_k = 1`), and a weak prior anchors it there — so fitting\n", "them to genuinely blackbody data just recovers that null rather than inventing a deviation.\n", "\n", "The fit itself can run on scipy's `least_squares` backend via `optimizer=\"least_squares\"`,\n", "which shares the analytic Jacobian of the default `iminuit` path and is usually faster." ] }, { "cell_type": "code", "execution_count": null, "id": "17", "metadata": {}, "outputs": [], "source": [ "# Each deviation term reduces to a pure blackbody at a \"null\" parameter value, with a weak\n", "# prior anchoring it there. Fitting them to the (blackbody) data above recovers that null —\n", "# i.e. no spurious deviation is introduced.\n", "shape_params = {\"modified_bb\": [\"beta\"], \"logparabola\": [\"sp_a\", \"sp_b\"], \"genwien\": [\"spec_k\"]}\n", "for spectral, shape in shape_params.items():\n", " feat = RainbowFit.from_angstrom(\n", " band_wave_aa, with_baseline=True,\n", " bolometric=\"bazin\", temperature=\"sigmoid\", spectral=spectral,\n", " )\n", " res = feat(t, flux, sigma=flux_err, band=band)\n", " shape_vals = \", \".join(f\"{p}={res[feat.names.index(p)]:+.3f}\" for p in shape)\n", " print(f\"{spectral:12s} reduced chi2 = {res[-1]:.2f} {shape_vals}\")\n", "\n", "# The same model fitted with the scipy least_squares backend (shares the analytic Jacobian).\n", "feature_ls = RainbowFit.from_angstrom(\n", " band_wave_aa, with_baseline=True,\n", " bolometric=\"bazin\", temperature=\"sigmoid\", optimizer=\"least_squares\",\n", ")\n", "result_ls = feature_ls(t, flux, sigma=flux_err, band=band)\n", "print(f\"\\n{'least_squares':12s} reduced chi2 = {result_ls[-1]:.2f} (matches the default iminuit fit)\")" ] }, { "cell_type": "markdown", "id": "18", "metadata": {}, "source": [ "## Binning before fitting\n", "\n", "Light curves may have a very uneven cadence. For example, most nights may have a single observation, while a few\n", "nights have a lot of observations in a single passband. A fit to all observations gives each night a weight\n", "proportional to its number of observations, so a few densely observed nights dominate the $\\chi^2$. Real light curves\n", "never follow the model exactly, so the fit bends the model towards these nights at the expense of the rest of the light\n", "curve.\n", "\n", "[`Bins.bin`](../api/meta/#light_curve.Bins.bin) bins observations of each passband into time intervals, here one bin per\n", "night, returning the weighted mean flux for each bin, so every night contributes a single point. Let's simulate such a\n", "light curve with the `\"linexp\"` bolometric term, and fit it with the `\"bazin\"` one, mimicking a real light curve\n", "which the model describes only approximately." ] }, { "cell_type": "code", "execution_count": null, "id": "19", "metadata": {}, "outputs": [], "source": [ "from light_curve import Bins\n", "\n", "rng = np.random.default_rng(0)\n", "\n", "# The \"true\" light curve: linear rise and exponential decay\n", "feature_true = RainbowFit.from_angstrom(\n", " band_wave_aa,\n", " with_baseline=False,\n", " bolometric=\"linexp\",\n", " temperature=\"sigmoid\",\n", ")\n", "# reference_time, amplitude, rise_time, T, T_amplitude, t_color, reduced chi^2 placeholder\n", "true_params_sparse = [-15.0, amplitude, -20.0, T_mid, T_amplitude, t_color, 1.0]\n", "\n", "# The model we fit: Bazin\n", "feature_sparse = RainbowFit.from_angstrom(\n", " band_wave_aa,\n", " with_baseline=False,\n", " bolometric=\"bazin\",\n", " temperature=\"sigmoid\",\n", ")\n", "\n", "# Most nights have a single observation, three nights have 60 observations each\n", "n_dense = 60\n", "t_sparse = np.r_[\n", " -9.0, -1.0, 4.0, 7.0, 9.0, 11.0, 15.0, 29.0, 41.0, 45.0,\n", " np.linspace(47.0, 47.19, n_dense),\n", " 51.0,\n", " np.linspace(63.0, 63.19, n_dense),\n", " 70.0,\n", " np.linspace(75.0, 75.19, n_dense),\n", " 79.0, 84.0, 87.0,\n", "]\n", "band_sparse = np.r_[\n", " list(\"zrgzzizgrr\"),\n", " [\"g\"] * n_dense,\n", " [\"z\"],\n", " [\"i\"] * n_dense,\n", " [\"z\"],\n", " [\"g\"] * n_dense,\n", " list(\"gzr\"),\n", "]\n", "\n", "flux_sparse = feature_true.model(t_sparse, band_sparse, *true_params_sparse)\n", "flux_err_sparse = np.sqrt(flux_sparse * np.min(flux_sparse)) / 10.0\n", "flux_sparse = flux_sparse + rng.normal(0.0, flux_err_sparse)" ] }, { "cell_type": "markdown", "id": "20", "metadata": {}, "source": [ "Bin the light curve with one-day bins. `Bins` takes a list of features to extract from the binned light curve, we need\n", "only the binned light curve itself, so the list is empty. In multiband mode, `bin()` returns binned times, fluxes,\n", "uncertainties and passbands." ] }, { "cell_type": "code", "execution_count": null, "id": "21", "metadata": {}, "outputs": [], "source": [ "binner = Bins([], window=1.0, offset=0.0, bands=list(band_wave_aa))\n", "t_bin, flux_bin, flux_err_bin, band_bin = binner.bin(t_sparse, flux_sparse, sigma=flux_err_sparse, band=band_sparse)\n", "print(f\"{len(t_sparse)} observations binned into {len(t_bin)} points\")\n", "\n", "params_full = feature_sparse(t_sparse, flux_sparse, sigma=flux_err_sparse, band=band_sparse)\n", "params_bin = feature_sparse(t_bin, flux_bin, sigma=flux_err_bin, band=band_bin)" ] }, { "cell_type": "code", "execution_count": null, "id": "22", "metadata": {}, "outputs": [], "source": [ "fig, axes = plt.subplots(1, 2, figsize=(12, 4), sharey=True)\n", "t_grid = np.linspace(t_sparse.min() - 5, t_sparse.max() + 5, 400)\n", "\n", "for ax, title, params, (t_plot, flux_plot, err_plot, band_plot) in [\n", " (axes[0], \"All observations\", params_full, (t_sparse, flux_sparse, flux_err_sparse, band_sparse)),\n", " (axes[1], \"Binned\", params_bin, (t_bin, flux_bin, flux_err_bin, band_bin)),\n", "]:\n", " for b in band_wave_aa:\n", " mask = band_plot == b\n", " ax.errorbar(t_plot[mask], flux_plot[mask], yerr=err_plot[mask], fmt=\".\", color=colors[b], label=f\"{b} data\")\n", " band_grid = np.full(len(t_grid), b)\n", " ax.plot(t_grid, feature_sparse.model(t_grid, band_grid, *params), color=colors[b], lw=2)\n", " ax.plot(t_grid, feature_true.model(t_grid, band_grid, *true_params_sparse), color=colors[b], lw=1, ls=\"--\")\n", " ax.set_title(f\"{title}\\nfit (solid) and truth (dashed)\")\n", " ax.set_xlabel(\"Time (days)\")\n", "axes[0].set_ylabel(\"Flux density\")\n", "axes[0].legend(ncol=2, fontsize=8)\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "23", "metadata": {}, "source": [ "The fit to all observations is dominated by the densely observed *g* and *i* nights in the tail: to follow them,\n", "it misses the *g* decline and overshoots the *r* peak. The binned fit gives every night the same weight and follows\n", "the true light curve better in all passbands." ] }, { "cell_type": "markdown", "id": "24", "metadata": {}, "source": [ "## See also\n", "\n", "- [RainbowFit API reference](../api/rainbow/#light_curve.RainbowFit)\n", "- [Feature table](../) — all extractors\n", "- [Parametric fits tutorial](../fitting/) — single-band transient fits" ] }, { "cell_type": "code", "execution_count": null, "id": "25", "metadata": {}, "outputs": [], "source": [] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }