"""Helpers for computing on a session's saved results (Discuss mode). This module runs inside the analysis sandbox, next to the snippet the model wrote (results_compute.py copies it into the job directory). It needs numpy and scipy (astropy for dates and luminosities) and reads one file, ``inputs.json``, which the server builds from the tasks' saved products (their SED and light-curve files and the fitted model of the task their fit comes from). Nothing here touches the counts or the likelihood of the analysis: every result rests on those saved numbers, and each helper says so in its ``basis``. The snippet sees this module as ``rh`` and prints what it found; tables and plots are recorded for the page (``table``, ``plot_sed``, ``plot_lc``), which draws them like the Outputs panel. """ import json import math import os import numpy as np MEV_TO_ERG = 1.602176634e-6 _STATE = {'inputs': None, 'out': None, 'records': 0} MAX_RECORDS = 12 MAX_TABLE_ROWS = 200 # What each helper does, in words: the one source for the "How this was # computed" line under a result, the hover card on its name in the code, # the notebook's note before a kept computation, the Discuss prompt and # the documentation index (docs/results_helpers.md, made by # ``python results_helpers.py --markdown``). ``summary`` is one sentence # for the method line; ``detail`` adds the basis and the caveats; ``minor`` # helpers (formatting, plotting, selection) get no method line. METHODS = { 'tasks': {'minor': True, 'summary': 'Lists the tasks with saved results.', 'detail': 'The ids of the finished tasks whose results the computation can read.'}, 'task': {'minor': True, 'summary': 'A task\'s record.', 'detail': 'A finished task: its request, the task it continues from, its fit and its SED and light-curve points as saved.'}, 'fit': {'summary': 'Reads the target\'s fitted spectrum as the task\'s likelihood fit saved it.', 'detail': 'The spectral model, its parameters in true units and the covariance of the fitted ones, read from the model the task saved (end_model_T.npy). A follow-up that only loaded a model gives the fit of the task it continues from.'}, 'sed': {'summary': 'Reads the SED that gta.sed() computed in the task.', 'detail': 'FermiPy\'s SED points (E² dN/dE per energy bin, 95% upper limits where TS < 4) and, per bin, the scan of the log-likelihood against the target\'s normalization in that bin, as saved by the task (or the task it continues from).'}, 'catalog_sed': {'summary': 'Reads the target\'s entry in a LAT catalog as SED points, the same points the SED card draws.', 'detail': 'The band fluxes a catalog publishes for the target (the entry of the same name, else the nearest within 0.2° of it) as E² dN/dE at each band\'s centre in MeV cm⁻² s⁻¹: the catalog\'s own νFν where it gives one (4FGL, FL16Y), else the band flux converted for a power law of index 2 across the band; the 95% upper limit where the catalog gives no lower error; and the catalog\'s spectral model. Labelled with the catalog and the time its data span. Read from the catalog files on the server when the question is asked (4FGL-DR4, FL16Y, 4FGL-DR3, 4LAC-DR3, 4FHL, 3FHL, 2FHL, where installed and listing the source); the catalog has no likelihood scans, so it can be plotted and compared but not fitted with fit_sed.'}, 'lc': {'summary': 'Reads the light curve that gta.lightcurve() computed in the task.', 'detail': 'FermiPy\'s light-curve bins (photon flux over the analysis band, errors, 95% upper limits, TS per bin, and FermiPy\'s variability TS for the whole curve), as saved.'}, 'band_flux': {'summary': 'Integrates the fitted spectral model over the band, with the error propagated from the fit\'s covariance.', 'detail': 'The flux in an energy band (the band flux): photon flux (cm⁻² s⁻¹) or energy flux (erg cm⁻² s⁻¹) between two energies, integrated from the task\'s fitted spectral model; its error is propagated from the fitted parameters\' covariance through a numerical Jacobian. Over the fitted range it matches FermiPy\'s own flux and error; outside it is an extrapolation, which the result says.'}, 'model_e2dnde': {'summary': 'Evaluates the fitted model\'s E² dN/dE at given energies, with errors from the covariance.', 'detail': 'The task\'s fitted spectral model at the energies asked for, its 1σ error propagated from the fit\'s covariance.'}, 'peak_energy': {'summary': 'Finds where the fitted model\'s E² dN/dE peaks inside the fitted range.', 'detail': 'The energy of the maximum of E² dN/dE of the task\'s fitted model, searched on a fine grid over the analysis range; none when the spectrum rises or falls throughout.'}, 'luminosity': {'summary': 'Turns an energy flux into an isotropic luminosity at a redshift (Planck 2018 cosmology).', 'detail': 'L = 4π d_L² F, with d_L from astropy\'s Planck18 cosmology and, when a photon index is given, the power-law K-correction (1+z)^(Γ−2). The redshift comes from the catalog, not the analysis.'}, 'fit_sed': {'summary': 'Fits a spectral shape to the SED bins\' likelihood scans (not a refit of the photons; the other sources stay as the SED left them).', 'detail': 'Uses what gta.sed() saved: in each energy bin FermiPy fitted only the target\'s normalization (an index-2 shape inside the bin, the other sources fixed at the global fit) and scanned the log-likelihood against it. For a trial spectrum the helper integrates dN/dE over each bin, divides by the bin\'s reference flux to get the normalization it implies, reads Δln L there from a cubic spline through that bin\'s scan and sums the bins; Nelder-Mead maximises the sum. Built-in shapes: power law, log-parabola, exponential cutoff, broken power law (normalization at the TS-weighted mean energy of the bins); a custom dN/dE can be given. Errors: the inverse Hessian of −ln L at the best fit. The log-likelihood shown is relative to each bin\'s best value, so 0 is the best any spectrum could do. Few or wide bins limit it, and the in-bin index-2 shape is an approximation; for a result to publish, FermiPy\'s own curvature test (gta.curvature(), a refit on the photons) can run as the next task.'}, 'compare_fits': {'summary': 'Compares fitted shapes: TS = 2 Δln L, the significance for a shape nested in the power law (Wilks), and the AIC.', 'detail': 'TS = 2 (ln L₂ − ln L₁) against the first fit. For a built-in shape that contains the power law (a log-parabola with β = 0, a cutoff at infinite energy, a broken power law with equal indices) Wilks\' theorem gives the significance: a χ² with the extra parameters as degrees of freedom, turned into a two-sided Gaussian σ. No significance for a custom shape, whose nesting is unknown. AIC = 2k − 2 ln L.'}, 'variability': {'summary': 'Tests the light curve for variability: χ² of the detected bins against a constant flux, the fractional variability F_var, and FermiPy\'s likelihood test for the whole curve.', 'detail': 'The χ² of the bins with TS ≥ 4 against their error-weighted mean flux and its p-value (and the equivalent σ); F_var after Vaughan et al. (2003) with its error; the brightest and faintest bins. FermiPy\'s likelihood variability TS (ts_var) is quoted only for the whole curve, since it was computed with every bin. A window (start, stop) restricts the bins tested.'}, 'lc_select': {'minor': True, 'summary': 'Keeps the light-curve bins inside a time window.', 'detail': 'The bins whose centre lies between the two times (MJD or dates).'}, 'bayesian_blocks': {'summary': 'Splits the light curve into Bayesian blocks of constant flux (Scargle et al. 2013).', 'detail': 'astropy\'s bayesian_blocks with the "measures" fitness on the detected bins (their fluxes and errors), with a false-alarm probability p0 (0.05 by default) per change point; each block\'s flux is the error-weighted mean of its bins.'}, 'blocks_curve': {'minor': True, 'summary': 'Turns blocks into a light curve for plotting.', 'detail': 'The blocks as bins of a light curve, so they can be drawn over the data.'}, 'doubling_times': {'summary': 'Finds flux doubling or halving times between consecutive detected bins that differ significantly.', 'detail': 'For consecutive bins with TS ≥ 4 whose fluxes differ by at least min_sigma (3 by default): τ = Δt ln 2 / |ln(F₂/F₁)|, Δt the time between the bin centres. Limited by the bin width.'}, 'mjd_to_date': {'minor': True, 'summary': 'Converts an MJD to a UTC date.', 'detail': 'An MJD as YYYY-MM-DD HH:MM (UTC).'}, 'fmt': {'minor': True, 'summary': 'Formats a number.', 'detail': 'A number to 3 significant digits.'}, 'table': {'minor': True, 'summary': 'Shows a table.', 'detail': 'Shows the rows as a table under the answer and prints them.'}, 'plot_sed': {'minor': True, 'summary': 'Draws an SED plot.', 'detail': 'Draws SEDs and fitted shapes on one plot under the answer, like the Outputs panel.'}, 'plot_lc': {'minor': True, 'summary': 'Draws a light-curve plot.', 'detail': 'Draws light curves (and blocks) on one plot under the answer, like the Outputs panel.'}, } def markdown(): """The helpers' methods as a page for the documentation index.""" lines = ['# How Discuss computes on the results', '', 'After a run, Discuss can compute numbers the run did not give (a flux in another band, ' 'another spectral shape, variability in a window, flare times, a comparison of tasks) by ' 'running a short Python snippet in the analysis sandbox on the results the tasks saved. ' 'The snippet uses Fermi-LLM\'s own helper module (results_helpers, written as rh), not ' 'FermiPy: none of these helpers refits the photons. What each one does:', ''] for name, m in METHODS.items(): if m.get('minor'): continue lines += [f'## rh.{name}', '', m['detail'], ''] return '\n'.join(lines).rstrip() + '\n' class HelperError(Exception): """A request the saved results cannot answer (said in plain words).""" class Result(dict): """A helper's result: a dict that prints short (numbers to 4 significant digits, curves and long lists summarised), so printing one gives the model the numbers and not the plot data.""" def __repr__(self): return '{' + ', '.join(f'{k!r}: {_short(v)}' for k, v in self.items()) + '}' __str__ = __repr__ def _short(v): if isinstance(v, dict): if 'e2dnde' in v and 'e' in v: return f"" return '{' + ', '.join(f'{k!r}: {_short(x)}' for k, x in v.items()) + '}' if isinstance(v, (list, tuple, np.ndarray)): if len(v) > 12: return f'<{len(v)} values>' inner = ', '.join(_short(x) for x in v) return f'({inner})' if isinstance(v, tuple) else f'[{inner}]' if isinstance(v, (float, np.floating)): return fmt(v, 4) return repr(v) class Curve(dict): """A model curve (energies and E^2 dN/dE) that prints as a summary.""" def __repr__(self): return f"" __str__ = __repr__ class Blocks(list): """Bayesian blocks that remember the light curve they were made from, so a plot of the blocks alone shows that curve under them.""" curve = None class _Shown: def __repr__(self): return '(shown on the page)' # ----------------------------------------------------------------- inputs def _load(inputs_path, out_path): with open(inputs_path) as f: _STATE['inputs'] = json.load(f) _STATE['out'] = out_path def _inputs(): if _STATE['inputs'] is None: raise HelperError('no results were given to this computation') return _STATE['inputs'] def tasks(): """The task ids that have results, oldest first.""" return [int(k) for k in sorted(_inputs()['tasks'], key=int)] def task(task_id=None): """A task's record: id, request, parent, status, fit, seds, lcs.""" inp = _inputs() tid = inp.get('followed') if task_id is None else task_id t = inp['tasks'].get(str(tid)) if t is None: raise HelperError(f'task {tid} has no results here (tasks with results: {tasks()})') return t def _walk(task_id, key): """The task's own item, else the nearest ancestor's (a follow-up that loaded a model inherits its fit and earlier products).""" seen, t = set(), task(task_id) while t is not None and t['id'] not in seen: seen.add(t['id']) if t.get(key): return t p = t.get('parent') t = _inputs()['tasks'].get(str(p)) if p is not None else None return None def fit(task_id=None): """The fitted spectrum of the target that a task's results rest on: {task, source, model, params (true units), errors, cov_names, cov, emin, emax, ts, flux}. A follow-up without its own fit gives the fit it loaded.""" t = _walk(task_id, 'fit') if t is None: raise HelperError('no fitted spectrum was saved for this task or the tasks it continues') return t['fit'] def sed(task_id=None, index=-1): """A task's SED (the last one it made by default), else the nearest ancestor's: e_min, e_max, e_ref, e2dnde, e2dnde_err, e2dnde_ul95, ts, norm_scan, dloglike_scan, ref_flux... (MeV, MeV cm-2 s-1).""" t = _walk(task_id, 'seds') if t is None: raise HelperError('no SED was computed in this task or the tasks it continues') s = dict(t['seds'][index]) s.setdefault('task', t['id']) return s _CATALOG_ALIASES = {'4fgl-dr4': '4fgl', '4fgldr4': '4fgl', 'dr4': '4fgl', 'fgl': '4fgl', '4fgldr3': '4fgl-dr3', 'dr3': '4fgl-dr3', '4lac-dr3': '4lac', '4lacdr3': '4lac', '5fgl': 'fl16y'} def catalog_sed(catalog='4fgl'): """The target's entry in a LAT catalog as an SED (the points the SED card draws): e_min, e_max, e_ctr, e2dnde, e2dnde_err, e2dnde_ul95, is_ul, ts, model (the catalog's spectral model), plus catalog, entry, span and label (MeV, MeV cm-2 s-1). ``catalog``: 4fgl (4FGL-DR4), fl16y, 4fgl-dr3, 4lac, 4fhl, 3fhl, 2fhl.""" cats = _inputs().get('catalogs') or {} key = str(catalog or '4fgl').strip().lower().replace(' ', '').replace('_', '-') key = _CATALOG_ALIASES.get(key, key) c = cats.get(key) if c is None: have = ', '.join(f"{k} ({v['name']})" for k, v in cats.items()) or 'none' raise HelperError(f'no {catalog} entry with band points for the target here ' f'(catalogs listing it: {have})') s = dict(c['sed']) s.update(catalog=c['name'], entry=c['entry'], span=c['span'], task=None, label=s.get('label') or f"{c['name']} ({c['span']})", basis=f"{c['name']} catalog entry {c['entry']}, data {c['span']}") return s def lc(task_id=None, index=-1): """A task's light curve, else the nearest ancestor's: tmin_mjd, tmax_mjd, flux, flux_err, flux_ul95, ts, ts_var (photon flux in the analysis band, cm-2 s-1).""" t = _walk(task_id, 'lcs') if t is None: raise HelperError('no light curve was computed in this task or the tasks it continues') s = dict(t['lcs'][index]) s.setdefault('task', t['id']) return s def _arr(values): return np.array([np.nan if v is None else v for v in (values or [])], dtype=float) # ----------------------------------------------------------- spectral shapes def _dnde(model, p, e): """dN/dE (cm-2 s-1 MeV-1) of a Fermi-tools spectral model with its parameters in true units (FermiPy's value x scale), E in MeV.""" e = np.asarray(e, dtype=float) if model == 'PowerLaw': return p['Prefactor'] * (e / p['Scale']) ** p['Index'] if model == 'PowerLaw2': g = p['Index'] lo, hi = p['LowerLimit'], p['UpperLimit'] if abs(g + 1.0) < 1e-9: return p['Integral'] / (e * math.log(hi / lo)) return p['Integral'] * (g + 1.0) * e ** g / (hi ** (g + 1.0) - lo ** (g + 1.0)) if model == 'LogParabola': x = e / p['Eb'] return p['norm'] * x ** (-(p['alpha'] + p['beta'] * np.log(x))) if model == 'PLExpCutoff': out = p['Prefactor'] * (e / p['Scale']) ** p['Index'] return np.where(e > p['Ebreak'], out * np.exp(-(e - p['Ebreak']) / p['P1']), out) if model == 'PLSuperExpCutoff': return p['Prefactor'] * (e / p['Scale']) ** p['Index1'] * np.exp(-(e / p['Cutoff']) ** p['Index2']) if model == 'PLSuperExpCutoff2': return (p['Prefactor'] * (e / p['Scale']) ** p['Index1'] * np.exp(p['Expfactor'] * (p['Scale'] ** p['Index2'] - e ** p['Index2']))) if model == 'PLSuperExpCutoff4': # K (E/E0)^(IndexS + d/b) exp[(d/b^2)(1 - (E/E0)^b)], in log form: # ln K + IndexS L - d (e^(bL) - 1 - bL) / b^2 with L = ln(E/E0), # stable for any b and going to the b -> 0 form K (E/E0)^(IndexS - d L / 2). lx = np.log(e / p['Scale']) b, d = p['Index2'], p['ExpfactorS'] y = b * lx f = np.where(np.abs(y) < 1e-3, y * y / 2 + y ** 3 / 6 + y ** 4 / 24, np.expm1(y) - y) g = lx * lx / 2 if b == 0 else f / (b * b) return p['Prefactor'] * np.exp(p['IndexS'] * lx - d * g) if model == 'BrokenPowerLaw': x = e / p['BreakValue'] return p['Prefactor'] * np.where(x < 1.0, x ** p['Index1'], x ** p['Index2']) raise HelperError(f'the {model} spectral model is not supported by these helpers') def _grid(emin, emax, n=256): return np.logspace(math.log10(emin), math.log10(emax), n) def _integral(f, emin, emax, energy): e = _grid(emin, emax) y = f(e) * e * (e if energy else 1.0) # d/dlnE return float(np.trapz(y, np.log(e))) def _propagate(func, f): """value and 1-sigma error of func(params) from the fit's covariance (a numerical Jacobian over the fitted parameters).""" p = dict(f['params']) value = func(p) names, cov = f.get('cov_names') or [], f.get('cov') note = None if not names or cov is None: errs = {k: v for k, v in (f.get('errors') or {}).items() if v is not None and np.isfinite(v)} names = list(errs) cov = np.diag([errs[k] ** 2 for k in names]) if names else None note = 'no covariance was saved: the error ignores the correlations between the parameters' if not names: return value, None, 'no parameter errors were saved' cov = np.asarray(cov, dtype=float) jac = [] for k in names: h = 1e-5 * abs(p[k]) or 1e-8 q = dict(p) q[k] = p[k] + h up = func(q) q[k] = p[k] - h jac.append((up - func(q)) / (2 * h)) jac = np.array(jac) var = float(jac @ cov @ jac) return value, (math.sqrt(var) if var >= 0 and np.isfinite(var) else None), note def band_flux(emin, emax, task_id=None, energy=False): """The target's flux between emin and emax (MeV) from the fitted spectral model, with its 1-sigma error from the fit's covariance: photon flux (cm-2 s-1), or with energy=True the energy flux (erg cm-2 s-1, with value_mev in MeV cm-2 s-1). Outside the fitted energy range it is an extrapolation, which the result says.""" f = fit(task_id) if not (emax > emin > 0): raise HelperError('the band needs 0 < emin < emax, in MeV') model = f['model'] value, err, note = _propagate(lambda p: _integral(lambda e: _dnde(model, p, e), emin, emax, energy), f) out = Result({'emin': float(emin), 'emax': float(emax), 'task': f['task'], 'source': f['source'], 'model': model, 'value': value, 'error': err, 'unit': 'MeV cm-2 s-1' if energy else 'cm-2 s-1', 'basis': f"task {f['task']}'s fitted spectral model and its covariance" + (f' ({note})' if note else '')}) if energy: # Energy fluxes are quoted in erg; the MeV value stays alongside. out.update(value_mev=value, error_mev=err, value=value * MEV_TO_ERG, error=err * MEV_TO_ERG if err is not None else None, unit='erg cm-2 s-1') lo, hi = f.get('emin'), f.get('emax') if lo and hi and (emin < lo * 0.999 or emax > hi * 1.001): out['extrapolated'] = f'outside the fitted range {lo:g}-{hi:g} MeV' return out def model_e2dnde(energies, task_id=None): """E^2 dN/dE (MeV cm-2 s-1) of the fitted model at the given energies (MeV), with 1-sigma errors: [(E, value, error)].""" f = fit(task_id) out = [] for e in np.atleast_1d(np.asarray(energies, dtype=float)): v, err, _note = _propagate(lambda p, e=e: float(_dnde(f['model'], p, e) * e * e), f) out.append((float(e), v, err)) return out def peak_energy(task_id=None): """Where the fitted model's E^2 dN/dE peaks inside the fitted range (MeV), or None when it rises or falls throughout.""" f = fit(task_id) e = _grid(f['emin'], f['emax'], 512) y = _dnde(f['model'], f['params'], e) * e * e i = int(np.nanargmax(y)) if i in (0, len(e) - 1): return None return float(e[i]) def luminosity(eflux_erg, z, emin=None, emax=None, index=None): """Isotropic luminosity (erg s-1) from an energy flux (erg cm-2 s-1) at redshift z (Planck 2018 cosmology), with the K-correction of a power law of photon index ``index`` (Gamma, positive) when given: L = 4 pi d_L^2 F (1+z)^(Gamma-2).""" from astropy.cosmology import Planck18 d_l = Planck18.luminosity_distance(z).to('cm').value k = (1.0 + z) ** (index - 2.0) if index is not None else 1.0 return float(4.0 * math.pi * d_l ** 2 * eflux_erg * k) # -------------------------------------------------------------- SED fitting SHAPES = ('powerlaw', 'logparabola', 'plexpcutoff', 'broken_powerlaw') def _shape_dnde(shape, q, e, e0): n0 = 10.0 ** q[0] x = e / e0 if shape == 'powerlaw': return n0 * x ** (-q[1]) if shape == 'logparabola': return n0 * x ** (-(q[1] + q[2] * np.log(x))) if shape == 'plexpcutoff': return n0 * x ** (-q[1]) * np.exp(-e / (10.0 ** q[2])) if shape == 'broken_powerlaw': eb = 10.0 ** q[3] xb = e / eb return n0 * (eb / e0) ** (-q[1]) * np.where(xb < 1.0, xb ** (-q[1]), xb ** (-q[2])) raise HelperError(f'unknown shape {shape!r}; use one of {", ".join(SHAPES)}') _SHAPE_NAMES = {'powerlaw': ['log10_N0', 'Gamma'], 'logparabola': ['log10_N0', 'alpha', 'beta'], 'plexpcutoff': ['log10_N0', 'Gamma', 'log10_Ecut_MeV'], 'broken_powerlaw': ['log10_N0', 'Gamma1', 'Gamma2', 'log10_Ebreak_MeV']} def _bin_loglike(s): """Per bin, a function norm -> delta log-likelihood from the scan: a cubic spline through the scan (smooth, so the curvature that gives the errors is meaningful), extended at the edges along its end slope (never rising past the last point).""" from scipy.interpolate import CubicSpline scans = [] for ns, dl in zip(s.get('norm_scan') or [], s.get('dloglike_scan') or []): x, y = _arr(ns), _arr(dl) ok = np.isfinite(x) & np.isfinite(y) x, y = x[ok], y[ok] if len(x) < 4: scans.append(None) continue order = np.argsort(x) x, y = x[order], y[order] keep = np.concatenate([[True], np.diff(x) > 0]) x, y = x[keep], y[keep] if len(x) < 4: scans.append(None) continue spl = CubicSpline(x, y, bc_type='natural') scans.append((x, y, spl, float(spl(x[0], 1)), min(float(spl(x[-1], 1)), 0.0))) def one(i, norm): sc = scans[i] if sc is None: return 0.0 x, y, spl, d0, d1 = sc if norm <= x[0]: return float(y[0] + d0 * (norm - x[0])) if norm >= x[-1]: return float(y[-1] + d1 * (norm - x[-1])) return float(spl(norm)) return scans, one def fit_sed(shape, task_id=None, sed_data=None, start=None, names=None, label=None): """Fit a spectral shape to an SED's per-bin likelihood profiles (the FermiPy SED's norm scans). ``shape`` is one of SHAPES (powerlaw, logparabola, plexpcutoff: an exponential cutoff, broken_powerlaw) or your own dN/dE: a function f(E, p1, p2, ...) of the energy in MeV returning cm-2 s-1 MeV-1, with ``start`` its starting values (a list, or a dict whose keys name the parameters; ``names`` otherwise) and ``label`` its name. Close to a likelihood fit of the data in those bins, but the other sources stay as the SED left them. Returns {shape, model (the shape's name), params {name: (value, error)}, loglike, npar, e0, basis, curve (for plot_sed)}; compare shapes with compare_fits. Without scans, a chi-square fit to the points.""" from scipy.optimize import minimize custom = callable(shape) if not custom and shape not in SHAPES: raise HelperError(f'unknown shape {shape!r}; use one of {", ".join(SHAPES)} or your own ' f'function f(E, *params) with start=[...]') s = sed_data or sed(task_id) e_min, e_max = _arr(s['e_min']), _arr(s['e_max']) e_ref = _arr(s.get('e_ref') or s.get('e_ctr')) ref_flux = _arr(s.get('ref_flux')) ts = _arr(s.get('ts')) # The pivot where the data weigh most (TS-weighted mean log energy), so # the normalization and the index are nearly uncorrelated. w = np.clip(np.nan_to_num(ts), 0, None) e0 = float(np.exp(np.sum(w * np.log(e_ref)) / np.sum(w))) if w.sum() > 0 \ else float(np.sqrt(e_min[0] * e_max[-1])) scans, one = _bin_loglike(s) use_scan = bool(scans) and any(sc is not None for sc in scans) and len(ref_flux) == len(e_min) y, yerr = _arr(s.get('e2dnde')), _arr(s.get('e2dnde_err')) good = np.isfinite(y) & (y > 0) if not good.any(): raise HelperError('the SED has no positive points') if custom: # Your function, in its own parameters, fitted in units of the start # values (so a 1e-10 normalization and an index of 2 move alike). if start is None: raise HelperError('a custom shape needs starting values: fit_sed(f, start=[...])') if isinstance(start, dict): names = list(start) start = list(start.values()) start = [float(v) for v in start] names = list(names or [f'p{i + 1}' for i in range(len(start))]) if len(names) != len(start): raise HelperError('names and start values differ in number') scale = np.array([abs(v) if v else 1.0 for v in start]) x0 = list(np.array(start) / scale) fname = label or getattr(shape, '__name__', '') or 'custom' fname = 'custom' if fname == '' else fname def dnde(q, e): return np.asarray(shape(e, *(np.asarray(q) * scale)), dtype=float) else: scale = None names = _SHAPE_NAMES[shape] fname = shape k = int(np.nanargmax(np.where(good, y, -np.inf))) n0 = y[k] / e_ref[k] ** 2 * (e_ref[k] / e0) ** 2.0 x0 = {'powerlaw': [math.log10(n0), 2.0], 'logparabola': [math.log10(n0), 2.0, 0.05], 'plexpcutoff': [math.log10(n0), 1.8, math.log10(max(e0 * 4, e_ref[-1] / 4))], 'broken_powerlaw': [math.log10(n0), 1.8, 2.5, math.log10(e0)]}[shape] def dnde(q, e): return _shape_dnde(shape, q, e, e0) def bin_flux(q, i): e = _grid(e_min[i], e_max[i], 24) return float(np.trapz(dnde(q, e) * e, np.log(e))) if use_scan: def nll(q): try: with np.errstate(all='ignore'): v = -sum(one(i, bin_flux(q, i) / ref_flux[i]) for i in range(len(e_min))) return v if np.isfinite(v) else 1e30 except (FloatingPointError, OverflowError, ValueError, ZeroDivisionError): return 1e30 basis = 'the SED bins\' likelihood profiles (norm scans)' else: det = np.isfinite(y) & np.isfinite(yerr) & (yerr > 0) & (np.nan_to_num(ts) >= 4) if det.sum() < len(names) + 1: raise HelperError('too few detected SED points for this fit') def nll(q): with np.errstate(all='ignore'): m = dnde(q, e_ref[det]) * e_ref[det] ** 2 v = 0.5 * float(np.sum(((y[det] - m) / yerr[det]) ** 2)) return v if np.isfinite(v) else 1e30 basis = 'a chi-square fit to the detected SED points (no likelihood profiles were saved)' if nll(np.array(x0, dtype=float)) >= 1e30: raise HelperError('the shape gives no finite flux at the starting values: check the ' 'function and its start values') with np.errstate(all='ignore'): r = minimize(nll, x0, method='Nelder-Mead', options={'maxiter': 8000, 'xatol': 1e-6, 'fatol': 1e-7}) r = minimize(nll, r.x, method='Nelder-Mead', options={'maxiter': 8000, 'xatol': 1e-7, 'fatol': 1e-8}) q = np.array(r.x, dtype=float) errs = _hessian_errors(nll, q) if scale is not None: values = q * scale errs = [None if e is None else float(e * sc) for e, sc in zip(errs, scale)] else: values = q params = {n: (float(v), errs[i]) for i, (n, v) in enumerate(zip(names, values))} ecurve = _grid(e_min[0], e_max[-1], 80) with np.errstate(all='ignore'): curve = dnde(q, ecurve) * ecurve ** 2 out = Result({'shape': fname, 'model': fname, 'custom': custom, 'params': params, 'loglike': -float(r.fun), 'npar': len(q), 'e0': e0, 'converged': bool(r.success), 'basis': basis, 'task': s.get('task'), 'curve': Curve(e=ecurve.tolist(), e2dnde=[_clean(float(v)) for v in curve])}) if any(err is None for err in errs): out['note'] = ('some errors could not be computed: the likelihood is flat or the fit sits ' 'at an edge in those directions, so those parameters are not constrained') return out def _hessian_errors(f, q): """1-sigma errors from the curvature of the negative log-likelihood f at its minimum q. Each step is sized so f rises by about 0.5 (the 1-sigma scale), which keeps the differences out of rounding noise and off the spline's knots.""" n = len(q) f0 = f(q) h = np.empty(n) for i in range(n): step = 0.05 * max(abs(q[i]), 0.1) for _ in range(30): qq = q.copy() qq[i] += step rise = f(qq) - f0 if rise > 2.0: step /= 2 elif rise < 0.1: step *= 2 else: break h[i] = step hess = np.zeros((n, n)) for i in range(n): for j in range(i, n): if i == j: qp, qm = q.copy(), q.copy() qp[i] += h[i] qm[i] -= h[i] hess[i, i] = (f(qp) - 2 * f0 + f(qm)) / h[i] ** 2 else: vals = [] for si, sj in ((1, 1), (1, -1), (-1, 1), (-1, -1)): qq = q.copy() qq[i] += si * h[i] qq[j] += sj * h[j] vals.append(f(qq)) hess[i, j] = hess[j, i] = (vals[0] - vals[1] - vals[2] + vals[3]) / (4 * h[i] * h[j]) try: cov = np.linalg.inv(hess) return [float(math.sqrt(cov[i, i])) if cov[i, i] > 0 else None for i in range(n)] except np.linalg.LinAlgError: return [None] * n def compare_fits(*fits): """Rows comparing fit_sed results: shape, log-likelihood, number of parameters, TS = 2 dlnL against the first fit, its significance when the first is nested in the other (a power law in a log-parabola, a cutoff or a broken power law: Wilks, with the extra parameters as the degrees of freedom) and the AIC.""" from scipy import stats base = fits[0] rows = [] for f in fits: ts = 2 * (f['loglike'] - base['loglike']) extra = f['npar'] - base['npar'] sig = None # Wilks applies to a built-in shape against the power law it contains; # a custom shape may not contain it, so no significance is claimed. if f is not base and extra > 0 and base['shape'] == 'powerlaw' and not f.get('custom'): p = float(stats.chi2.sf(max(ts, 0.0), extra)) sig = float(stats.norm.isf(p / 2)) if 0 < p < 1 else (0.0 if p >= 1 else None) rows.append(Result({'shape': f['shape'], 'loglike': round(f['loglike'], 2), 'npar': f['npar'], 'TS_vs_' + base['shape']: round(ts, 2), 'sigma_vs_' + base['shape']: None if sig is None else round(sig, 2), 'AIC': round(2 * f['npar'] - 2 * f['loglike'], 2)})) return rows # ------------------------------------------------------------ light curves def _to_mjd(t): if t is None: return None if isinstance(t, (int, float, np.floating, np.integer)): return float(t) from astropy.time import Time return float(Time(str(t), scale='utc').mjd) def mjd_to_date(mjd): """An MJD as 'YYYY-MM-DD HH:MM' (UTC).""" from astropy.time import Time return Time(float(mjd), format='mjd', scale='utc').strftime('%Y-%m-%d %H:%M') def lc_select(curve, start=None, stop=None): """The bins of a light curve whose centre lies between start and stop (MJD numbers or dates like '2024-03-01').""" a, b = _to_mjd(start), _to_mjd(stop) t0, t1 = _arr(curve['tmin_mjd']), _arr(curve['tmax_mjd']) mid = (t0 + t1) / 2 keep = np.ones(len(mid), bool) if a is not None: keep &= mid >= a if b is not None: keep &= mid <= b out = {k: ([v[i] for i in range(len(v)) if keep[i]] if isinstance(v, list) and len(v) == len(mid) else v) for k, v in curve.items()} out['ts_var'] = None # FermiPy's test applies to the whole curve only return out def variability(curve, start=None, stop=None): """Variability of a light curve (optionally only the bins between start and stop): the chi-square of the detected bins (TS >= 4) against their weighted mean and its p-value, the fractional variability F_var (Vaughan et al. 2003) with its error, and the brightest and faintest bins. FermiPy's likelihood test (ts_var) is quoted for the whole curve only, since it was computed with every bin.""" from scipy import stats whole = start is None and stop is None c = curve if whole else lc_select(curve, start, stop) f, e, ts = _arr(c['flux']), _arr(c['flux_err']), _arr(c['ts']) t0, t1 = _arr(c['tmin_mjd']), _arr(c['tmax_mjd']) det = np.isfinite(f) & np.isfinite(e) & (e > 0) & (np.nan_to_num(ts) >= 4) out = Result({'bins': int(len(f)), 'detected': int(det.sum()), 'from': mjd_to_date(t0.min()) if len(t0) else None, 'to': mjd_to_date(t1.max()) if len(t1) else None, 'basis': 'the light-curve bins (fluxes and errors as saved)'}) if det.sum() >= 2: w = 1.0 / e[det] ** 2 mean = float(np.sum(w * f[det]) / np.sum(w)) chi2 = float(np.sum(((f[det] - mean) / e[det]) ** 2)) dof = int(det.sum() - 1) p = float(stats.chi2.sf(chi2, dof)) out.update(weighted_mean=mean, chi2=chi2, dof=dof, p_value=p, sigma=float(stats.norm.isf(p / 2)) if p > 0 else None) x, err = f[det], e[det] s2 = float(np.var(x, ddof=1)) excess = s2 - float(np.mean(err ** 2)) xm = float(np.mean(x)) if excess > 0 and xm > 0: fvar = math.sqrt(excess) / xm n = len(x) ferr = math.sqrt((math.sqrt(1.0 / (2 * n)) * np.mean(err ** 2) / (xm ** 2 * fvar)) ** 2 + (math.sqrt(np.mean(err ** 2) / n) / xm) ** 2) out.update(fvar=fvar, fvar_err=ferr) else: out.update(fvar=None, fvar_note='F_var is undefined: the scatter of the fluxes is ' 'no larger than their errors (no excess variance)') i, j = int(np.argmax(np.where(det, f, -np.inf))), int(np.argmin(np.where(det, f, np.inf))) out['brightest'] = {'from': mjd_to_date(t0[i]), 'to': mjd_to_date(t1[i]), 'flux': float(f[i]), 'flux_err': float(e[i])} out['faintest'] = {'from': mjd_to_date(t0[j]), 'to': mjd_to_date(t1[j]), 'flux': float(f[j]), 'flux_err': float(e[j])} if whole and c.get('ts_var') is not None and len(f) > 1: out['ts_var'] = float(c['ts_var']) out['ts_var_p'] = float(stats.chi2.sf(c['ts_var'], len(f) - 1)) return out def bayesian_blocks(curve, p0=0.05): """Bayesian blocks (Scargle et al. 2013) on the detected bins of a light curve: [{from, to, from_mjd, to_mjd, flux, bins}], one per block, with the false-alarm probability p0 per change point.""" from astropy.stats import bayesian_blocks as bb f, e, ts = _arr(curve['flux']), _arr(curve['flux_err']), _arr(curve['ts']) t0, t1 = _arr(curve['tmin_mjd']), _arr(curve['tmax_mjd']) det = np.isfinite(f) & np.isfinite(e) & (e > 0) & (np.nan_to_num(ts) >= 4) if det.sum() < 3: raise HelperError('Bayesian blocks need at least 3 detected bins') mid = (t0 + t1)[det] / 2 edges = bb(mid, f[det], e[det], fitness='measures', p0=p0) blocks = Blocks() blocks.curve = curve for a, b in zip(edges[:-1], edges[1:]): inb = (mid >= a) & (mid <= b) if not inb.any(): continue w = 1.0 / e[det][inb] ** 2 idx = np.where(det)[0][inb] blocks.append(Result({'from': mjd_to_date(t0[idx].min()), 'to': mjd_to_date(t1[idx].max()), 'from_mjd': float(t0[idx].min()), 'to_mjd': float(t1[idx].max()), 'flux': float(np.sum(w * f[det][inb]) / np.sum(w)), 'flux_err': float(1.0 / math.sqrt(np.sum(w))), 'bins': int(inb.sum())})) return blocks def blocks_curve(blocks, name='Bayesian blocks'): """Blocks from bayesian_blocks as a light curve for plot_lc.""" return {'name': name, 'of': getattr(blocks, 'curve', None), 'tmin_mjd': [b['from_mjd'] for b in blocks], 'tmax_mjd': [b['to_mjd'] for b in blocks], 'flux': [b['flux'] for b in blocks], 'flux_err': [b['flux_err'] for b in blocks], 'ts': [25.0] * len(blocks)} def doubling_times(curve, min_sigma=3.0): """Flux doubling or halving times between consecutive detected bins whose fluxes differ by at least min_sigma: [{from, to, tau_days, rising, sigma}], shortest first. tau = dt ln2 / |ln(F2/F1)|, dt the time between the bin centres.""" f, e, ts = _arr(curve['flux']), _arr(curve['flux_err']), _arr(curve['ts']) t0, t1 = _arr(curve['tmin_mjd']), _arr(curve['tmax_mjd']) det = np.where(np.isfinite(f) & np.isfinite(e) & (e > 0) & (np.nan_to_num(ts) >= 4) & (f > 0))[0] out = [] for a, b in zip(det[:-1], det[1:]): sig = abs(f[b] - f[a]) / math.sqrt(e[a] ** 2 + e[b] ** 2) if sig < min_sigma: continue dt = (t0[b] + t1[b]) / 2 - (t0[a] + t1[a]) / 2 tau = dt * math.log(2) / abs(math.log(f[b] / f[a])) out.append(Result({'from': mjd_to_date((t0[a] + t1[a]) / 2), 'to': mjd_to_date((t0[b] + t1[b]) / 2), 'tau_days': float(tau), 'rising': bool(f[b] > f[a]), 'sigma': float(sig)})) return sorted(out, key=lambda x: x['tau_days']) # ----------------------------------------------------- output for the page def _record(rec): if _STATE['out'] is None: _draw_here(rec) # in a notebook: matplotlib return if _STATE['records'] >= MAX_RECORDS: print(f'[not shown: at most {MAX_RECORDS} tables and plots per computation]') return _STATE['records'] += 1 with open(_STATE['out'], 'a') as f: f.write(json.dumps(rec, default=_json_default) + '\n') def _draw_here(rec): """Outside the app (the notebook download): draw a recorded plot with matplotlib; tables were printed already.""" if rec.get('type') not in ('sed', 'lightcurve'): return import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(6.4, 4.2) if rec['type'] == 'sed' else (7.2, 3.8)) for i, sr in enumerate(rec['series']): d = sr.get('sed') if rec['type'] == 'sed' else sr.get('lc') d = d or {} color = f'C{i}' if rec['type'] == 'sed': x, y, err = _arr(d.get('e_ctr')), _arr(d.get('e2dnde')), _arr(d.get('e2dnde_err')) ul = np.array(d.get('is_ul') or [False] * len(x), bool) if len(x): ax.errorbar(x[~ul] / 1e3, y[~ul], yerr=err[~ul], fmt='o', ms=4, color=color, label=sr.get('label')) u = _arr(d.get('e2dnde_ul95')) if ul.any() and len(u): ax.errorbar(x[ul] / 1e3, u[ul], yerr=0.35 * u[ul], uplims=True, fmt='none', color=color) m = d.get('model') or {} if m.get('e'): ax.plot(_arr(m['e']) / 1e3, _arr(m['e2dnde']), color=color, lw=1.4, label=None if len(x) else sr.get('label')) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel('Energy [GeV]') ax.set_ylabel('E$^2$ dN/dE [MeV cm$^{-2}$ s$^{-1}$]') else: t0, t1 = _arr(d.get('tmin_mjd')), _arr(d.get('tmax_mjd')) f, e = _arr(d.get('flux')), _arr(d.get('flux_err')) ul = np.array(d.get('is_ul') or [False] * len(f), bool) ax.errorbar(((t0 + t1) / 2)[~ul], f[~ul], xerr=((t1 - t0) / 2)[~ul], yerr=e[~ul], fmt='o', ms=4, color=color, label=sr.get('label')) u = _arr(d.get('flux_ul95')) if ul.any() and len(u): ax.errorbar(((t0 + t1) / 2)[ul], u[ul], xerr=((t1 - t0) / 2)[ul], yerr=0.25 * u[ul], uplims=True, fmt='none', color=color) ax.set_xlabel('MJD') ax.set_ylabel('Flux [ph cm$^{-2}$ s$^{-1}$]') if rec.get('title'): ax.set_title(rec['title']) if ax.get_legend_handles_labels()[0]: ax.legend(frameon=False, fontsize=9) plt.show() def _json_default(v): if isinstance(v, (np.floating,)): return float(v) if isinstance(v, (np.integer,)): return int(v) if isinstance(v, np.ndarray): return v.tolist() return str(v) def _clean(v): if isinstance(v, float) and not math.isfinite(v): return None if isinstance(v, (np.floating, np.integer)): return _clean(v.item()) return v def fmt(v, digits=3): """A number with ``digits`` significant digits (None as '-').""" if v is None: return '-' if isinstance(v, (int, np.integer)) and not isinstance(v, bool): return str(v) if isinstance(v, (float, np.floating)): if not math.isfinite(v): return '-' return f'{v:.{digits}g}' return str(v) def _cell(v): """A table cell: numbers and text as they are, anything else short.""" v = _clean(v) if v is None or isinstance(v, (bool, int, float, str)): return v if isinstance(v, dict) and 'e2dnde' in v: return 'model curve' return _short(v) def table(rows, columns=None, title=None): """Show a table on the page and print it for the model: rows as dicts (columns from the first row unless given) or lists.""" rows = list(rows)[:MAX_TABLE_ROWS] if rows and isinstance(rows[0], dict): columns = columns or list(rows[0]) data = [[_cell(r.get(c)) for c in columns] for r in rows] else: data = [[_cell(x) for x in r] for r in rows] columns = columns or [f'col{i + 1}' for i in range(len(data[0]) if data else 0)] if title: print(title) print(' | '.join(str(c) for c in columns)) for r in data: print(' | '.join(fmt(x) for x in r)) _record({'type': 'table', 'title': title, 'columns': [str(c) for c in columns], 'rows': data}) return _Shown() def _sed_series(item, label=None): if 'shape' in item and 'curve' in item: # a fit_sed result return {'label': label or f"{item['shape']} fit", 'sed': { 'name': label or item['shape'], 'e_ctr': [], 'e_min': [], 'e_max': [], 'e2dnde': [], 'e2dnde_err': [], 'e2dnde_ul95': [], 'ts': [], 'is_ul': [], 'model': item['curve']}} ts = _arr(item.get('ts')) return {'label': label or item.get('label') or f"task {item.get('task')} SED", 'sed': { 'name': item.get('name'), 'e_ctr': item.get('e_ctr') or item.get('e_ref'), 'e_min': item.get('e_min'), 'e_max': item.get('e_max'), 'e2dnde': item.get('e2dnde'), 'e2dnde_err': item.get('e2dnde_err'), 'e2dnde_ul95': item.get('e2dnde_ul95'), 'ts': item.get('ts'), # A catalog entry says which bands are limits (no lower error); an # analysis SED's limits are its bins with TS < 4. 'is_ul': (list(item['is_ul']) if item.get('is_ul') is not None else [bool(not np.isfinite(t) or t < 4) for t in ts]), 'model': item.get('model')}} def _flat(items): """Items given one by one or as lists, as one list of dicts.""" out = [] for it in items: if isinstance(it, (list, tuple)): out.extend(_flat(it)) elif isinstance(it, dict): out.append(it) else: raise HelperError(f'cannot plot a {type(it).__name__}: pass SEDs, fits or light curves') return out def plot_sed(*items, labels=None, title=None, fits=None, task_id=None): """Show an SED plot on the page: SEDs (from rh.sed) and fits (from rh.fit_sed) overlaid, each with an optional label.""" labels = list(labels or []) items = _flat(list(items) + list(fits or [])) if items and all('shape' in it for it in items): # Fits alone: the SED they were fitted to goes under them. items.insert(0, sed(task_id if task_id is not None else items[0].get('task'))) if labels and len(labels) < len(items): # labels for the fits only labels.insert(0, None) series = [_sed_series(it, labels[i] if i < len(labels) else None) for i, it in enumerate(items)] print(f"[SED plot shown: {title or ', '.join(s['label'] for s in series)}]") _record({'type': 'sed', 'title': title, 'series': series}) return _Shown() def plot_lc(*curves, labels=None, title=None): """Show a light-curve plot on the page: curves from rh.lc, rh.lc_select or rh.blocks_curve, overlaid.""" labels = list(labels or []) series = [] flat = [] for c in curves: if isinstance(c, (list, tuple)) and c and all(isinstance(b, dict) and 'from_mjd' in b for b in c): flat.append(blocks_curve(c)) # bayesian_blocks() output (keeps its curve) else: flat.extend(_flat([c])) curves = flat if curves and all(c.get('of') for c in curves): # Blocks alone: the light curve they were made from goes under them. curves.insert(0, curves[0]['of']) if labels and len(labels) < len(curves): labels.insert(0, None) for i, c in enumerate(curves): ts = _arr(c.get('ts')) lab = ((labels[i] if i < len(labels) else None) or c.get('label') or c.get('name') or f"task {c.get('task')} light curve") series.append({'label': lab, 'lc': { 'name': c.get('name'), 'tmin_mjd': c.get('tmin_mjd'), 'tmax_mjd': c.get('tmax_mjd'), 'flux': c.get('flux'), 'flux_err': c.get('flux_err'), 'flux_ul95': c.get('flux_ul95'), 'ts': c.get('ts'), 'is_ul': [bool(not np.isfinite(t) or t < 4) for t in ts]}}) print(f"[light-curve plot shown: {title or ', '.join(s['label'] for s in series)}]") _record({'type': 'lightcurve', 'title': title, 'series': series}) return _Shown() if __name__ == '__main__': import sys if '--markdown' in sys.argv: sys.stdout.write(markdown())