Anatomy of an SED

What you will do

Build a panchromatic spectral energy distribution (SED) model with every major component enabled: stellar continuum, nebular emission, dust attenuation and re-emission, active galactic nucleus, radio, X-ray, and intergalactic medium absorption. You will sweep individual parameters to isolate each component’s contribution to the total flux, from hard X-rays to radio wavelengths.

What you need

A bare-stellar stellar population synthesis grid (without nebular or dust emissions) and a panchromatic filter set spanning ultraviolet through radio to showcase each component.

What you will have

A framework for understanding which components matter where in the SED, and how to enable or disable each in your own models. A complete self-consistent spectrum from hard X-rays to 10 centimeter radio.


A faithful SED is a composition of stellar continuum, nebular emission, dust attenuation and re-emission, active galactic nucleus, radio, X-ray, and intergalactic medium absorption. Tengri assembles all of these from a single nested-dictionary specification. The methods model.summary() makes the composition explicit, and citations.print_citations(model) produces a bibliography ready for your methods section.

[1]:
import os

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"  # silence XLA/PjRt C++ INFO+WARNING logs

import logging
import warnings
from copy import deepcopy
from pathlib import Path

import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np

# Keep the narrative clean: hide JAX/XLA chatter, the harmless
# BakedInBackend notice (emitted when a component has no precompute
# path), and the SFH-before-Big-Bang notice the z = 2 demo triggers
# (a parametric SFH there has support older than cosmic time; the
# absolute mass scale is irrelevant for the shape-only anatomy figure).
warnings.filterwarnings("ignore", message=".*BakedInBackend.*")
warnings.filterwarnings("ignore", message=".*before the Big Bang.*")
warnings.filterwarnings("ignore", message=".*WavePrecomp.*")
warnings.filterwarnings("ignore", message=".*states no 'all_params' disposition.*")
warnings.filterwarnings("ignore", message=".*Composable AGN.*")
warnings.filterwarnings("ignore", category=RuntimeWarning)
logging.getLogger("jax").setLevel(logging.ERROR)

from _setup import FIG_DIR
import tengri
from tengri import (
    builders,
    citations,
    DEFAULT,
    Fixed,
    FREE,
    Observation,
    Photometry,
    plot,
    recipes,
    SEDModel,
    Uniform,
)
from tengri.units import erg_per_s_to_lsun, lnu_to_llambda

plot.setup_style()

Setup: bare-stellar SSP and panchromatic filters

The Cue nebular backend requires a bare-stellar stellar population synthesis grid. The filter set spans GALEX through ALMA so every component has wavelengths where it contributes measurably.

[2]:
ssp = tengri.load_ssp("fsps_prsc_miles_chabrier", download=True)

filters = [
    "galex_fuv",
    "galex_nuv",
    "sdss_u",
    "sdss_g",
    "sdss_r",
    "sdss_i",
    "sdss_z",
    "ukidss_y",
    "ukidss_j",
    "ukidss_h",
    "ukidss_k",
    "irac_36",
    "irac_45",
    "irac_58",
    "irac_80",
    "wise_w3",
    "wise_w4",
    "mips_24",
    "mips_70",
    "mips_160",
    "herschel_100",
    "herschel_160",
    "herschel_250",
    "herschel_350",
    "herschel_500",
]
obs = Observation(photometry=Photometry.from_names(filters))

The complete model

A full model at z = 2 with all major components enabled: star formation, dust attenuation and emission, nebular continuum and lines, active galactic nucleus, radio, X-ray, and intergalactic medium absorption. Every parameter is pinned at a physically reasonable value so the figure is reproducible.

[3]:
# log_lbol is log10(L_bol / L_sun), set to a modest active galactic nucleus here. At z = 2 (cosmic age 3.29 Gyr), a parametric double power-law inevitably has support before the Big Bang, which tengri flags with a `SFHBeforeBigBangWarning` and truncates; the absolute mass scale is irrelevant for this shape-only anatomy illustration, so we silence the warning above.
kitchen_sink = dict(
    sfh={
        "type": "dpl",
        "all_params": Fixed(DEFAULT),
        "log_total_mass": 10.5,
        "alpha": 2.2,
        "beta": 1.4,
        "tau_gyr": 4.0,
    },
    dust_attenuation={
        "type": "two_component",
        "law": "calzetti",
        "all_params": Fixed(DEFAULT),
        "tau_bc": 0.8,
        "tau_diff": 0.3,
        # dale2014_cigale, not dale2014: this notebook also switches on a radio
        # block, and the plain Dale+2014 template embeds its own star-forming
        # radio synchrotron continuum out to 1.335 GHz. Running both double-counts
        # the radio continuum (~2x between ~1.34 and ~10 GHz), which #1983 made a
        # ConfigError. The _cigale variant has that tail stripped, per CIGALE
        # convention — the remedy that error itself prescribes.
    },
    dust_emission={"type": "dale2014_cigale", "all_params": Fixed(DEFAULT), "alpha_dale": 2.2},
    neb={"type": "cue", "all_params": Fixed(DEFAULT)},
    agn={
        "all_params": Fixed(DEFAULT),  # every AGN block here is deliberately fixed (#1995)
        "disc": {"type": "multicolor", "all_params": Fixed(DEFAULT), "log_lbol": 10.5},
        "torus": {
            "type": "skirtor",
            "all_params": Fixed(DEFAULT),
            "tau_skirtor": 5.0,
            "torus_frac": 0.5,
        },
        "nlr": {"type": "analytic", "all_params": Fixed(DEFAULT)},
        "blr": {"type": "none", "all_params": Fixed(DEFAULT)},
    },
    radio={"sf": {"type": "bell2003"}, "agn": {"type": "powerlaw"}, "all_params": Fixed(DEFAULT)},
    xray={"type": "simple", "all_params": Fixed(DEFAULT)},
    redshift=Fixed(2.0),
    igm={"type": "inoue"},
)

model = SEDModel.build(ssp_data=ssp, observation=obs, **kitchen_sink)
print(model.summary())
Model  SFH: dpl
──────────────────────────────────────────────────────────────────
  SSP grid:    15 Z × 93 ages × 5994 λ [91–100000000 Å]
  Filters:     25 bands
  Redshift:    2.0000 (fixed)
  Dtype:       float64
  Fast path:   exact (approx=None)
  Components:  nebular=cue, dust_emission=dale2014_cigale, agn=composable, igm, radio, xray

  Pipeline (8 components):
    1. stellar        [sfh_model=dpl, metallicity_model=delta, n_grid=256]
    2. nebular        [backend=cue]
    3. dust           [law=calzetti]
    4. dust_emission
    5. agn            [model=composable]
    6. radio
    7. xray           [model=simple]
    8. igm

  Parameters:  0 free
──────────────────────────────────────────────────────────────────

Citations from the assembled model

[4]:
citations.print_citations(model)
Please cite the following when publishing results that use tengri:

  [1] Cooray et al. (2026, Paper I) ; SED fitting framework — methods paper (this package)
       {tengri: Differentiable SED fitting with Information-Field-Theory star formation history priors. I. Framework and mock recovery}

  [2] Bradbury et al. (2018) ; Autodiff framework and XLA compiler integration
       {JAX}: composable transformations of {P}ython+{N}um{P}y programs
       code: jax-ml/jax

  [3] Hearin et al. (2023) ; Differentiable stellar population synthesis engine
       {DSPS: Differentiable stellar population synthesis}
       DOI: 10.1093/mnras/stad456   arXiv: 2112.06830   code: ArgonneCPAC/dsps

  [4] Oke \& Gunn (1983) ; AB magnitude system / absolute spectrophotometric zero point
       {Secondary standard stars for absolute spectrophotometry.}
       DOI: 10.1086/160817

  [5] Hogg et al. (2002) ; Photon-counting bandpass AB flux (Eq.~5); K-correction formalism
       {The K correction}
       DOI: 10.48550/arXiv.astro-ph/0210394   arXiv: astro-ph/0210394

  [6] Fukugita et al. (1996) ; Photon-counting AB magnitude definition (cited by FSPS getmags)
       {The Sloan Digital Sky Survey Photometric System}
       DOI: 10.1086/117915

  [7] Bessell \& Murphy (2012) ; Photonic (photon-counting) passbands and pivot wavelength
       {Spectrophotometric Libraries, Revised Photonic Passbands, and Zero Points for UBVRI, Hipparcos, and Tycho Photometry}
       DOI: 10.1086/664083   arXiv: 1112.2698

  [8] Conroy & Gunn (2010) ; Stellar population synthesis (reference implementation)
       {The Propagation of Uncertainties in Stellar Population Synthesis Modeling. III. Model Calibration, Comparison, and Evaluation}
       DOI: 10.1088/0004-637X/712/2/833   arXiv: 0911.3151   code: cconroy20/fsps

  [9] Carnall et al. (2018) ; Reference SED fitting framework (BAGPIPES)
       {Inferring the star formation histories of massive quiescent galaxies with BAGPIPES: evidence for multiple quenching mechanisms}
       DOI: 10.1093/mnras/sty2169   arXiv: 1712.04452   code: ACCarnall/bagpipes

  [10] Conroy, Gunn \& White (2009) ; FSPS — flexible stellar population synthesis (grid generator)
       {The Propagation of Uncertainties in Stellar Population Synthesis Modeling. I. The Relevance of Uncertain Aspects of Stellar Evolution and the Initial Mass Function to the Derived Physical Properties of Galaxies}
       DOI: 10.1088/0004-637X/699/1/486   arXiv: 0809.4261   code: cconroy20/fsps

  [11] Foreman-Mackey et al. (2014) ; python-fsps — Python interface used to generate the SSP grids
       {python-fsps: Python bindings to FSPS (v0.1.1)}
       DOI: 10.5281/zenodo.12157   code: dfm/python-fsps

  [12] Aringer et al. (2009) ; Carbon-star spectral library extending FSPS TP-AGB stars redward of K
       {Synthetic photometry for carbon rich giants. I. Hydrostatic dust-free models}
       DOI: 10.1051/0004-6361/200911703   arXiv: 0905.4415

  [13] Villaume et al. (2015) ; Circumstellar (AGB) dust-shell SEDs in FSPS (add_agb_dust_model)
       {Circumstellar Dust around AGB Stars and Implications for Infrared Emission from Galaxies}
       DOI: 10.1088/0004-637X/806/1/82   arXiv: 1504.00900

  [14] Bressan et al. (2012) ; PARSEC stellar evolution isochrones
       {PARSEC: stellar tracks and isochrones with the PAdova and TRieste Stellar Evolution Code}
       DOI: 10.1111/j.1365-2966.2012.21948.x   arXiv: 1208.4498

  [15] Falc{\'o}n-Barroso et al. (2011) ; Empirical stellar spectral library (MILES)
       {An updated MILES stellar library and stellar population models}
       DOI: 10.1051/0004-6361/201116842   arXiv: 1107.2303

  [16] Chabrier (2003) ; Chabrier initial mass function
       {Galactic Stellar and Substellar Initial Mass Function}
       DOI: 10.1086/376392   arXiv: astro-ph/0304382

  [17] Charlot & Fall (2000) ; Two-component dust attenuation (BC+ISM)
       {A Simple Model for the Absorption of Starlight by Dust in Galaxies}
       DOI: 10.1086/309250   arXiv: astro-ph/0003128

  [18] Dale et al. (2014) ; Two-parameter IR/submm/radio SED template family
       {A Two-parameter Model for the Infrared/Submillimeter/Radio Spectral Energy Distributions of Galaxies and Active Galactic Nuclei}
       DOI: 10.1088/0004-637X/784/1/83   arXiv: 1402.1495

  [19] Calzetti et al. (2000) ; Starburst dust attenuation law
       {The Dust Content and Opacity of Actively Star-forming Galaxies}
       DOI: 10.1086/308692   arXiv: astro-ph/9911459

  [20] Inoue et al. (2014) ; IGM Lyman series attenuation
       {An updated analytic model for attenuation by the intergalactic medium}
       DOI: 10.1093/mnras/stu936   arXiv: 1402.0677

  [21] Li et al. (2025) ; Nebular emission-line emulator
       {Cue: A Fast and Flexible Photoionization Emulator for Modeling Nebular Emission Powered By Almost Any Ionizing Source}
       DOI: 10.3847/1538-4357/adcab4   arXiv: 2405.04598   code: yi-jia-li/cue

  [22] Fragos et al. (2013) ; HMXB L_X/SFR metallicity quartic (Eq. 3) and LMXB L_X/M* age quartic (Eq. 4)
       {Energy Feedback from X-ray Binaries in the Early Universe}
       DOI: 10.1088/2041-8205/776/2/L31   arXiv: 1306.1405

  [23] Lehmer et al. (2016) ; Observational benchmark for the XRB scalings: redshift-dependent L_X-M*-SFR relation from the 6 Ms CDF-S
       {The Evolution of Normal Galaxy X-Ray Emission through Cosmic History: Constraints from the 6 Ms Chandra Deep Field-South}
       DOI: 10.3847/0004-637X/825/1/7   arXiv: 1604.06461

  [24] Condon (1992) ; Radio synchrotron + free-free continuum from star formation
       {Radio emission from normal galaxies}
       DOI: 10.1146/annurev.aa.30.090192.003043

  [25] Bell (2003) ; IR-radio correlation / SFR calibration
       {Estimating Star Formation Rates from Infrared and Radio Luminosities: The Origin of the Radio-Infrared Correlation}
       DOI: 10.1086/367829   arXiv: astro-ph/0212121

Panchromatic anatomy

All components of the SED from X-rays to radio are shown together on a single rest-frame wavelength grid.

The dust emission in this model is the Dale 2014 template, which has no single dust temperature, so the da Cunha et al. (2013) CMB heating boost does not apply to it. The analytic models (modified_blackbody, graybody, casey2012) include the boost by default, and the Schreiber templates include it when cmb=True is set. Their emitted dust luminosity is the absorbed power times [T_d(z)/T_d,0]^(4+beta). For 20 K dust with beta = 1.8 at z = 6 that factor is 1.76, so the far-IR can exceed the absorbed stellar power. The stellar energy balance is unchanged.

[5]:
params = model.spec.sample(jax.random.PRNGKey(0))
state = model.predict_state(params)

wave_rest = np.asarray(state.wave)  # Å
total = np.asarray(state.sed_intrinsic)  # erg/s/Hz, post-dust-attenuation + emission


# Per-component contributions from the orchestrator's derived bundle.
def _get(key, default=None):
    arr = state.derived.get(key, default)
    return None if arr is None else np.asarray(arr)


lnu_age = _get("lnu_age")  # (n_age, n_wave) intrinsic
sed_stellar_intrinsic = lnu_age.sum(axis=0) if lnu_age is not None else None
sed_stellar_attenuated = _get("sed_dust_attenuated")
sed_nebular = _get("sed_nebular")
sed_dust_emission = _get("sed_dust_ir")
sed_agn = _get("sed_agn", _get("sed_grahsp"))  # AGN may be off in some builds

C = {
    "stellar": "#d97a3a",  # warm
    "nebular": "#c8377d",  # magenta
    "dust_att": "#3a76d9",  # blue
    "dust_em": "#c3372a",  # red
    "agn": "#7c3fbf",  # violet
    "total": "0.05",  # near-black
}

fig, ax = plt.subplots(figsize=(9.5, 5.4))
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlabel(r"rest-frame wavelength $\lambda$  [$\mu$m]")
ax.set_ylabel(r"$\nu L_\nu$  [erg s$^{-1}$]")
wave_um = wave_rest / 1e4


def nu_lnu(wave, lnu):
    """nu*L_nu [erg/s] on a wavelength grid [Angstrom].

    nu*L_nu and lambda*L_lambda are the same quantity, so the public unit
    conversion gives it without hand-rolling a speed-of-light literal.
    """
    return None if lnu is None else wave * lnu_to_llambda(lnu, wave)


def nuLnu(y):
    return nu_lnu(wave_rest, y)


ax.plot(wave_um, nuLnu(total), color=C["total"], lw=2.2, label="total")
if sed_stellar_intrinsic is not None:
    ax.plot(
        wave_um,
        nuLnu(sed_stellar_intrinsic),
        color=C["stellar"],
        lw=1.0,
        ls="--",
        alpha=0.7,
        label="stellar (intrinsic)",
    )
if sed_stellar_attenuated is not None:
    ax.plot(
        wave_um,
        nuLnu(sed_stellar_attenuated),
        color=C["dust_att"],
        lw=1.4,
        label="stellar (attenuated)",
    )
if sed_nebular is not None:
    ax.plot(wave_um, nuLnu(sed_nebular), color=C["nebular"], lw=1.0, label="nebular")
if sed_dust_emission is not None:
    ax.plot(wave_um, nuLnu(sed_dust_emission), color=C["dust_em"], lw=1.4, label="dust emission")
if sed_agn is not None:
    ax.plot(wave_um, nuLnu(sed_agn), color=C["agn"], lw=1.4, label="AGN (disc + torus + NLR)")

# Annotate physical features.
for lam_um, label in [
    (0.0912, "Lyman\nbreak"),
    (0.122, r"Ly$\alpha$"),
    (0.36, "Balmer\nbreak"),
    (0.6564, r"H$\alpha$"),
    (7.7, "PAH"),
    (100, r"100$\,\mu$m peak"),
]:
    if lam_um < wave_um.min() or lam_um > wave_um.max():
        continue
    y = np.interp(lam_um, wave_um, nuLnu(total))
    ax.annotate(
        label,
        xy=(lam_um, y),
        xytext=(0, 18),
        textcoords="offset points",
        fontsize=8,
        ha="center",
        color="0.25",
        arrowprops=dict(arrowstyle="-", color="0.5", lw=0.5),
    )

ax.set_xlim(1e-2, 1e4)
ax.set_ylim(nuLnu(total).max() * 1e-7, nuLnu(total).max() * 3)
ax.legend(loc="lower center", ncol=3, frameon=False, fontsize=9)
ax.set_title(f"Kitchen-sink SED at z = {float(model.spec.get_fixed_values()['redshift']):.1f}")
fig.tight_layout()
fig.savefig(FIG_DIR / "02_anatomy_panchromatic.png", dpi=300, bbox_inches="tight")
../_images/spine_02_sed_anatomy_9_0.png

Four sweeps, one knob at a time

We use a leaner star-forming recipe so the figures remain readable; all parameters are held fixed except the swept one.

[6]:
base = recipes.star_forming_photometry()
# Pin the model down to defaults, then sweep one parameter at a time.
base["sfh"]["all_params"] = Fixed(DEFAULT)
base["dust_attenuation"]["all_params"] = Fixed(DEFAULT)
base["dust_emission"]["all_params"] = Fixed(DEFAULT)
base["redshift"] = Fixed(0.5)


def predict_rest(m, p):
    s = m.predict_state(p)
    return np.asarray(s.wave), np.asarray(s.sed_intrinsic)


fig, axes = plt.subplots(2, 2, figsize=(11, 7.4), constrained_layout=True)


# (a) SFH shape — three canonical SFHs, mass-normalized
ax = axes[0, 0]
for label, sfh_dict, color in [
    ("exponential", builders.sfh.exp(all_params=Fixed(DEFAULT)), "#d97a3a"),
    ("delayed-exp", builders.sfh.dexp(all_params=Fixed(DEFAULT)), "#c8377d"),
    ("DPL", builders.sfh.dpl(all_params=Fixed(DEFAULT)), "#3a76d9"),
]:
    cfg = deepcopy(base)
    cfg["sfh"] = sfh_dict
    m = SEDModel.build(ssp_data=ssp, observation=obs, **cfg)
    p = m.spec.sample(jax.random.PRNGKey(0))
    w, sed = predict_rest(m, p)
    ax.plot(w / 1e4, nu_lnu(w, sed), label=label, color=color, lw=1.3)
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlim(0.05, 30)
ax.set_xlabel(r"$\lambda$ [$\mu$m]")
ax.set_ylabel(r"$\nu L_\nu$ [erg/s]")
ax.set_title("SFH shape")
ax.legend(frameon=False, fontsize=9)

# (b) Birth-cloud τ_V sweep: same structure, varying parameter value. Build once with tau_bc as a free parameter; predict at each value. This illustrates that a model is a function of its parameters.
ax = axes[0, 1]
cmap = plt.colormaps["viridis"]
tau_grid = [0.0, 0.5, 1.0, 2.0, 3.0]
cfg = deepcopy(base)
cfg["dust_attenuation"]["tau_bc"] = Uniform(0.0, 3.0)  # tau_bc is now a free parameter
m = SEDModel.build(ssp_data=ssp, observation=obs, **cfg)
p = m.spec.sample(jax.random.PRNGKey(0))
for tau, col in zip(tau_grid, cmap(np.linspace(0.15, 0.85, len(tau_grid)))):
    w, sed = predict_rest(m, {**p, "dust_tau_bc": tau})
    ax.plot(w / 1e4, nu_lnu(w, sed), color=col, lw=1.2, label=rf"$\tau_{{\rm BC}}={tau:g}$")
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlim(0.05, 30)
ax.set_xlabel(r"$\lambda$ [$\mu$m]")
ax.set_ylabel(r"$\nu L_\nu$ [erg/s]")
ax.set_title("Birth-cloud optical depth")
ax.legend(frameon=False, fontsize=9, ncol=2)

# (c) AGN bolometric luminosity sweep: same structure, varying parameter value. A lightweight active galactic nucleus uses a multicolor disc and Nenkova torus; build once, predict at each luminosity. The Nenkova torus is an analytic stand-in (SKIRTOR would cost 5 times more). log_lbol = log10(L_bol / L_sun), so 10–11 spans a Seyfert to a low-luminosity quasar.
ax = axes[1, 0]
log_lbol_grid = [9.5, 10.0, 10.5, 11.0, 11.5]
cmap = plt.colormaps["plasma"]
cfg = deepcopy(base)
cfg["agn"] = {
    "all_params": Fixed(
        DEFAULT
    ),  # unprovided sub-blocks (nlr/blr/feii/atten) stay fixed by intent
    "disc": {"type": "multicolor", "all_params": Fixed(DEFAULT), "log_lbol": Uniform(9.0, 12.0)},
    "torus": {"type": "nenkova", "all_params": Fixed(DEFAULT)},
}
m = SEDModel.build(ssp_data=ssp, observation=obs, **cfg)
p = m.spec.sample(jax.random.PRNGKey(0))
for log_lbol, col in zip(log_lbol_grid, cmap(np.linspace(0.15, 0.85, len(log_lbol_grid)))):
    w, sed = predict_rest(m, {**p, "agn_log_lbol": log_lbol})
    ax.plot(
        w / 1e4, nu_lnu(w, sed), color=col, lw=1.2, label=rf"$\log L_{{\rm AGN}}={log_lbol:g}$"
    )
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlim(0.05, 30)
ax.set_xlabel(r"$\lambda$ [$\mu$m]")
ax.set_ylabel(r"$\nu L_\nu$ [erg/s]")
ax.set_title("AGN luminosity")
ax.legend(frameon=False, fontsize=8, ncol=1)

# (d) Redshift sweep: same intrinsic spectrum, different intergalactic medium attenuation and observed-frame wavelengths.
ax = axes[1, 1]
z_grid = [0.0, 1.0, 3.0, 6.0]
cmap = plt.colormaps["cividis"]
for z, col in zip(z_grid, cmap(np.linspace(0.15, 0.85, len(z_grid)))):
    cfg = deepcopy(base)
    cfg["redshift"] = Fixed(z)
    cfg["igm"] = {"type": "inoue"} if z > 0 else {"type": "none"}
    m = SEDModel.build(ssp_data=ssp, observation=obs, **cfg)
    p = m.spec.sample(jax.random.PRNGKey(0))
    pred = m.predict(p)
    w_obs = np.asarray(pred.wave_obs)  # observed-frame wavelength [Å]
    sed_obs = np.asarray(pred.obs_sed())  # L_nu [erg/s/Hz], observed frame + IGM
    ax.plot(w_obs / 1e4, nu_lnu(w_obs, sed_obs), color=col, lw=1.2, label=rf"$z={z:g}$")
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlim(0.05, 30)
ax.set_xlabel(r"$\lambda_{\rm obs}$ [$\mu$m]")
ax.set_ylabel(r"$\nu L_\nu$ [erg/s]")
ax.set_title("Redshift + IGM")
ax.legend(frameon=False, fontsize=9)

fig.savefig(FIG_DIR / "02_anatomy_sweeps.png", dpi=300, bbox_inches="tight")
../_images/spine_02_sed_anatomy_11_0.png

Editing a built model: spec.to_groups()

Extract the model’s configuration, edit a parameter, and rebuild it.

[7]:
groups = model.spec.to_groups()
groups["dust_attenuation"]["tau_bc"] = Fixed(1.5)  # double the birth-cloud opacity
model_edited = SEDModel.build(ssp_data=ssp, observation=obs, **groups)
print(model_edited.summary())
Model  SFH: dpl
──────────────────────────────────────────────────────────────────
  SSP grid:    15 Z × 93 ages × 5994 λ [91–100000000 Å]
  Filters:     25 bands
  Redshift:    2.0000 (fixed)
  Dtype:       float64
  Fast path:   exact (approx=None)
  Components:  nebular=cue, dust_emission=dale2014_cigale, agn=composable, igm, radio, xray

  Pipeline (8 components):
    1. stellar        [sfh_model=dpl, metallicity_model=delta, n_grid=256]
    2. nebular        [backend=cue]
    3. dust           [law=calzetti]
    4. dust_emission
    5. agn            [model=composable]
    6. radio
    7. xray           [model=simple]
    8. igm

  Parameters:  0 free
──────────────────────────────────────────────────────────────────

What each layer does

  • Stellar continuum. Differentiable Stellar Population Synthesis integration of an SFH and metallicity history onto an age × wavelength grid, summed to intrinsic L_ν.

  • Dust attenuation. Birth-cloud (Calzetti) and diffuse interstellar medium optical depths reshape the ultraviolet to near-infrared. Absorbed energy is tracked as L_ir. The two-component group also routes each emission source through specified screens: nebular_screen (default birth cloud), shock_screen (default diffuse), and agn_screen (default none).

  • Dust emission. Dale 2014, Draine–Li, or THEMIS templates re-radiate L_ir from 8 to 1000 micrometers.

  • Nebular. Cue, a neural emulator trained on Cloudy 22.00, yields photoionized continuum and 128 emission lines from ionization parameter and conditions.

  • AGN. Disc (multicolor, Kubota–Done, ADAF, or power-law), torus (SKIRTOR, Nenkova, CAT3D, Silva04, or toy), narrow-line region (Cue), and broad-line region (qsogen).

  • Radio. Free-free and synchrotron emission from the infrared to radio correlation, plus an optional AGN power-law.

  • X-ray. Lusso & Risaliti 2017 L_2500 to L_2keV conversion with optional ADAF or Comptonization refinements.

  • IGM. Inoue 2014 Lyman-alpha forest opacity for z greater than 0.

Multiwavelength SED

A complete self-consistent SED from hard X-rays to radio wavelengths at z = 0.1. The model parameters (stellar mass, SFR, and AGN bolometric luminosity) are displayed in the title, read from the assembled model.

The X-ray component is shown twice: unobscured and behind a heavily absorbing column (N_H = 10²³ cm⁻²). This demonstrates how line-of-sight photoelectric absorption attenuates the soft band while hard X-rays penetrate.

[8]:
C_UM = 2.998e14  # speed of light in [µm Hz], for the λ → ν twin axis

money_shot = dict(
    # tau is close to the cosmic age at z = 0.1, which places the double power-law on its
    # rising shoulder, so the current SFR is near its peak (an elevated, dusty
    # main-sequence galaxy).
    sfh={
        "type": "dpl",
        "all_params": Fixed(DEFAULT),
        "log_total_mass": 10.72,
        "alpha": 0.9,
        "beta": 2.7,
        "tau_gyr": 13.2,
    },
    dust_attenuation={
        "type": "two_component",
        "law": "calzetti",
        "all_params": Fixed(DEFAULT),
        "tau_bc": 0.8,
        "tau_diff": 0.3,
        # dale2014_cigale, not dale2014: this notebook also switches on a radio
        # block, and the plain Dale+2014 template embeds its own star-forming
        # radio synchrotron continuum out to 1.335 GHz. Running both double-counts
        # the radio continuum (~2x between ~1.34 and ~10 GHz), which #1983 made a
        # ConfigError. The _cigale variant has that tail stripped, per CIGALE
        # convention — the remedy that error itself prescribes.
    },
    dust_emission={"type": "dale2014_cigale", "all_params": Fixed(DEFAULT), "alpha_dale": 2.2},
    neb={"type": "cue", "all_params": Fixed(DEFAULT)},
    agn={
        "all_params": Fixed(DEFAULT),  # every AGN block here is deliberately fixed (#1995)
        "disc": {"type": "multicolor", "all_params": Fixed(DEFAULT), "log_lbol": 10.5},
        "torus": {
            "type": "skirtor",
            "all_params": Fixed(DEFAULT),
            "tau_skirtor": 5.0,
            "torus_frac": 0.5,
        },
        "nlr": {"type": "analytic", "all_params": Fixed(DEFAULT)},
        "blr": {"type": "none", "all_params": Fixed(DEFAULT)},
    },
    radio={"sf": {"type": "bell2003"}, "agn": {"type": "powerlaw"}, "all_params": Fixed(DEFAULT)},
    xray={"type": "simple", "all_params": Fixed(DEFAULT)},
    redshift=Fixed(0.1),
)

ms_model = SEDModel.build(ssp_data=ssp, observation=obs, **money_shot)
state = ms_model.predict_state(ms_model.spec.sample(jax.random.PRNGKey(0)))

wave_aa = np.asarray(state.wave)  # Å
wave_um = wave_aa / 1e4


def _comp(key):
    arr = state.derived.get(key)
    return None if arr is None else np.asarray(arr)


# Convert to nu*L_nu in solar luminosities so the y-axis matches the reference figure.
def nuLnu_lsun(lnu):
    return None if lnu is None else erg_per_s_to_lsun(nu_lnu(wave_aa, lnu))


lnu_age = _comp("lnu_age")
sed_stars = lnu_age.sum(axis=0) if lnu_age is not None else None
sed_total = np.asarray(state.sed_intrinsic)

# X-ray with line-of-sight obscuration as a teaching point. state.derived["sed_xray"] is the full Yang+2020 / X-CIGALE X-ray (XRB plus hot gas plus AGN corona) at the default column N_H = 1e20. The corona is driven by the AGN-published L_2500_intrinsic via the Just+2007 α_ox relation, and it is already included in the total. To show how line-of-sight absorption attenuates the soft band, we recompute the X-ray at N_H = 1e23 using the model's 2500 Angstrom luminosity (Morrison & McCammon 1983 + Wilms+2000 photoelectric + Compton). Since N_H is not yet a build-time parameter, the obscured variant uses the public tengri.xray API.
from tengri.xray import xray_total

_sfr = float(state.derived["sfr"])
_mstar = 10.0 ** float(state.derived["log_mstar"])
# Use the same L_2500 as the X-ray component: intrinsic disc 2500 Å, or the Hopkins+2007 bolometric correction if the disc value is unavailable.
_l2500 = float(state.derived.get("L_2500_intrinsic", 0.0))
if _l2500 <= 0.0:
    _l2500 = float(state.derived["L_agn_bol"]) / (5.15 * 1.199e15)
sed_xray_unobs = _comp("sed_xray")  # build's corona-complete X-ray (N_H=1e20)
sed_xray_obsc = np.asarray(
    xray_total(wave_aa, sfr=_sfr, stellar_mass=_mstar, l_2500_30deg=_l2500, log_nh=23.0)
)

# (sed, label, color, linestyle, linewidth): drawn back-to-front.
CURVES = [
    (sed_stars, "Stars (intrinsic, no dust)", "0.55", "--", 1.1),
    (_comp("sed_nebular"), "Nebular (Cue: continuum + lines)", "#19b3c4", "-", 1.0),
    (_comp("sed_dust_attenuated"), "Stellar continuum (attenuated)", "#3a6ea5", "-", 1.4),
    (_comp("sed_dust_ir"), "Dust emission (Dale 2014)", "#e8920c", "-", 1.4),
    (_comp("sed_agn"), "AGN (disc + SKIRTOR torus + NLR)", "#d94f4f", "-", 1.4),
    (_comp("sed_radio"), "Radio (SF + AGN)", "#3aa653", "-", 1.4),
    (sed_xray_unobs, r"X-ray (XRB + corona, $N_{\rm H}=10^{20}$)", "#8a5fbf", "-.", 1.4),
    (sed_xray_obsc, r"X-ray obscured ($N_{\rm H}=10^{23}\,$cm$^{-2}$)", "#5a2f8f", ":", 1.6),
]

# Rest-frame wavelength regimes [micrometers] with pale alternating tints behind the SED.
BANDS = [
    ("Hard\nX-ray", 1e-4, 1.24e-3),
    ("Soft\nX-ray", 1.24e-3, 1.24e-2),
    ("EUV", 1.24e-2, 0.0912),
    ("FUV", 0.0912, 0.15),
    ("UV", 0.15, 0.30),
    ("Optical", 0.30, 0.75),
    ("NIR", 0.75, 5.0),
    ("MIR", 5.0, 40.0),
    ("FIR", 40.0, 1000.0),
    ("Radio", 1000.0, 1e6),
]

fig, ax = plt.subplots(figsize=(13, 6.5))
ax.set_xscale("log")
ax.set_yscale("log")

band_cmap = plt.colormaps["tab20c"]
for i, (name, w0, w1) in enumerate(BANDS):
    ax.axvspan(w0, w1, color=band_cmap(i / len(BANDS)), alpha=0.12, lw=0, zorder=0)
    ax.text(
        np.sqrt(w0 * w1),
        0.93,
        name,
        transform=ax.get_xaxis_transform(),
        ha="center",
        va="top",
        fontsize=8,
        color="0.35",
        style="italic",
    )

for sed, label, color, ls, lw in CURVES:
    y = nuLnu_lsun(sed)
    if y is None:
        continue
    mask = np.asarray(sed) > 0
    if not np.any(mask):
        continue
    ax.plot(wave_um[mask], y[mask], color=color, ls=ls, lw=lw, label=label, zorder=3)

ax.plot(wave_um, nuLnu_lsun(sed_total), color="k", lw=2.6, label="Total model", zorder=4)

# Annotate two rest-frame ultraviolet landmarks.
for lam_aa, txt in [(912.0, "Lyman\nlimit\n(912 Å)"), (3646.0, "Balmer\nbreak\n(3646 Å)")]:
    lam_um = lam_aa / 1e4
    ax.axvline(lam_um, color="0.5", ls=":", lw=0.8, zorder=1)
    ax.text(lam_um, 2e5, txt, fontsize=7, color="0.4", ha="center", va="bottom")

ax.set_xlim(1e-4, 1e6)
ymax = float(np.nanmax(nuLnu_lsun(sed_total)))
ax.set_ylim(ymax * 1e-9, ymax * 30)
ax.set_xlabel(r"Rest-frame wavelength $\lambda$  [$\mu$m]")
ax.set_ylabel(r"$\nu L_\nu$  [$L_\odot$]")

# Add a twin frequency axis (nu = c / lambda), sharing the log scale.
secax = ax.secondary_xaxis("top", functions=(lambda w: C_UM / w, lambda f: C_UM / f))
secax.set_xlabel(r"Rest-frame frequency $\nu$  [Hz]")

# Extract the headline numbers from the model.
m_star = 10.0 ** float(state.derived["log_mstar"])
sfr = float(state.derived["sfr"])
log_lagn = np.log10(erg_per_s_to_lsun(float(state.derived["L_agn_bol"])))
ax.set_title(
    "Multiwavelength SED\n"
    rf"$M_\star \approx {m_star:.0e}\,M_\odot$, "
    rf"SFR $\approx {sfr:.0f}\,M_\odot\,$yr$^{{-1}}$, "
    rf"$\log L_{{\rm bol}}^{{\rm AGN}} = {log_lagn:.1f}$"
)
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.14), ncol=4, frameon=False, fontsize=9)
fig.tight_layout()
fig.savefig(FIG_DIR / "02_anatomy_moneyshot.png", dpi=300, bbox_inches="tight")
../_images/spine_02_sed_anatomy_16_0.png

The next notebook, `03_discovering_the_menu.py <03_discovering_the_menu.ipynb>`__, shows how to discover every available component variant from inside Python.