.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "report/infant_sne/plot_infant_sne_yields.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_report_infant_sne_plot_infant_sne_yields.py: Infant Supernova Triggers ========================= How many infant supernovae does UVEX find, and how many can it trigger on early enough to get a spectrum? **Infant SNe** are the internal triggers we can expect from UVEX, and can be used to trigger follow-up spectroscopy. To make sure that spectroscopic follow-up is possible, we define an infant SN as an event that reaches **20 AB mag** or brighter (:math:`m \le 20`, ``INFANT_MAG``) in a :math:`\ge 5\sigma` detection within the first **48 hours** (``WINDOW_HR``) after the last non-detection in the same band. To actually trigger on these events, we need cuts that can be applied early in the alert stream and serve as indicators. For a given event, we consider the following conditions, each evaluated on :math:`\ge 5\sigma` detections within 48 hours of the last non-detection in the same band: (a) The event has brightened by at least :math:`X` AB magnitudes in at least 1 band, from the limit at its last non-detection to the current detection. (b) The event is brightening at a rate of at least :math:`Y` AB mag / day in at least 1 band, from the limit at its last non-detection to the current detection. An event is **triggered** if and only if (a) OR (b) is satisfied. The thresholds :math:`X` and :math:`Y`, along with the infant magnitude and time window, are the settings below. The analysis reads the event summary and photometry tables of the infant supernova run from the latest release, through :func:`~uvex_transients.utils.results.get_results`. The brightening in (a) and (b) is measured from the limit at the last non-detection, which is one of the photometry rows, so it needs the photometry to reach back before the explosion (``photometry_pre_window`` in ``configs/infant_sne.yaml``). A release cut without it cannot satisfy (a) or (b), so nothing triggers. .. GENERATED FROM PYTHON SOURCE LINES 31-49 .. code-block:: Python import warnings import astropy.units as u import matplotlib.pyplot as plt import numpy as np from astropy.table import Table from erfa import ErfaWarning import uvex_transients.transients from uvex_transients.dust import log_attenuation from uvex_transients.missions import get_mission from uvex_transients.simulation import estimate_yield from uvex_transients.utils import get_results, get_rng # Reading the time columns triggers "dubious year" warnings; they're harmless. warnings.filterwarnings("ignore", category=ErfaWarning) .. GENERATED FROM PYTHON SOURCE LINES 50-54 Settings --------- The trigger configuration. Change any of these and everything below follows. .. GENERATED FROM PYTHON SOURCE LINES 54-64 .. code-block:: Python DET_SNR = 5 # S/N for a detection (and for the limiting magnitude of a non-detection) INFANT_MAG = 20.0 # infant SNe must reach m <= INFANT_MAG ... WINDOW_HR = 48 # ... within this many hours of the last non-detection in the same band X_BRIGHTEN = 3.0 # (a) brightening since the last non-detection limit, mag Y_RATE = 3.0 # (b) brightening rate since the last non-detection limit, mag / day USE_A, USE_B = True, True # which conditions enter the OR .. GENERATED FROM PYTHON SOURCE LINES 65-69 Load the tables ---------------- The event summary has one row per detected event, and the photometry one row per observation of those events. .. GENERATED FROM PYTHON SOURCE LINES 69-80 .. code-block:: Python try: paths = get_results(["summary", "photometry"], simulation="infant_sne") summary = Table.read(paths["summary"], format="ascii.ecsv") photometry = Table.read(paths["photometry"], format="ascii.ecsv") except (ConnectionError, LookupError, OSError, ValueError) as err: summary = photometry = None print(f"Skipping this page's analysis, the release data is not available: {err}") else: print(f"Loaded {len(summary)} events and {len(photometry)} photometry rows.") .. rst-class:: sphx-glr-script-out .. code-block:: none Extracting event_summary.ecsv: 0%| | 0.00/3.62M [00:00= DET_SNR, ab_mag <= INFANT_MAG and dt_last_nondet <= WINDOW_HR. is_infant = ( (photometry["ab_mag"] <= INFANT_MAG) & (photometry["dt_last_nondet"] <= WINDOW_HR / 24) & (photometry["snr"] >= DET_SNR) ) is_infant_theory = ( (photometry["ab_mag"] <= INFANT_MAG) & (photometry["rel_time"] <= WINDOW_HR / 24) & (photometry["snr"] >= DET_SNR) ) infant_ids = np.asarray(list(set(photometry["event_id"][is_infant]))) infant_theory_ids = np.asarray(list(set(photometry["event_id"][is_infant_theory]))) print(f"There are {len(infant_ids)} infant SNe, and {len(infant_theory_ids)} in theory.") infant_summary = summary[np.isin(summary["event_id"], infant_ids)] infant_phot = photometry[np.isin(photometry["event_id"], infant_ids)] def earliest_passing_rows(photometry, epoch_mask): """Event ids and photometry rows of the earliest epoch of each event for which epoch_mask holds. Both bands are exposed together, so ties between bands resolve to whichever row comes first in the table. """ candidates = np.flatnonzero(epoch_mask) event_id = np.asarray(photometry["event_id"])[candidates] by_event_time = np.lexsort((photometry["obs_time"].mjd[candidates], event_id)) candidates = candidates[by_event_time] event_ids, first = np.unique(event_id[by_event_time], return_index=True) return event_ids, candidates[first] .. rst-class:: sphx-glr-script-out .. code-block:: none There are 10 infant SNe, and 50 in theory. .. GENERATED FROM PYTHON SOURCE LINES 170-181 Cuts (a) and (b) ----------------- For each infant SN, find the earliest epoch at which each condition holds: a :math:`\ge 5\sigma` detection within ``WINDOW_HR`` of the last non-detection in the same band that - (a) has brightened by at least ``X_BRIGHTEN`` mag relative to the 5-sigma limit of that non-detection, - (b) has brightened at a rate of at least ``Y_RATE`` mag / day since that limit. Each returns the ``event_id`` of the infant SNe that pass, and the row of the photometry holding the earliest passing epoch, which is the time at which that trigger would fire. .. GENERATED FROM PYTHON SOURCE LINES 181-200 .. code-block:: Python if summary is not None: dt = np.asarray(infant_phot["dt_last_nondet"]) detected = np.asarray(infant_phot["snr"]) >= DET_SNR in_window = (dt > 0) & (dt <= WINDOW_HR / 24) # Brightening (mag, > 0 when brighter) from the last non-detection limit to this detection. The limit is # NaN where the non-detection is not in the photometry, so those epochs never pass (a) or (b). with np.errstate(invalid="ignore", divide="ignore"): brightening = np.asarray(infant_phot["m_last_nondet"]) - np.asarray(infant_phot["ab_mag"]) meets_a = detected & in_window & (brightening >= X_BRIGHTEN) meets_b = detected & in_window & (brightening / dt >= Y_RATE) cut_ids, cut_rows = {}, {} for name, meets in (("a", meets_a), ("b", meets_b)): cut_ids[name], cut_rows[name] = earliest_passing_rows(infant_phot, meets) print(f"(a) brightened >= {X_BRIGHTEN} mag: {len(cut_ids['a'])} of {len(infant_summary)} infant SNe") print(f"(b) rate >= {Y_RATE} mag/day: {len(cut_ids['b'])} of {len(infant_summary)} infant SNe") .. rst-class:: sphx-glr-script-out .. code-block:: none (a) brightened >= 3.0 mag: 10 of 10 infant SNe (b) rate >= 3.0 mag/day: 6 of 10 infant SNe .. GENERATED FROM PYTHON SOURCE LINES 201-206 Union of the cuts ------------------ An infant SN is triggered if (a) OR (b) holds, restricted to the conditions switched on by ``USE_A`` and ``USE_B``. .. GENERATED FROM PYTHON SOURCE LINES 206-216 .. code-block:: Python if summary is not None: passing = [cut_ids[name] for name, use in (("a", USE_A), ("b", USE_B)) if use] triggered_ids = ( np.unique(np.concatenate(passing)) if passing else np.array([], dtype=np.asarray(infant_summary["event_id"]).dtype) ) print(f"Triggered on {len(triggered_ids)} of {len(infant_summary)} infant SNe.") .. rst-class:: sphx-glr-script-out .. code-block:: none Triggered on 10 of 10 infant SNe. .. GENERATED FROM PYTHON SOURCE LINES 217-230 Yield comparison ----------------- The expected number of events in each category: the sum of the event weights, where each Monte Carlo event stands for :math:`\mu_0 / n` real ones. Every cut is a subset of the one before it, except that the two conditions are alternative ways of triggering on the infants. The overall detections dwarf everything else, so they get a panel of their own. Each bar carries two uncertainties, from :func:`~uvex_transients.simulation.rates.estimate_yield`. The dark bars are the Monte Carlo error of the finite sample (a Clopper-Pearson interval on the selected fraction of each type, added in quadrature across types since the draws are independent). The light bars are the uncertainty on the volumetric rates, summed across types, which assumes the types' rates are fully correlated and so is conservative. Rare categories are dominated by the Monte Carlo error. .. GENERATED FROM PYTHON SOURCE LINES 230-296 .. code-block:: Python def yield_with_errors(event_ids): """Expected events for the given event ids, with Monte Carlo and rate uncertainties. Returns the total and, for each of the Monte Carlo and rate uncertainties, the (lower, upper) distance from the total to its bounds. """ per_type = estimate_yield(summary, mask=np.isin(summary["event_id"], event_ids)) expected = np.asarray(per_type["expected_events"]) mc_lower = expected - np.asarray(per_type["expected_events_binom_lower"]) mc_upper = np.asarray(per_type["expected_events_binom_upper"]) - expected rate_lower = expected - np.asarray(per_type["expected_events_rate_lower"]) rate_upper = np.asarray(per_type["expected_events_rate_upper"]) - expected return ( expected.sum(), (np.hypot.reduce(mc_lower), np.hypot.reduce(mc_upper)), (rate_lower.sum(), rate_upper.sum()), ) categories = ["Detections\n(overall)", "Infants", "Infants\n(theory)", "(a)", "(b)", "(a) OR (b)"] if summary is not None: detected_ids = np.asarray(summary["event_id"])[np.asarray(summary["n_det"]) > 0] yields = [ yield_with_errors(ids) for ids in ( detected_ids, infant_summary["event_id"], infant_theory_ids, cut_ids["a"], cut_ids["b"], triggered_ids, ) ] for name, (total, mc, rate) in zip(categories, yields): print( f"{name.replace(chr(10), ' '):<24} {total:>8.1f} MC +{mc[1]:.1f}/-{mc[0]:.1f} " f"rate +{rate[1]:.1f}/-{rate[0]:.1f}" ) # The overall detections dwarf everything else, so they get their own panel. fig, (ax_det, ax_rest) = plt.subplots(1, 2, figsize=(11, 4.5), gridspec_kw={"width_ratios": [1, 6], "wspace": 0.12}) for ax, cols, fmt in ((ax_det, [0], "{:.0f}"), (ax_rest, range(1, len(categories)), "{:.1f}")): x = np.arange(len(cols)) total = np.array([yields[c][0] for c in cols]) mc = np.array([yields[c][1] for c in cols]).T rate = np.array([yields[c][2] for c in cols]).T ax.bar(x, total, 0.7, color="#2a78d6") ax.errorbar(x + 0.12, total, yerr=rate, fmt="none", ecolor="#9aa5b1", elinewidth=3, capsize=0) ax.errorbar(x - 0.12, total, yerr=mc, fmt="none", ecolor="k", elinewidth=1.2, capsize=3) for xi, t, top in zip(x, total, (total + np.maximum(mc[1], rate[1]))): ax.annotate(fmt.format(t), (xi, top), xytext=(0, 3), textcoords="offset points", ha="center", fontsize=8) ax.set_xticks(x, [categories[c] for c in cols]) ax.margins(y=0.12) ax.spines[["top", "right"]].set_visible(False) ax_det.set_ylabel("Expected events (weighted)") fig.suptitle( f"Yield (X={X_BRIGHTEN} mag, Y={Y_RATE} mag/day, " f"infant: m <= {INFANT_MAG} within {WINDOW_HR} hr)\nblack: Monte Carlo error, grey: rate uncertainty", fontsize=11, ) plt.show() .. image-sg:: /report/infant_sne/images/sphx_glr_plot_infant_sne_yields_001.png :alt: Yield (X=3.0 mag, Y=3.0 mag/day, infant: m <= 20.0 within 48 hr) black: Monte Carlo error, grey: rate uncertainty :srcset: /report/infant_sne/images/sphx_glr_plot_infant_sne_yields_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none Detections (overall) 4407.7 MC +103.2/-100.7 rate +1431.5/-1591.8 Infants 10.0 MC +9.9/-4.3 rate +3.7/-4.0 Infants (theory) 49.9 MC +15.3/-10.7 rate +16.7/-18.6 (a) 10.0 MC +9.9/-4.3 rate +3.7/-4.0 (b) 6.0 MC +9.1/-3.1 rate +2.1/-2.3 (a) OR (b) 10.0 MC +9.9/-4.3 rate +3.7/-4.0 .. GENERATED FROM PYTHON SOURCE LINES 297-301 Infant population ------------------ What kinds of events are the infant SNe? The raw counts, and the expected number (the sum of the weights). .. GENERATED FROM PYTHON SOURCE LINES 301-317 .. code-block:: Python if summary is not None: infant_yields = estimate_yield(summary, mask=np.isin(summary["event_id"], infant_ids)) types = np.asarray(infant_yields["transient_type"]).astype(str) n_raw = np.asarray(infant_yields["n_selected"]) n_weighted = np.asarray(infant_yields["expected_events"]) mc_lower = n_weighted - np.asarray(infant_yields["expected_events_binom_lower"]) mc_upper = np.asarray(infant_yields["expected_events_binom_upper"]) - n_weighted print(f"{len(infant_summary)} infant SNe ({n_weighted.sum():.1f} expected)") for i in np.argsort(-n_weighted): print( f" {types[i]:<16} {n_raw[i]:>3} events " f"({n_weighted[i]:.1f} +{mc_upper[i]:.1f}/-{mc_lower[i]:.1f} expected, Monte Carlo error)" ) .. rst-class:: sphx-glr-script-out .. code-block:: none 10 infant SNe (10.0 expected) iip_sne 5 events (5.0 +5.5/-3.0 expected, Monte Carlo error) iib_sne 5 events (4.9 +5.5/-3.0 expected, Monte Carlo error) ia_sne 0 events (0.0 +3.1/-0.0 expected, Monte Carlo error) ib_sne 0 events (0.0 +2.6/-0.0 expected, Monte Carlo error) icbl_sne 0 events (0.0 +2.2/-0.0 expected, Monte Carlo error) ic_sne 0 events (0.0 +2.9/-0.0 expected, Monte Carlo error) slsne 0 events (0.0 +2.9/-0.0 expected, Monte Carlo error) .. GENERATED FROM PYTHON SOURCE LINES 318-328 Light curves ------------- The measured photometry (detections and 5-sigma limits) of triggered events against days since explosion, with the noiseless model light curve of the same event. The model is rebuilt the way the simulation built it: the transient class, its SED parameters from the event's own ``parameter_seed``, and then the SED averaged over each UVEX bandpass, with the event's Milky Way reddening applied. The dotted line is the explosion, and the dashed lines are the last non-detection of each band. The inset zooms in on the first days. ``EVENT_IDS`` picks the events. By default ``N_EXAMPLES`` of the triggered ones are drawn at random. .. GENERATED FROM PYTHON SOURCE LINES 328-459 .. code-block:: Python EVENT_IDS = None # for example [35726] N_EXAMPLES = 3 BAND_COLORS = {"FUV": "tab:blue", "NUV": "tab:red"} X_RANGE = (-30, 60) # days since explosion INSET_RANGE = (-2, 5) # The transient class of each population, as the run config names them. TRANSIENT_CLASSES = { "iip_sne": "TypeIIPSNe", "iib_sne": "TypeIIbSNe", "ib_sne": "TypeIbSNe", "ic_sne": "TypeIcSNe", "icbl_sne": "TypeIcBLSNe", "slsne": "MagnetarSLSNe", "ia_sne": "TypeIaSNe", } def theory_mag(event, bandpass, t_days): """Noiseless apparent AB magnitude of the event's model in `bandpass` at `t_days` since explosion.""" transient = getattr(uvex_transients.transients, TRANSIENT_CLASSES[str(event["transient_type"])])() rng = get_rng(int(event["parameter_seed"])) sed_params = {name: value[0] for name, value in transient.sed.sample_parameters(size=1, rng=rng).items()} nu = bandpass.waveset.to(u.Hz, equivalencies=u.spectral()) mag = transient.sed.mag_bandpass( bandpass, t_days * u.day, redshift=float(event["redshift"]), luminosity_distance=float(event["luminosity_distance"]) * u.Mpc, log_attenuation=log_attenuation(nu, float(event["ebv"])), **sed_params, ) return mag.value def plot_event(event_id): """Plot the photometry and model light curve of one event, with an inset on its first days.""" row = np.flatnonzero(summary["event_id"] == event_id)[0] event = summary[row] # Last non-detection of each band, in days since explosion (NaN if the event has none). t_explosion_mjd = summary["t_explosion"].mjd[row] t_last_nondet = { band: np.ma.filled(summary[f"t_last_nondet_{band}"].mjd, np.nan)[row] - t_explosion_mjd for band in BAND_COLORS } phot = photometry[photometry["event_id"] == event_id] t = np.asarray(phot["rel_time"]) band_of = np.asarray(phot["band"]) detected = np.asarray(phot["snr"]) >= DET_SNR ab_mag = np.asarray(phot["ab_mag"]) m_limit = -2.5 * np.log10(DET_SNR * np.asarray(phot["flux_err"]) / 3631) # 5-sigma limit (flux in Jy) # The model only exists after the explosion; sample the first couple of days more densely. t_model = np.concatenate([np.linspace(0.005, 2, 300), np.linspace(2, X_RANGE[1], 300)[1:]]) bandpasses = get_mission("uvex_fast").detector.bandpasses theory = {band: theory_mag(event, bandpasses[band], t_model) for band in BAND_COLORS} def draw(ax, labels): for band, color in BAND_COLORS.items(): in_band = band_of == band det, non_det = in_band & detected, in_band & ~detected ax.plot(t_model, theory[band], color=color, lw=1.2, alpha=0.8, label=f"{band} model" if labels else None) ax.errorbar( t[det], ab_mag[det], yerr=phot["mag_err"][det], color=color, marker="o", ms=4, ls="", capsize=2, label=f"{band} detection" if labels else None, ) ax.plot( t[non_det], m_limit[non_det], color=color, marker="v", mfc="none", ms=4, ls="", label=f"{band} 5σ limit" if labels else None, ) ax.axvline(0, color="k", ls=":", lw=1) for band, color in BAND_COLORS.items(): if np.isfinite(t_last_nondet[band]): ax.axvline( t_last_nondet[band], color=color, ls="--", lw=1, label=f"{band} last non-det" if labels else None ) def mag_range(window): """(faint, bright) magnitude limits for `window`: the faint end holds the detections and limits, the bright end also the model (which diverges to infinitely faint at the explosion).""" in_window = (t >= window[0]) & (t <= window[1]) mags = np.concatenate([ab_mag[in_window & detected], m_limit[in_window & ~detected]]) mags = mags[np.isfinite(mags)] in_model_window = (t_model >= window[0]) & (t_model <= window[1]) model_bright = min(np.nanmin(theory[band][in_model_window]) for band in BAND_COLORS) if mags.size == 0: # nothing was measured in the window, so show the model return model_bright + 3, model_bright - 0.5 return mags.max() + 0.5, min(mags.min(), model_bright) - 0.5 fig, ax = plt.subplots(figsize=(10, 5)) draw(ax, labels=True) ax.set_xlim(*X_RANGE) ax.set_ylim(*mag_range(X_RANGE)) ax.set_xlabel("Days since explosion") ax.set_ylabel("AB mag") ax.set_title(f"Event {event_id} ({event['transient_type']}, z = {event['redshift']:.3f})") ax.legend(fontsize=8, ncol=2, loc="upper left") inset = ax.inset_axes([0.6, 0.45, 0.3, 0.5]) draw(inset, labels=False) inset.set_xlim(*INSET_RANGE) inset.set_ylim(*mag_range(INSET_RANGE)) inset.tick_params(labelsize=7) if summary is not None: if EVENT_IDS is None: pool = triggered_ids if len(triggered_ids) else infant_ids # nothing triggered: fall back to the infants EVENT_IDS = np.random.default_rng(42).choice(pool, size=min(N_EXAMPLES, len(pool)), replace=False) if len(EVENT_IDS) == 0: print("There are no infant SNe in this release to plot.") for event_id in EVENT_IDS: plot_event(int(event_id)) plt.show() .. rst-class:: sphx-glr-horizontal * .. image-sg:: /report/infant_sne/images/sphx_glr_plot_infant_sne_yields_002.png :alt: Event 29944 (iib_sne, z = 0.035) :srcset: /report/infant_sne/images/sphx_glr_plot_infant_sne_yields_002.png :class: sphx-glr-multi-img * .. image-sg:: /report/infant_sne/images/sphx_glr_plot_infant_sne_yields_003.png :alt: Event 6006 (iip_sne, z = 0.025) :srcset: /report/infant_sne/images/sphx_glr_plot_infant_sne_yields_003.png :class: sphx-glr-multi-img * .. image-sg:: /report/infant_sne/images/sphx_glr_plot_infant_sne_yields_004.png :alt: Event 25369 (iip_sne, z = 0.021) :srcset: /report/infant_sne/images/sphx_glr_plot_infant_sne_yields_004.png :class: sphx-glr-multi-img .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 7.811 seconds) .. _sphx_glr_download_report_infant_sne_plot_infant_sne_yields.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_infant_sne_yields.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_infant_sne_yields.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_infant_sne_yields.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_