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