Fitting spectroscopy¶
What you will do¶
Fit an SDSS-like optical spectrum alone to constrain stellar age and metallicity. You’ll see what spectroscopy constrains sharply (age, metallicity via absorption lines) and what stays loose (absolute dust optical depth).
What you need¶
An SSP grid at R ≳ 2000, an observed optical spectrum (for example, 3800–9200 Å). The fit uses the exact flux-conserving spectrum: at 260 pixels each pixel spans several resolution elements, so the model is integrated over every pixel rather than sampled at its center.
What you will have¶
A posterior with tight age and metallicity but loose dust normalization. This shows why combining spectroscopy with photometry helps.
Broadband photometry alone leaves stellar metallicity and dust prior-dominated. An optical spectrum carries absorption-line depths (Hβ, the Mgb triplet, the Fe blends) that pin stellar age and metallicity. This notebook fits a spectrum alone using the same machinery as the quickstart (SEDModel.build with a fixed-length HMC sampler) and shows what it constrains and what stays degenerate. The absolute dust optical depth remains loose because a spectrum sets the continuum shape, not its
normalization. Adding photometry closes that degeneracy, as shown in `07_joint_photo_spec <07_joint_photo_spec.ipynb>`__.
[1]:
import os
import warnings
# Four host devices so the four chains run in parallel.
os.environ["TENGRI_HOST_DEVICES"] = "4"
from _setup import FIG_DIR, quiet
quiet()
# Notebook-specific: we pair the wNE SSP with baked-in nebular, as intended.
warnings.filterwarnings("ignore", message=".*wNE.*")
import time
from pathlib import Path
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
import tengri
from tengri import (
builders,
Data,
DEFAULT,
Fixed,
ForwardModel,
FREE,
Observation,
plot,
SEDModel,
Spectroscopy,
Uniform,
)
plot.setup_style()
C_POST, C_TRUTH, C_DATA = "#3a76d9", "0.15", "#c3372a"
Stellar library and observation¶
An SDSS-like R≈2000 optical spectrum (3800–9200 Å observed, which is rest-frame 3620–8760 Å at z = 0.05). The spectrum covers the 4000 Å break, Hβ, Mgb, the Fe blends, Hα, and the Ca II triplet, sampled at 260 pixels to keep the demo fast. The FSPS grid has nebular emission baked into the templates at fixed ionization and escape fraction.
[2]:
SSP_NAME = "prsc_miles_chabrier_wNE"
ssp = tengri.load_ssp(SSP_NAME, download=True)
Z_GAL = 0.05
WAVE_OBS = jnp.linspace(3800.0, 9200.0, 260) # SDSS spectral coverage
obs = Observation(spectroscopy=Spectroscopy(wave_obs=WAVE_OBS, resolution=2000))
Build the model¶
Truncated-skew-normal SFH (normalization plus two timescales free; skew and truncation fixed), free stellar metallicity, and two dust optical depths. This is the same physics as notebooks 05 and 07, so the three are comparable.
[3]:
sed_model = SEDModel.build(
ssp_data=ssp,
observation=obs,
sfh=builders.sfh.tsnorm(
all_params=Fixed(DEFAULT), log_total_mass=FREE, peak_lbt_frac=FREE, width_gyr=FREE
),
dust_attenuation=builders.dust.two_component(
all_params=Fixed(DEFAULT),
law="calzetti",
tau_bc=Uniform(0.0, 1.0),
tau_diff=Uniform(0.0, 1.0),
),
neb={"type": "ssp"},
met={"logzsol": Uniform(-1.5, 0.3)},
redshift=Fixed(Z_GAL),
)
forward = ForwardModel.build(sed=sed_model)
print(f"Free parameters ({sed_model.spec.n_free}): {', '.join(sed_model.spec.free_params)}")
src/tengri/forward/sed_model.py:14707: YoungTopMetallicityWarning: met_logzsol reaches Z = 0.0565 (its upper bound, Z = 0.0283, plus 3 x the metallicity-scatter upper bound of 0.1 dex that the scatter kernel spans), above Z = 0.0497, where the metallicity weights start to use the Z = 0.0600 node of this SSP grid (its highest complete node is Z = 0.0400). The Z = 0.0600 node has no stars above ~12 Msun for log10(age/yr) <= 7.15: FSPS ISOCHRONES/PARSEC/isoc_z0.0600.dat: Mini capped at 12.01 Msun for every log age 5.50-7.15 (343 rows at 5.50; isoc_z0.0200.dat reaches 300 Msun); the PARSEC massive-star tracks stop at Z = 0.04 (Chen et al. 2015, MNRAS 452, 1068). The metallicity is therefore held at Z = 0.0400 for log10(age/yr) <= 7.15, and the top node's weight rises linearly with log age to 1 at 7.20; older populations use the top node unchanged. To use a MIST [Z/H] = +0.5 node (FSPS zlegend Z = 0.0449) at young ages instead, load the grid with top_z='mist': tengri.load_ssp(<name>, top_z='mist') or load_ssp_data(<path>, top_z='mist'). That node has MIST isochrones, so between Z = 0.0400 and 0.0449 the young population switches isochrone physics, not only metallicity.
return cls(
Free parameters (6): dust_tau_bc, dust_tau_diff, met_logzsol, sfh_tsnorm_log_total_mass, sfh_tsnorm_peak_lbt_frac, sfh_tsnorm_width_gyr
src/tengri/forward/sed_model.py:14707: SFHBeyondOldestTemplateWarning: The SSP grid's oldest template is 12.589 Gyr but the universe is 13.090 Gyr old at redshift 0.05. Stars formed in that gap are older than every template, so both age kernels assign them to the oldest one: the formed mass is conserved, and those stars carry the colors of a 12.589 Gyr population. Use a grid whose oldest template reaches 13.090 Gyr (e.g. MIST) to remove the approximation.
return cls(
Mock observation¶
Truth with an interior metallicity; one noisy realization at S/N = 30 per pixel.
[4]:
truth = sed_model.spec.sample(jax.random.PRNGKey(0))
truth = {
**truth,
"met_logzsol": jnp.array(-0.30),
"dust_tau_bc": jnp.array(0.30),
"dust_tau_diff": jnp.array(0.25),
"sfh_tsnorm_log_total_mass": jnp.array(10.5),
}
truth = {k: float(v) for k, v in truth.items()}
p_spec = np.asarray(sed_model.predict_spectrum(truth, wave_obs=WAVE_OBS))
noise = p_spec / 30.0
flux = p_spec + np.random.default_rng(0).normal(size=p_spec.shape) * noise
wave_um = np.asarray(WAVE_OBS) / 1e4
print(f"Truth metallicity log(Z/Zsun) = {float(truth['met_logzsol']):+.2f}")
print(f"Mock: {len(flux)}-pixel R=2000 spectrum, SNR = 30/pixel")
Truth metallicity log(Z/Zsun) = -0.30
Mock: 260-pixel R=2000 spectrum, SNR = 30/pixel
Fit¶
Fixed-length Hamiltonian Monte Carlo: four chains, 200 warmup and 300 draws each, 50 leapfrog steps per draw. The sampler is preconditioned with the model’s curvature at the best-fit point, which enables a short trajectory to cross this posterior’s geometry.
[5]:
t0 = time.perf_counter()
posterior = forward.fit(
Data(spectrum=(flux, noise)),
key=jax.random.PRNGKey(1),
verbose=False,
method="mcmc_hmc",
precondition=True,
dense_mass_matrix=False,
n_chains=4,
n_warmup=200,
n_samples=300,
n_leapfrog_steps=50,
profile_mass=False,
)
rhat = posterior.rhat()
rmax = max(float(v) for v in rhat.values())
print(f"{time.perf_counter() - t0:.0f} s max R-hat {rmax:.3f}")
415 s max R-hat 1.015
Recovery: what a spectrum alone pins¶
Metallicity, stellar mass, and the SFH timescales recover tightly. The diffuse dust optical depth is constrained (it shapes the continuum slope), but the birth-cloud component tau_bc stays broad because a spectrum fixes the continuum shape, not the overall dust normalization.
[6]:
params = sed_model.spec.free_params
print(f"{'parameter':<28}{'truth':>9}{'p16':>9}{'p50':>9}{'p84':>9} cover")
print("-" * 66)
n_cov = 0
for p in params:
s = np.asarray(posterior.samples[p])
lo, med, hi = np.percentile(s, [16, 50, 84])
tv = float(truth[p])
ok = lo <= tv <= hi
n_cov += ok
print(f"{p:<28}{tv:>9.3f}{lo:>9.3f}{med:>9.3f}{hi:>9.3f} {'ok' if ok else 'miss'}")
print(f"\n68% coverage: {n_cov}/{len(params)}")
parameter truth p16 p50 p84 cover
------------------------------------------------------------------
dust_tau_bc 0.300 0.176 0.522 0.849 ok
dust_tau_diff 0.250 0.176 0.204 0.230 miss
met_logzsol -0.300 -0.309 -0.246 -0.185 ok
sfh_tsnorm_log_total_mass 10.500 10.505 10.526 10.551 miss
sfh_tsnorm_peak_lbt_frac 0.228 0.235 0.262 0.296 miss
sfh_tsnorm_width_gyr 0.483 0.497 0.779 1.003 miss
68% coverage: 2/6
Posterior SED¶
[7]:
N_DRAW = 60
idx = np.linspace(0, len(next(iter(posterior.samples.values()))) - 1, N_DRAW).astype(int)
draws = [{k: float(v[i]) for k, v in posterior.samples.items()} for i in idx]
spec_draws = np.stack(
[np.asarray(sed_model.predict_spectrum(p, wave_obs=WAVE_OBS)) for p in draws]
)
sp_lo, sp_med, sp_hi = np.percentile(spec_draws, [16, 50, 84], axis=0)
resid = (flux - sp_med) / noise
chi2_dof = float(np.sum(resid**2) / len(resid))
fig = plt.figure(figsize=(9.2, 5.2))
gs = fig.add_gridspec(2, 1, height_ratios=[3, 1], hspace=0.05)
ax, ax_r = fig.add_subplot(gs[0]), fig.add_subplot(gs[1])
ax.plot(wave_um, flux, color=C_DATA, lw=0.6, alpha=0.7, label="observed")
ax.fill_between(wave_um, sp_lo, sp_hi, color=C_POST, alpha=0.35, lw=0, label="posterior 68%")
ax.plot(wave_um, sp_med, color=C_POST, lw=1.0, label="posterior median")
ax.set_ylabel(r"$F_\nu$ [erg s$^{-1}$ cm$^{-2}$ Hz$^{-1}$]")
ax.set_title(rf"Posterior spectrum ($\chi^2/N$ = {chi2_dof:.2f})", fontsize=11)
ax.legend(frameon=False, fontsize=9, loc="upper left")
plt.setp(ax.get_xticklabels(), visible=False)
ax_r.axhspan(-1, 1, alpha=0.08, color="0.5")
ax_r.axhline(0, color="0.4", lw=0.8)
ax_r.plot(wave_um, resid, color=C_DATA, lw=0.5)
ax_r.set_ylim(-3.5, 3.5)
ax_r.set_xlabel(r"observed wavelength [$\mu$m]")
ax_r.set_ylabel(r"$(d-m)/\sigma$")
fig.savefig(FIG_DIR / "06_spectrum_fit.png", dpi=300, bbox_inches="tight")
plt.show()
Corner¶
[8]:
labels = {
"met_logzsol": r"$\log Z/Z_\odot$",
"dust_tau_bc": r"$\tau_{\rm bc}$",
"dust_tau_diff": r"$\tau_{\rm diff}$",
"sfh_tsnorm_log_total_mass": r"$\log M_\star$",
"sfh_tsnorm_peak_lbt_frac": r"$t_{\rm peak}/t_{\rm age}$",
"sfh_tsnorm_width_gyr": r"$\sigma_t$",
}
fig_corner = posterior.plot_corner(truths=truth, color=C_POST)
for ax_c in fig_corner.axes: # readable axis labels in place of parameter keys
if ax_c.get_xlabel() in labels:
ax_c.set_xlabel(labels[ax_c.get_xlabel()], fontsize=11)
if ax_c.get_ylabel() in labels:
ax_c.set_ylabel(labels[ax_c.get_ylabel()], fontsize=11)
fig_corner.savefig(FIG_DIR / "06_corner.png", dpi=200, bbox_inches="tight")
plt.show()
Summary¶
The fit takes about 400 seconds on a laptop CPU, with max R-hat 1.015. Spectroscopy alone constrains stellar age, metallicity, and mass sharply from the absorption features, but dust normalization remains loose. `07_joint_photo_spec <07_joint_photo_spec.ipynb>`__ adds broadband photometry, which fixes dust and tightens convergence.