Fermi-LLM

Documentation

← Back to app

Computations on the results

A run gives the products it was asked for. To go further, such as a number the run did not print, the SED against a catalog, or two tasks side by side, there are three ways, and not all of them need a new run. This page compares them, then lists the helpers Discuss computes with, Fermi-LLM's own code, with their source.

Three ways to get a result

A new task (Draft)The Outputs panel and CompareDiscuss computations
What runsFermiPy on the photons: a full run of a reviewed scriptNothing: the app draws what the tasks savedA short Python snippet the model writes, with the helpers below
What it readsThe data and everything FermiPy hasThe tasks' saved products and the catalogs' entriesThe tasks' saved fits, SEDs and light curves, and the target's catalog entries
What you getThe products drawn in Outputs, the script's own filesPlots you can restyle and save (Customize and save)Numbers, tables and plots under the answer; Keep files one with its task
How longMinutes to hoursAt onceSeconds

How the plots look is part of the request. Say how you want them and the app draws it, with no code in the script: catalog points beside the SED ("…and overlay the 4FGL-DR4 band points") or the light curve (the catalog's yearly fluxes), another catalog's sources marked on the maps ("mark the 3FHL sources on the TS map"), the SED's energies in GeV or TeV and E² dN/dE in erg cm⁻² s⁻¹, the light curve against calendar dates, a colour map, a title. Catalog points come with the catalog's spectral model and the time its data span, and a switch over the catalogs that list the target. The task report shows the same. Without such a request each plot is the app's default. The settings belong to the task that asked for them: a follow-up gets the default plots unless it asks for the earlier ones ("same plot settings as before", "plots like task 0").

Compare overlays the SEDs and light curves of several tasks, sessions and catalog entries at any time. Add to the task's results saves what it shows (the overlays and the fit numbers) under a task of the session, in its outputs and its report.

Which to use

  • A number from results you have, such as a flux in another band, a log-parabola against a power law, variability in a window, or flare times: ask Discuss.
  • A plot against a catalog or another task: ask for the catalog points in the request, or open Compare afterwards. The app draws these plots, so no code is written and no unit conversion can slip.
  • Anything that needs the photons, such as a refit with other sources free, other bins, another time or energy range, or a TS at a new position: a new task, drafted in Draft (or sent by Discuss's Draft button).

For a plot no setting gives, such as two of the script's own SEDs on one plot, a quantity against energy or time, or a histogram, the script hands the data to the app's plotting module, fermillm_plots (sed_plot, lc_plot, xy_plot, hist_plot, table). The Outputs panel draws it under "Plots made by the script", with hover, zoom and Customize and save. Only a plot none of these fits is a matplotlib image, shown as the script's own. Only the review model checks the code that prepares the data.

Your own code. In Draft you can edit the script in the Python panel: it goes through the same review and runs in the same sandbox. In Discuss the model writes a new snippet for each question, using the fixed helpers below. For a spectral shape of your own, give its formula and rh.fit_sed fits it. Snippets are never added to the helpers, so no one's code runs in another person's session.

How Discuss computes

When you ask Discuss for such a number, the model writes a short Python snippet that calls these helpers (as rh). The app runs it in a sandbox and the model answers from what it printed. Under the answer you see the result, a How this was computed line, and the code. Keep files a result with its task, in the Outputs panel and the notebook.

The snippet reads only what the tasks saved: each task's fitted model with its covariance, its SED with each bin's likelihood scan, and its light curves. It also reads the target's catalog entries, the points the SED card draws. It runs with numpy, scipy and parts of astropy, without files or network, for about 30 seconds at most.

Nothing here goes back to the photons. A refit, a TS or upper limit at a new position, other bins, or another time or energy range needs the counts and the likelihood. Discuss says so and offers it as the next task.

results_helpers.py · 22 helpers, 20 private functions, 983 lines View the full module

Reading the results

What a task saved, and the target's catalog entries, as the helpers hand them to the computation.

rh.fit(task_id=None)

Reads the target's fitted spectrum as the task's likelihood fit saved it.

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<id>.npy). A follow-up that only loaded a model gives the fit of the task it continues from.

AskWhat are the fitted parameters of the target, with their errors?
Sourceresults_helpers.py, line 187
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']

Private functions it calls (2)

_walkresults_helpers.py, line 174
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
_inputsresults_helpers.py, line 153
def _inputs():
    if _STATE['inputs'] is None:
        raise HelperError('no results were given to this computation')
    return _STATE['inputs']

rh.sed(task_id=None, index=-1)

Reads the SED that gta.sed() computed in the task.

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).

AskIn which energy bins is the source detected?
Sourceresults_helpers.py, line 198
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

Private functions it calls (2)

_walkresults_helpers.py, line 174
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
_inputsresults_helpers.py, line 153
def _inputs():
    if _STATE['inputs'] is None:
        raise HelperError('no results were given to this computation')
    return _STATE['inputs']

rh.lc(task_id=None, index=-1)

Reads the light curve that gta.lightcurve() computed in the task.

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.

AskList the light-curve bins with TS above 25.
Sourceresults_helpers.py, line 236
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

Private functions it calls (2)

_walkresults_helpers.py, line 174
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
_inputsresults_helpers.py, line 153
def _inputs():
    if _STATE['inputs'] is None:
        raise HelperError('no results were given to this computation')
    return _STATE['inputs']

rh.catalog_sed(catalog='4fgl')

Reads the target's entry in a LAT catalog as SED points, the same points the SED card draws.

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.

AskHow do my SED points compare with the 4FGL-DR4 band points? Plot both.
Sourceresults_helpers.py, line 215
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

Private functions it calls (1)

_inputsresults_helpers.py, line 153
def _inputs():
    if _STATE['inputs'] is None:
        raise HelperError('no results were given to this computation')
    return _STATE['inputs']

From the fitted model

Numbers the task's fitted spectrum gives, with errors from its covariance.

rh.band_flux(emin, emax, task_id=None, energy=False)

Integrates the fitted spectral model over the band, with the error propagated from the fit's covariance.

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.

AskWhat is the energy flux above 10 GeV, with its error?

Uses rh.fit

Sourceresults_helpers.py, line 332
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

Private functions it calls (4)

_propagateresults_helpers.py, line 303
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
_integralresults_helpers.py, line 297
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)))
_dnderesults_helpers.py, line 254
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')
_gridresults_helpers.py, line 293
def _grid(emin, emax, n=256):
    return np.logspace(math.log10(emin), math.log10(emax), n)

rh.model_e2dnde(energies, task_id=None)

Evaluates the fitted model's E² dN/dE at given energies, with errors from the covariance.

The task's fitted spectral model at the energies asked for, its 1σ error propagated from the fit's covariance.

AskWhat is E² dN/dE of the fitted model at 1 GeV?

Uses rh.fit

Sourceresults_helpers.py, line 358
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

Private functions it calls (2)

_propagateresults_helpers.py, line 303
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
_dnderesults_helpers.py, line 254
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')

rh.peak_energy(task_id=None)

Finds where the fitted model's E² dN/dE peaks inside the fitted range.

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.

AskWhere does the SED peak?

Uses rh.fit

Sourceresults_helpers.py, line 369
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])

Private functions it calls (2)

_gridresults_helpers.py, line 293
def _grid(emin, emax, n=256):
    return np.logspace(math.log10(emin), math.log10(emax), n)
_dnderesults_helpers.py, line 254
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')

rh.luminosity(eflux_erg, z, emin=None, emax=None, index=None)

Turns an energy flux into an isotropic luminosity at a redshift (Planck 2018 cosmology).

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.

AskWhat luminosity does that energy flux give at the catalog redshift?
Sourceresults_helpers.py, line 381
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)

Other spectral shapes

Shapes fitted to the SED bins' likelihood scans, and their comparison.

rh.fit_sed(shape, task_id=None, sed_data=None, start=None, names=None, label=None)

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).

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.

AskDoes a log-parabola describe the SED better than a power law?

Uses rh.sed

Sourceresults_helpers.py, line 456
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 == '<lambda>' 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

Private functions it calls (6)

_arrresults_helpers.py, line 248
def _arr(values):
    return np.array([np.nan if v is None else v for v in (values or [])], dtype=float)
_bin_loglikeresults_helpers.py, line 419
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
_hessian_errorsresults_helpers.py, line 575
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
_gridresults_helpers.py, line 293
def _grid(emin, emax, n=256):
    return np.logspace(math.log10(emin), math.log10(emax), n)
_shape_dnderesults_helpers.py, line 397
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)}')
_cleanresults_helpers.py, line 852
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

rh.compare_fits(*fits)

Compares fitted shapes: TS = 2 Δln L, the significance for a shape nested in the power law (Wilks), and the AIC.

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.

AskCompare the power law, log-parabola and cutoff fits to the SED.
Sourceresults_helpers.py, line 619
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

The light curve

Variability, change points and time scales from the saved bins.

rh.variability(curve, start=None, stop=None)

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.

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.

AskIs the source variable between March and June?

Uses rh.lc_select, rh.mjd_to_date

Sourceresults_helpers.py, line 678
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

Private functions it calls (1)

_arrresults_helpers.py, line 248
def _arr(values):
    return np.array([np.nan if v is None else v for v in (values or [])], dtype=float)

rh.bayesian_blocks(curve, p0=0.05)

Splits the light curve into Bayesian blocks of constant flux (Scargle et al. 2013).

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.

AskWhen were the flares? Show the light curve with Bayesian blocks.

Uses rh.mjd_to_date

Sourceresults_helpers.py, line 727
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

Private functions it calls (1)

_arrresults_helpers.py, line 248
def _arr(values):
    return np.array([np.nan if v is None else v for v in (values or [])], dtype=float)

rh.doubling_times(curve, min_sigma=3.0)

Finds flux doubling or halving times between consecutive detected bins that differ significantly.

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.

AskWhat is the shortest flux doubling time?

Uses rh.mjd_to_date

Sourceresults_helpers.py, line 761
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'])

Private functions it calls (1)

_arrresults_helpers.py, line 248
def _arr(values):
    return np.array([np.nan if v is None else v for v in (values or [])], dtype=float)

Small helpers

Selecting, formatting, and showing tables and plots under the answer.

rh.tasks()

Lists the tasks with saved results.

Sourceresults_helpers.py, line 159
def tasks():
    """The task ids that have results, oldest first."""
    return [int(k) for k in sorted(_inputs()['tasks'], key=int)]

Private functions it calls (1)

_inputsresults_helpers.py, line 153
def _inputs():
    if _STATE['inputs'] is None:
        raise HelperError('no results were given to this computation')
    return _STATE['inputs']

rh.task(task_id=None)

A task's record.

Uses rh.tasks

Sourceresults_helpers.py, line 164
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

Private functions it calls (1)

_inputsresults_helpers.py, line 153
def _inputs():
    if _STATE['inputs'] is None:
        raise HelperError('no results were given to this computation')
    return _STATE['inputs']

rh.lc_select(curve, start=None, stop=None)

Keeps the light-curve bins inside a time window.

Sourceresults_helpers.py, line 661
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

Private functions it calls (2)

_to_mjdresults_helpers.py, line 646
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)
_arrresults_helpers.py, line 248
def _arr(values):
    return np.array([np.nan if v is None else v for v in (values or [])], dtype=float)

rh.blocks_curve(blocks, name='Bayesian blocks')

Turns blocks into a light curve for plotting.

Sourceresults_helpers.py, line 754
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)}

rh.mjd_to_date(mjd)

Converts an MJD to a UTC date.

Sourceresults_helpers.py, line 655
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')

rh.fmt(v, digits=3)

Formats a number.

Sourceresults_helpers.py, line 860
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)

rh.table(rows, columns=None, title=None)

Shows a table.

Uses rh.fmt

Sourceresults_helpers.py, line 883
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()

Private functions it calls (7)

_recordresults_helpers.py, line 783
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')
_cellresults_helpers.py, line 873
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)
_draw_hereresults_helpers.py, line 795
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()
_json_defaultresults_helpers.py, line 842
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)
_cleanresults_helpers.py, line 852
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
_shortresults_helpers.py, line 110
def _short(v):
    if isinstance(v, dict):
        if 'e2dnde' in v and 'e' in v:
            return f"<model curve: {len(v.get('e') or [])} points>"
        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)
_arrresults_helpers.py, line 248
def _arr(values):
    return np.array([np.nan if v is None else v for v in (values or [])], dtype=float)

rh.plot_sed(*items, labels=None, title=None, fits=None, task_id=None)

Draws an SED plot.

Uses rh.sed

Sourceresults_helpers.py, line 933
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()

Private functions it calls (6)

_flatresults_helpers.py, line 920
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
_recordresults_helpers.py, line 783
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')
_sed_seriesresults_helpers.py, line 902
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')}}
_draw_hereresults_helpers.py, line 795
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()
_json_defaultresults_helpers.py, line 842
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)
_arrresults_helpers.py, line 248
def _arr(values):
    return np.array([np.nan if v is None else v for v in (values or [])], dtype=float)

rh.plot_lc(*curves, labels=None, title=None)

Draws a light-curve plot.

Uses rh.blocks_curve

Sourceresults_helpers.py, line 949
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()

Private functions it calls (5)

_recordresults_helpers.py, line 783
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')
_arrresults_helpers.py, line 248
def _arr(values):
    return np.array([np.nan if v is None else v for v in (values or [])], dtype=float)
_flatresults_helpers.py, line 920
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
_draw_hereresults_helpers.py, line 795
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()
_json_defaultresults_helpers.py, line 842
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)