Core API

The core classes that form tengri’s high-level interface: defining models, specifying parameters, generating predictions, and creating mock data.

ForwardModel is the outer shell and the surface inference consumes; the SEDModel you build is what goes inside it. Build the SED chain, wrap it, fit it.

Forward model

class tengri.ForwardModel(populations: tuple[Population, ...], observation: Any, mode: str = 'single')[source]

Bases: object

The outer shell of the forward model, and the surface inference consumes.

Holds one or more populations plus an observation, and exposes .predict(params) as the single API every inference backend talks to. A backend never has to ask which channels exist, the returned dict says so, which is what lets one Fitter drive photometry, spectroscopy, joint, and hierarchical fits without branching.

Build the SED chain, wrap it, fit it. fit() is the canonical entry point for inference (issue #211); it is exactly Fitter(self, data, noise).run(method).

Parameters:
  • populations (tuple of Population) – One or more populations. Each carries an SED SubModel and optionally a spatial SubModel. Names must be distinct.

  • observation (object) – Observation model exposing predict(state, params) -> dict (single-population) and predict_summed(per_pop_states, params) (multi-population).

Notes

Construction. Prefer build() over the raw constructor, it accepts the sed= / population= / populations= forms and wraps them into the uniform populations tuple for you.

Parameter names. Single-population fits use flat names (sfh_dpl_alpha, dust_tau_v). Multi-population decompositions namespace by population, <population>.<component_prefix>_<param>, disc.sfh_dpl_alpha, bulge.dust_tau_v, so three stellar components in three populations no longer collide (ADR-0012).

JIT. predict and the channel-specific predict_photometry / predict_spectrum are traced by the inference backends under jax.jit. Prefer predict_photometry() on the fitting hot path; predict_observables() returns the full dict and bypasses the photometry lookup table.

See also

build

construct one, the recommended path.

fit

run inference; the canonical entry point.

tengri.SEDModel

the SED physics chain that goes inside a population.

tengri.Fitter

the inference engine fit() delegates to.

Examples

Wrap an SED chain and fit photometry:

>>> from tengri import ForwardModel, SEDModel
>>> sed = SEDModel.build(ssp_data=ssp, observation=obs, **config)
>>> forward = ForwardModel.build(sed=sed, observation=obs)
>>> result = forward.fit(flux, noise, method="mcmc_nuts")
>>> result.properties["stellar_mass"].shape
(4000,)

Hierarchical fit over a population sharing PSD hyperparameters:

>>> pop = PopulationSEDModel(
...     sed=sed,
...     galaxies=galaxies,
...     shared=("sfh_field_psd_sigma", "sfh_field_psd_tau_myr"),
... )
>>> forward = ForwardModel.build(population=pop, observation=obs)
>>> result = forward.fit(method="vi")
property approx

The effective approximation state of the wrapped SED.

Delegates to SEDModel.approx, so the question “is a LUT live?” has one spelling and one answer whether it is asked of a SEDModel or of the ForwardModel wrapping it. Reaching past this for an inner attribute (model._approx) reads a detail the wrapper does not carry and silently reports “exact”.

Returns:

Frozen summary of the active LUTs; falsy for an exact model.

Return type:

ApproxState

property approx_configs: tuple

The wrapped SED’s active precompute configs, in approx= form.

Delegates to SEDModel.approx_configs for the same reason approx does: one spelling, one answer, whether asked of the SED or of the wrapper. Lets a caller add a LUT family without discarding another’s settings.

Returns:

Active config objects; empty for an exact model.

Return type:

tuple

property available_properties

Derived-property catalog of the inner SED. Delegated (#1300).

band_table_decline(name: str, slot: str)[source]

The wrapped SED’s recorded refusal of one slot, or None.

classmethod build(*, sed: Any | None = None, spatial: Any | None = None, population: Any | None = None, populations: Iterable[Population] | None = None, mode: str | None = None, observation: Any | None = None, approx: Any | None = None) → ForwardModel[source]

Construct a ForwardModel.

Three forms:

  • Single-population sugar (the common case): pass sed=<SEDModel> and observation=<Observation>, optionally spatial=<SpatialModel>. They are wrapped into a one-element populations tuple with name="default".

  • Hierarchical population: pass population=<PopulationSEDModel> for a hierarchical fit across many galaxies sharing some parameters (e.g. PSD). The PopulationSEDModel holds the SED template, the per-galaxy data, the names of shared parameters, and their priors. Inference goes through the standard Fitter(forward, ...).run('vi') path; the Fitter routes to the hierarchical machinery when it detects a PopulationSEDModel.

  • Multi-population explicit: pass populations=[...] for galaxy decompositions (AGN + bulge + disc, ADR-0012). Names must be unique and must not contain ..

Parameters:
  • sed (SEDModel or SubModel, optional) – Single-population shortcut. Mutually exclusive with population and populations.

  • spatial (SpatialModel or SubModel, optional) – Single-population spatial side. Only valid when sed= is also given.

  • population (PopulationSEDModel or SubModel, optional) – Hierarchical-population shortcut. Mutually exclusive with sed and populations. The PopulationSEDModel is held inside Population(name="default", sed=population); the outer-shell signature stays uniform.

  • populations (iterable of Population, optional) – Explicit population list for galaxy decompositions. Mutually exclusive with sed and population.

  • observation (object, optional) – Observation model. Inherited from sed when omitted.

  • approx (WavePrecomp or SpectrumPrecomp or FeaturePrecomp or tuple, optional) – LUT policy, built against the authoritative observation (spec §5, #1367). Same grammar as SEDModel.build(approx=...). Reuse-on-match: a sed already carrying exactly this LUT against the same filters is used as-is; a different-filter LUT is rebuilt (superseding the mismatch guard below, the rebuild is the guard’s own suggested remedy); no LUT → built. Only valid with the sed= form; None (default) leaves the sed untouched.

Return type:

ForwardModel

Raises:

ValueError – If construction doesn’t get exactly one of sed, population, or populations; if spatial= is given without sed=; or if populations contains duplicate names.

compile_signature()[source]

Structural signature of the inner SED (used for JIT cache keys).

property dl_cm_fixed

Fixed luminosity distance [cm], or None, delegated from the inner SED.

fit(data: Any = None, noise: Any = None, method: str = 'mcmc_nuts_fast', *, approx: Any = 'auto', key: Any = None, params: dict[str, Any] | None = None, **kwargs: Any)[source]

Run inference. Canonical convenience entry point.

Equivalent to Fitter(self, data, noise, approx=approx).run(method, **kwargs), wires the standard inference pipeline through the ForwardModel exactly as the architecture spec prescribes (‘inference is always through ForwardModel’, issue #211).

Parameters:
  • data (array_like or Data, optional) – Observed flux (photometry / spectroscopy) or a Data record. Optional for hierarchical fits where the per-galaxy data lives on the PopulationSEDModel.

  • noise (array, optional) – 1-sigma uncertainties matching data. Must be None if data is a Data record.

  • method (str, default "mcmc_nuts_fast") – Inference method. Any value accepted by Fitter.run() ("vi", "mcmc_nuts", "map", …).

  • approx ({“auto”, None} or WavePrecomp or SpectrumPrecomp or tuple, default "auto") – Approximation policy for the fit. "auto" (default) routes the fit through the fast precompute LUT selected by data type (WavePrecomp for photometry, SpectrumPrecomp for spectroscopy/joint, plus FeaturePrecomp when emission lines are fit); None forces the exact wave-grid path; an explicit config (or tuple) overrides. Model prediction stays exact regardless; only the fit is accelerated. The user’s model object is left unchanged; the returned posterior references the fit clone.

  • key (jax.random.PRNGKey, optional) – Inference seed.

  • params (dict, optional) – Per-fit parameter override dict. Keys that name fixed parameters (not free) will override their values for this fit only; the model object is left unchanged. Useful for catalog-fitting with per-galaxy fixed values (e.g. params={"redshift": z_i}). Keys must name valid parameters (raise ValueError if not); keys naming free parameters raise ValueError (you cannot pin a parameter being fit). Default None (no override).

  • **kwargs (Any) – Forwarded to Fitter.run() (e.g. prewarm=, JIT-compile the loss/sampler/predict surface before the fit loop, default True).

Returns:

Same return as Fitter.run().

Return type:

Posterior

Notes

Prefer this entry over SEDModel.fit() for new code. Fitter(forward, data, noise).run(method) remains the low-level path; forward.fit(...) is just the shortcut.

property has_fixedz_photometry_precompute: bool

Fast-path eligibility, delegated from the inner SED (#620).

line_model_sigma_frac(target_wavelengths, **kwargs)[source]

Delegate to SEDModel.line_model_sigma_frac() on the inner SED.

Without this, a Fitter built on a ForwardModel would find no model error and silently score line fluxes as if the nebular model were exact (#2941).

measure_line_fluxes(*args, **kwargs)

Delegated to the inner SEDModel’s measure_line_fluxes (#1300).

The inference stack calls this on fitter.model, which is a ForwardModel on the canonical path. Raises for multi-population forwards rather than answering for an arbitrary population.

mock(*args, **kwargs)

Delegated to the inner SEDModel’s mock (#1300).

The inference stack calls this on fitter.model, which is a ForwardModel on the canonical path. Raises for multi-population forwards rather than answering for an arbitrary population.

mode: str = 'single'
property n_grid

PSD-grid resolution, or 0, delegated from the inner SED.

name(*args, **kwargs)

Delegated to the inner SEDModel’s name (#1300).

The inference stack calls this on fitter.model, which is a ForwardModel on the canonical path. Raises for multi-population forwards rather than answering for an arbitrary population.

observation: Any
populations: tuple[Population, ...]
predict(params: Mapping[str, Any]) → Any[source]

Lazy Prediction for derived quantities.

Symmetric with SEDModel.predict(). Delegates to the inner SED’s predict, so the rich attribute groups (.sfh, .sed, .lines, .radio, .xray, .ionizing, .photometry(), .spectrum(), .magnitudes()) are available directly on a ForwardModel.

For the JIT-safe channel dict consumed by the inference path (loss functions, Observation.predict_summed, fiber_spectroscopy), use predict_observables() instead, that’s the path the Fitter dispatches into.

Parameters:

params (mapping of str -> array) – Free parameter values. Single-population fits use bare names ("sfh_dpl_alpha").

Returns:

Lazy caching wrapper with .sfh, .sed, .lines, .radio, .xray, .ionizing, .photometry(), .spectrum, and .magnitudes property groups.

Return type:

Prediction

Raises:

NotImplementedError – For multi-population forward models. Prediction is a single-population shape; explicit galaxy decompositions (AGN + bulge + disc) should iterate populations and call .predict on each, or use predict_observables() for the combined channel dict.

Notes

JIT-compatible: no, Prediction uses Python-side caching. Use predict_observables() inside JIT.

predict_line_fluxes(params, target_wavelengths=None, **kwargs)[source]

Delegate to SEDModel.predict_line_fluxes() on the inner SED.

Forwards **kwargs (tolerance_aa, the shared-forward state=) so the joint-loss fast path works on the ForwardModel path.

predict_line_ratios(params, line_ratio_data, **kwargs)[source]

Delegate to SEDModel.predict_line_ratios() on the inner SED.

predict_observables(params: Mapping[str, Array], *, ssp_data=None, template_data=None) → Mapping[str, Array][source]

Predicted observables for the given parameters.

Per-population orchestration (architecture spec §9.1):

  1. For each population, slice params by namespace ("<name>.<key>" → "<key>"; bare names like redshift pass through to all populations).

  2. Merge the population’s fixed-parameter values.

  3. Run pop.sed.run(state, full_params) then pop.spatial.run(state, full_params) if present.

  4. Hand all per-population states to the observation.

For a single-population fit, the observation receives the one state via observation.predict(state, params). For multi-population, the observation receives the dict of states via observation.predict_summed(per_pop_states, params), falling back to a default sum if the observation does not provide predict_summed.

Cross-population reads (a component in one population reading a derived key published by another) are supported by copying each population’s typed derived bundle into every other population’s state under the namespaced key ("agn.L_bolometric", etc.) before the next sub-model runs.

Parameters:

params (mapping of str -> array) – Free parameter values. Single-population fits use bare names ("sfh_dpl_alpha"); multi-population fits use namespaced names ("disc.sfh_dpl_alpha").

Returns:

Prediction dict, keyed by observation channel.

Return type:

mapping of str -> array

predict_observables_jit(*args, **kwargs)

Delegated to the inner SEDModel’s predict_observables_jit (#1300).

The inference stack calls this on fitter.model, which is a ForwardModel on the canonical path. Raises for multi-population forwards rather than answering for an arbitrary population.

predict_photometry(params, *, ssp_data=None, template_data=None)[source]

Channel-specific prediction: phot_fnu extracted from predict_observables().

Single-galaxy fits return shape (n_filters,); hierarchical fits (PopulationSEDModel) return shape (N_gal, n_filters). The Fitter’s legacy loss_fn calls this directly; providing it on ForwardModel ensures the batched output flows through rather than reaching for the inner scalar SED.

Parameters:
  • params (Mapping) – Free-parameter dict.

  • ssp_data (Any | None, keyword-only, optional) – The JIT-threading channel, see SEDModel.predict_photometry(). Pass these only when wrapping this method in your own JAX transform; None (default) uses the model’s own arrays, which is correct for every ordinary call.

  • template_data (Any | None, keyword-only, optional) – The JIT-threading channel, see SEDModel.predict_photometry(). Pass these only when wrapping this method in your own JAX transform; None (default) uses the model’s own arrays, which is correct for every ordinary call.

predict_properties(*args, **kwargs)

Delegated to the inner SEDModel’s predict_properties (#1300).

The inference stack calls this on fitter.model, which is a ForwardModel on the canonical path. Raises for multi-population forwards rather than answering for an arbitrary population.

predict_sfh(params, *args, **kwargs)[source]

Delegate to SEDModel.predict_sfh() on the inner SED.

predict_spectral_indices(params, index_defs, **kwargs)[source]

Delegate to SEDModel.predict_spectral_indices() on the inner SED.

predict_spectrum(params, wave_obs=None, wave_chunk_size=None, *, ssp_data=None, template_data=None)[source]

Channel-specific prediction: spec_fnu extracted from predict_observables().

Symmetric with predict_photometry(). Routing the default (no explicit wave_obs/wave_chunk_size) spectrum call through predict_observables() keeps the standardized forward seam: single-galaxy fits return shape (n_pix,) and hierarchical fits (PopulationSEDModel) return (N_gal, n_pix), the per-galaxy batching and the spectrum projection are vmapped below this method (see _predict_observation()). The previous delegation to the inner scalar SED bypassed the population vmap, so stacked per-galaxy SFH params collided with the age grid (suchethac/tengri#711, Gap 2).

An explicit wave_obs/wave_chunk_size (interactive plotting on a custom grid) still delegates to the inner SED, which evaluates the SED on the requested grid (suchethac/tengri#707).

ssp_data/template_data are the JIT-threading channel, see SEDModel.predict_photometry() (#1753).

predict_state(params, fixed_values=None, ssp_data=None, template_data=None, *, observables_only=False)[source]

Delegate to SEDModel.predict_state() on the inner SED.

The three optional positional arguments are the JIT-threading channel: when the loss builder has them, it passes the SSP grid and template arrays in rather than letting the forward close over them, which keeps them out of the compiled program as constants. observables_only is the publication-shortcut opt-in; see SEDModel.predict_state(). Defaulting it to False here means a delegated call cannot lose a published SED by omission (#1673).

This signature must track SEDModel.predict_state(). It previously took params only, so the threaded feature-channel call raised TypeError here, invisible, because the caller only reached this branch when _jit_inputs was populated, and a missing ssp_data delegation meant it never was. Two omissions masking each other.

prewarm(*, data_shape=None, method: str = 'mcmc_nuts', **kwargs)[source]

Pre-compile the JIT kernels for method against this model’s shape.

After this returns, a subsequent fit() call with the same method skips XLA compilation. It still runs its own sampler warmup adaptation on the real data: the dummy (zeros) data used here would give a meaningless step size / mass matrix, so that adaptation is discarded and only the value-independent compile is kept.

Parameters:
  • data_shape (tuple of int or None, optional) – Shape of the data to pre-warm against. If None, uses the observation’s photometry shape. Dummy data (zeros) of this shape are created internally, pre-warm is value-independent and only needs the compile signature (shape, filters, wavelengths, etc.).

  • method (str, default "mcmc_nuts") – Inference method to pre-warm. Any name accepted by fit().

  • **kwargs – Forwarded to the underlying Fitter.prewarm() call (e.g. n_chains=4 for multichain compilation).

Return type:

None

Notes

Pre-warm is idempotent, a second call with the same method is a fast no-op, reusing the compiled kernels from the first call. The persistent XLA cache (~/.cache/tengri_jax_cache) also captures the compile, so a fresh Python process sees a warm XLA cache too.

See also

Fitter.prewarm

Low-level pre-warm interface

Examples

>>> fwd = ForwardModel.build(sed=sed, observation=obs)
>>> fwd.prewarm(method="mcmc_nuts", n_chains=4)
>>> posterior = fwd.fit(flux, flux_err, method="mcmc_nuts", n_chains=4)
record_decline(name: str, slot: str, reason: str)[source]

Record a table gate’s refusal on the wrapped SED’s one memo.

Delegates to SEDModel.record_decline(); approx='auto' records the FeaturePrecomp refusal through here when the model it was handed is a ForwardModel.

property spec

The Parameters-shaped spec the Fitter consumes.

Delegates to self.populations[0].sed.spec. For single- galaxy fits, that’s the SEDModel’s scalar spec; for hierarchical fits (PopulationSEDModel), it’s the batched PopulationSpecView (see PR #241). The Fitter sees the same Protocol surface either way and doesn’t need to know which.

Notes

For multi-population galaxy decompositions (ADR-0012), this returns the first population’s spec, those fits use namespaced parameter names and have their own conventions handled elsewhere in the pipeline.

property ssp_data

SSP grid of the inner SED. Delegated.

A property, not one of the auto-installed method delegations: callers read model.ssp_data as an attribute, so installing it via _install_inner_sed_delegations() would hand them a bound method and thread that instead of the grid.

Load-bearing for JIT data threading. Fitter._build_data_args reads this to populate data_args["_jit_inputs"], and did so inside a contextlib.suppress(AttributeError, TypeError). While this property was missing, that read raised, the suppress swallowed it, and the whole _jit_inputs assignment was skipped, so the SSP grid closure-captured into every compiled loss on the canonical inference surface. On a real grid (15x93x5994 float64) it inlined twice as hex, 267.6 MB of a 274.6 MB program, and XLA compilation was OOM-killed. Guarded by tests/contract/test_loss_ssp_threading.py.

threaded_template_inputs(*args, **kwargs)

Delegated to the inner SEDModel’s threaded_template_inputs (#1300).

The inference stack calls this on fitter.model, which is a ForwardModel on the canonical path. Raises for multi-population forwards rather than answering for an arbitrary population.

property uses_stochastic_sfh: bool

Stochastic-SFH flag delegated from the inner SED.

property wave_obs

Observed-frame spectroscopy wavelength grid, or None.

Delegates to the first population’s inner SED, single-population and hierarchical fits share one spectroscopy grid across the channel. Migration 2 step 1 promotes this from the legacy __getattr__ fall-through to a first-class property.

property wavelengths

Rest-frame wavelength grid delegated from the inner SED.

with_approx(approx)[source]

Return a copy of this forward model with a different approx policy.

Clones the wrapped SED via SEDModel.with_approx() and re-wraps it, preserving the observation. Only the common single-population, SED-only forward is cloned; multi-population, spatial, and hierarchical (PopulationSEDModel) forwards are returned unchanged, as is any request that resolves to a no-op.

Parameters:

approx (WavePrecomp or SpectrumPrecomp or FeaturePrecomp or tuple or None) – Approximation policy for the clone (same grammar as approx= on SEDModel).

Returns:

A new forward model on the requested approximation path, or self when the request is a no-op or the topology is not a plain single-population SED forward.

Return type:

ForwardModel

with_fixed_redshift(redshift)[source]

Return a copy of this forward model built at a different Fixed redshift.

Rebuilds the SED of every population via SEDModel.with_fixed_redshift() (which rebuilds each redshift-dependent table) and re-wraps them with the same population names, spatial submodels, observation and mode. A bare redshift is the galaxy’s redshift and flows to every population (see predict_observables()), so the rebuild pins all of them.

Parameters:

redshift (float) – The new constant redshift.

Returns:

The rebuilt forward model, or self when every population is already at that redshift.

Return type:

ForwardModel

Raises:

tengri.config.exceptions.ParameterError – If any population’s redshift is free: a free redshift is fit, not pinned, so an override cannot address it and the galaxy would have populations at different redshifts.

Notes

Hierarchical populations rebuild their template SED and keep the galaxies, shared names, priors and data type. Spatial submodels are kept as they are: they describe a profile in physical kpc and read no redshift.

with_runtime_redshift(z_range=None)[source]

Return a copy whose populations all read redshift at call time (#3505).

Promotes the SED of every population via SEDModel.with_runtime_redshift() and re-wraps them as with_fixed_redshift() does, so a bare redshift in params (or the fitter’s per-galaxy value) reaches every population through one path.

Parameters:

z_range (tuple of float or None, optional) – (z_lo, z_hi) table range [dimensionless]. Tabulated populations take it; exact populations have no table and ignore it.

Returns:

The promoted forward model, or self when every population already reads redshift at call time.

Return type:

ForwardModel

Notes

Costs one model construction per population. JIT-compatible after construction.

xi_to_params(xi)[source]

Delegate to SEDModel.xi_to_params() on the inner SED.

property z_fixed

Fixed redshift, or None, delegated from the inner SED.

Population

class tengri.Population(name: str, sed: SubModel, spatial: SubModel | None = None)[source]

Bases: object

One (SED, spatial) pair inside a ForwardModel.

Parameters:
  • name (str) – Population namespace. Used as the outer prefix in parameter names: {name}.{prefix}_{param} (ADR-0012). Must be non-empty and must not contain . (the namespace separator). Convention: use "default" for single-population fits; "agn", "bulge", "disc" for galaxy decompositions.

  • sed (SubModel) – SED SubModel for this population.

  • spatial (SubModel or None, optional) – Spatial SubModel for this population. None for SED-only populations.

name: str
sed: SubModel
spatial: SubModel | None = None

SED model

The predict_* methods that once returned individual observables are superseded by the single cached predict() pass — see Predicting and properties. They still work and still warn, but they are omitted here rather than presented as current API; the migration table in docs/dev/api_migration_v0.x.md maps each one to its replacement.

class tengri.SEDModel(spec, ssp_data, filters=None, observation=None, precompute=<unset>, forward_dtype='float64', approx=None, csp_integration='trapz', wave_chunk_size=None, agn_config=None, strategy=<unset>, compile=None, z_runtime=False)[source]

Bases: object

Differentiable SED forward model with modular physics and clean API.

The forward model maps physical parameters (stellar mass, SFH, metallicity, dust, AGN, etc.) to observables: photometry, spectrum, and derived SED quantities. Internally, it decomposes the SED pipeline into independent physics modules (stellar populations, star formation history, dust, nebular, AGN, IGM) that are composed into prediction kernels at initialization time, enabling fast inference and flexibility in model configuration.

The SFH is computed via a registry-driven composed function that handles additive smooth models, burst mixture, and correlated-field (GP) modulation in a single call. Three prediction modes (compositional, hybrid, exact) trade accuracy for speed, with automatic fallback.

Parameters:
  • spec (Parameters) – Parameter specification from tengri.Parameters. Defines free/fixed parameters and their priors.

  • ssp_data (SSPData) – Pre-loaded SSP templates (from load_ssp_data()). Contains absolute SSP grid in log10(Z) absolute, age array, and optional mass-remaining tables for stellar mass surviving constraints.

  • filters (list or tuple, optional) –

    Filter transmission curves for photometric prediction. Accepts either:

    If provided, enables photometry prediction and automatic precomputation at initialization. Either filters or observation may be passed, not both.

  • observation (Observation, optional) – Unified observation config (photometry + spectroscopy + emission lines). Mutually exclusive with filters.

  • precompute (bool, optional) – Legacy / largely superseded. Builds the pre-approx=-era PrecomputedData container (fixed-z SSP photometry/spectroscopy grid defaults). This predates (and is NOT) the fast LUT path: the Zacharegkas+2025 fast-photometry / spectroscopy speedup is selected at build time via approx=WavePrecomp() / approx=SpectrumPrecomp() (see approx below), which builds its own LUTs through the component chain and does not consume PrecomputedData. precompute now only supplies a couple of grid fallbacks for the exact path and is scheduled to be folded into approx (tracked in the precompute-naming cleanup issue). Default True; leave it unless you know you need the legacy container. Set False to skip building it.

  • forward_dtype (str or jnp.dtype, optional) –

    Dtype for forward model computation. Default "float64".

    Deprecated since version 2026-07: Retired (#1433). Passing anything but "float64" emits a DeprecationWarning, a warning, not an exception; the call proceeds, and does nothing else. "float32" cast nothing and changed nothing, measured bit-for-bit identical photometry to "float64" on both the exact and the WavePrecomp path. It no longer enters compile_signature() either, so it no longer costs the second compile of an identical kernel that it used to.

    Retired rather than repaired because there is no second float32 mode worth maintaining: pure float32 is what the range protections in components/ gate on, it is what #1206 delivers, and the knob sat dead for two months without a single report. Wiring it instead would mean reviving a distinct mixed-precision path with its own gate semantics and re-earning a speed claim that was never re-measured.

    The casts it names were real until 1e57d973d (2026-05-20) deleted forward/_kernels/; the kwarg, this docstring, the state field and the signature entry survived that refactor, and the six casts did not. This description previously promised “halves memory and gives ~1.5x speedup with <0.1% accuracy loss”, none of which has held since.

    For float32 today use pure float32: enter a jax.enable_x64(False) context. That is a different mechanism (it changes JAX’s default dtype rather than casting captured arrays), it is the mode the float32 range protections in components/ gate on, and it is the one #1206 is making work end to end.

    The argument is still accepted so that existing callers keep working, nothing they compute was ever different, and it will be removed once the warning has been in a release.

    Independently of this knob, the multiplicative flux/distance seams (photometry, spectrum, line flux projections) apply cosmological factors as range-safe log offsets (see tengri.utils.scale), so float32 arrays do not materialize out-of-range intermediates there.

  • approx (dict or bool, optional) –

    Control which approximations enter the component chain. Default True enables all approximations (fastest). False disables all (forces exact path everywhere). A dict enables selective control:

    • "ztable": SSP × filter lookup table indexed on redshift grid (True, default)

    • "wave_precomp": SSP × filter lookup table on fixed wavelength grid (False, default)

    Approximation dependencies (resolved at build time):

    • wave_precomp=True with free redshift auto-enables ztable=True.

    • ztable=True requires wave_precomp=True.

    • Unknown flag names raise ValueError with list of legal flags.

  • compile (str, optional) –

    JIT-wrapping strategy for the forward pass. Default "per_component" wraps each SEDComponent.apply independently for faster cold-starts in notebooks; "fused" compiles the entire observation.predict ∘ run_components chain at once for hot inference loops; "auto" is a stub that currently resolves to "per_component".

    Legal values: "per_component" (default), "fused", "auto". Invalid values raise ValueError.

  • csp_integration (str, optional) –

    Deprecated and inert (#1500); accepted so existing calls keep working, and slated for removal in v1.0. Any non-default value raises a DeprecationWarning. Accepted: "trapz" (default), "log_trapz", "log_interp", "dsps_native", "dsps_met_table".

    Warning

    No value changes any output. The stellar component integrates the CSP with the age-weight kernel named by sfh={'age_kernel': ...} (components/stellar/component.py), which this argument does not feed, so it never reached the SED under any configuration. predict_photometry is bit-identical across all five values; measured, not assumed.

    It formerly changed _predict_sfh_quantities alone, which meant the reported stellar mass came from a different integration than the spectrum it was fitted to: 0.32% off for "log_interp" and "dsps_native", and NaN for "dsps_met_table", a NaN that Posterior then vmapped over every sample. Derived quantities are now computed from the SED’s own age weights, so every value agrees to machine precision.

    The age-weight kernel that does reach the CSP is sfh={'age_kernel': 'cic' | 'dsps'} (#964); since #2683 both names select the same integration, so it moves no output either. tengri.list_age_kernels() is the live menu.

Variables:
  • observation (Observation or None) – Attached observation object containing photometry and/or spectroscopy configuration. Set by constructor if filters or observation= passed.

  • spec (Parameters) – Parameter specification defining all free/fixed parameters and their priors.

  • ssp_data (SSPData) – Pre-loaded stellar population synthesis templates (from load_ssp_data()).

  • config (ModelConfig) – Frozen model configuration (immutable after init).

Notes

JIT-compatible: yes, all prediction methods (except predict() for lazy evaluation) are fully JAX differentiable and can be called inside jax.jit() and jax.vmap().

Gradient-safe: yes, all physical parameters are differentiable for inference via HMC, VI, and score-based methods.

Approximation scheme: All prediction methods route through the single JIT-safe orchestrator predict_observables_jit() (the SSP grid is threaded as a JIT runtime input). Historical mode-cascade strategies (compositional / hybrid / exact) collapsed into this one path in 2026-05; the orchestrator itself remains XLA-fused and bit-exact for the configured approx= policy.

Physical units (internal):

  • Time: years (yr). User-facing API converts to Myr/Gyr.

  • Wavelength: Angstrom (Å).

  • Luminosity (SED components): erg/s/Hz (L_ν).

  • Luminosity (photometry): erg/s/cm²/Hz (f_ν).

  • Metallicity (SSP grid): log₁₀(Z) absolute. User API uses log₁₀(Z/Z☉).

  • AGN bolometric luminosity: log₁₀(L_bol/L☉) at API level.

IGM absorption gotcha: predict_obs_sed() applies IGM transmission at observed-frame wavelengths (input to igm_transmission() is redshifted). This is automatic when igm=True in spec.

References

[tengri.SEDModel-1]

A. Zacharegkas et al., “Fast Photometry with Precomputed Stellar Population Grids,” ApJ, (2025).

[tengri.SEDModel-2]

S. Cooray et al., “Forward Model for Differentiable SED Fitting with Correlated SFH,” (2026).

Examples

Standard photometric fit with DPL SFH:

from tengri import SEDModel, Parameters, Uniform, load_ssp_data, Photometry

ssp = load_ssp_data("data/ssp_miles.h5")
phot = Photometry.from_names(["sdss_r", "sdss_i", "sdss_z"])
spec = Parameters(
    redshift=0.1,
    sfh_dpl_alpha=Uniform(0.5, 4.0),
    sfh_dpl_beta=Uniform(0.3, 3.0),
)
model = SEDModel(spec, ssp, observation=phot)
property Observables: type

Return the per-model Observables NamedTuple class.

Returns:

A typing.NamedTuple subclass whose fields match the configured observation sub-blocks. Synthesized at construction time by build_observables_class().

Return type:

type

Raises:

ValueError – If no observation is configured.

Notes

Each model gets its own NamedTuple class, with fields (and magnitude properties) appearing only when the corresponding observation sub-block is configured.

property approx: ApproxState

The effective approximation state of this model.

Answers “is a build-time look-up table live on this model?”, the same question, spelled the same way, on ForwardModel.

Returns:

Frozen summary of the LUTs that resolved and activated. Falsy for an exact wave-grid model.

Return type:

ApproxState

Examples

>>> model.approx.wave_precomp
True
>>> if not model.approx:
...     ...  # exact path

Notes

Reads the same lowered _approx flags the forward pipeline itself consumes, so it reports what the code does, not what was requested: a SpectrumPrecomp that fell back to the exact path reports spectrum_precomp=False. Deriving it from any other source would make this a third spelling of the question and free it to drift.

Not JIT-relevant: Python-side introspection, never traced.

property approx_configs: tuple

The config objects currently active, in approx= tuple form.

Companion to approx, which reports whether each LUT is live as booleans. This returns the configs themselves, so a caller can add one family without discarding another’s settings, rebuilding from WavePrecomp() because approx.wave_precomp was True would silently drop a configured catalog_z_range, which is a behavioral change wearing a speedup’s clothes.

Returns:

Active configs (WavePrecomp / SpectrumPrecomp / FeaturePrecomp), suitable to pass straight back to with_approx(). Empty for an exact model.

Return type:

tuple

property available_properties: tuple[str, ...]

Names of all properties available for this model.

Returns:

Sorted tuple of property names that can be queried via predict_properties() or accessed as attributes on a Prediction object.

Return type:

tuple[str, …]

Raises:

ValueError – If two active components declare the same property name. Each property can be owned by at most one active component.

Notes

This property triggers assembly of the property catalog on first access and caches the result in _property_catalog for subsequent calls. The collision check runs at this point.

Examples

>>> model = SEDModel.build(...)
>>> model.available_properties
('stellar_mass', 'stellar_mass_surviving', 'sfr_10myr', ...)
band_table(name: str, slot: str) → BandTable | None[source]

Return the built band table of one component slot.

Parameters:
  • name (str) – Component name, a key of BAND_TABLE_PROVIDERS.

  • slot (str) – A band-table slot of that component, for example "band_table".

Returns:

The table, or None when the slot was refused or has not been built.

Return type:

BandTable or None

band_table_decline(name: str, slot: str) → Decline | None[source]

Return the refusal of one component slot.

Parameters:
  • name (str) – Component name, a key of BAND_TABLE_PROVIDERS.

  • slot (str) – A band-table slot of that component, for example "band_table".

Returns:

The refusal with its reason, or None when the slot built a table or was never built.

Return type:

Decline or None

classmethod build(ssp_data, *, sfh=None, met=None, dust_attenuation=None, dust_emission=None, neb=None, shock=None, agb_dust=None, agn=None, igm=None, radio=None, xray=None, foreground=None, redshift=None, filters=None, observation=None, **model_kwargs) → SEDModel[source]

Build an SEDModel from the nested-dict grammar.

The primary way to construct a model. Organizes physics components into one dict per block (sfh, dust_attenuation, neb, etc.), each declaring a structural type, which parameters are free, and per-parameter values. Translates this grammar to a Parameters spec via tengri.parse_groups(), then constructs the model.

The grammar has three kinds of keys:

  1. Structural keys configure the component variant and behavior: 'type' (required; e.g., 'type': 'dpl' for SFH), and component-specific settings ('law' for dust, 'norm' for AGN, etc.).

  2. ``’all_params’`` wildcard sets free/fixed status for all parameters in the group not explicitly overridden. Accepts FREE or Fixed(DEFAULT) (default; see Fixed, DEFAULT). The only valid wildcard spelling.

  3. Parameter keys are bare or full-prefixed names that override the wildcard or default. Use short forms ('beta' in sfh, 'tau_bc' in dust) for readability.

Core groups with defaults: sfh, met, dust_attenuation, dust_emission, redshift.

Optional groups (OFF by default): neb, shock, agn, igm, radio, xray, foreground. Activate by providing a dict with 'type'; omit or pass {'type': 'none'} to keep off.

Parameters:
  • ssp_data (SSPData) – Pre-loaded SSP grid (from load_ssp_data()).

  • sfh (dict, optional) – Star-formation history. Keys: 'type' (required; e.g., 'dpl', 'delayed_tau', 'field'), 'age_kernel' (‘cic’ or ‘dsps’), 'bin_edges_gyr' (for non-parametric), 'all_params', and per-parameter overrides. Menu: tengri.list_sfh_models().

  • met (dict, optional) – Metallicity mode. Keys: 'type' (required; e.g., 'table', 'ramp'), 'all_params', parameters. Menu: tengri.list_metallicity_modes().

  • dust_attenuation (dict, optional) – Dust attenuation screen. Keys: 'type' (required; 'single_component', 'two_component', 'wg00'), 'law' or 'law_bc'/'law_diff' (required depending on type), 'all_params', parameters. Menu: tengri.list_dust_laws(). On two-component, you must provide either a single 'law' for both screens or both 'law_bc' and 'law_diff'.

  • dust_emission (dict, optional) – Dust infrared emission. Keys: 'type' (required; 'dale2014', 'draine2016', etc.), 'eta_balance', 'all_params', parameters. Menu: tengri.list_dust_emission_models().

  • neb (dict, optional) – Nebular emission. Keys: 'type' (required; 'cue', 'cloudy', 'none'), 'full_catalog', 'grid' (CLOUDY), 'all_params', parameters. Default: off. Menu: tengri.list_nebular_backends(). Metallicity ('logZ_gas' or 'neb_logz') is independent from met=; default is -0.3 (solar).

  • shock (dict, optional) – Shock nebular emission. Keys: 'type' (required; 'mappings', 'none'), 'norm' ('frac', 'lhalpha', 'component'), 'abundance', 'all_params', parameters. Default: off. Composes with neb when both are on.

  • agb_dust (dict, optional) – AGB circumstellar dust-shell weighting (Villaume, Conroy & Johnson 2015). Keys: 'type' (required; 'fsps_shell', 'none'), 'all_params', and 'weight' (agb_dust_weight, dimensionless, default Fixed(1.0) = the weight baked into the shipped FSPS MIST grid, free Uniform(0, 3)). Default: off (grid untouched). Supported only on fsps_mist_* SSP grids.

  • agn (dict, optional) – AGN emission. Keys: 'type' (required; 'composable', 'legacy', 'none'), 'norm' ('cigale_joint' or 'independent'), and six optional sub-blocks ('disc', 'torus', 'nlr', 'blr', 'feii', 'atten'), each with 'type' and parameters. Default: off. Each sub-block follows the same grammar. Menu: tengri.list_agn_models(), tengri.list_agn_blocks().

  • igm (dict, optional) – IGM absorption. Keys: 'type' (required; 'inoue', 'madau', 'meiksin06', 'none'), 'patchy', optional 'dla' sub-block, 'all_params', parameters. Default: off. Menu: tengri.list_igm_models().

  • radio (dict, optional) – Radio emission (star-formation and/or AGN). Keys: 'type' (required; 'sfonly', 'agn', 'sf_agn', 'none'), optional 'sf' and 'agn' sub-blocks, 'all_params', parameters. Default: off. Menu: tengri.list_radio_models().

  • xray (dict, optional) – X-ray emission. Keys: 'type' (required; 'simple', 'yang20', 'lopez24', 'none'), 'all_params', parameters. Default: off. Menu: tengri.list_xray_models().

  • foreground (dict, optional) – Milky Way foreground reddening. Keys: 'ebmv_mw' (E(B-V) in mag), 'law' (dust law; e.g., 'mw_rv31'), 'rv' (RV override). No 'type' (not a registry). Default: off (no foreground reddening).

  • redshift (scalar, Distribution, or sentinel) –

    Source redshift. REQUIRED. Omitting it raises ParameterError. Specify as one of:

    • Fixed(z) for a known redshift (e.g., Fixed(0.05))

    • Uniform(lo, hi) for a photo-z fit

    • A bare scalar (auto-converts to Fixed, e.g., redshift=0.05)

    • Any other Distribution (e.g., Normal(mu, sigma))

    With approx=WavePrecomp(), a free redshift adds ~9 s to the build (for IGM z-table folding); a fixed z adds ~0.4 s. See Compilation: caching and diagnostics.

  • filters (list of str, optional) – Filter names; forwarded to __init__.

  • observation (Observation, optional) – Observation object (photometry, spectroscopy); forwarded to __init__.

  • **model_kwargs – Additional keywords forwarded to __init__() (e.g., approx, precompute). forward_dtype is retired and ignored (#1433).

Returns:

Fully initialized model, equivalent to SEDModel(parse_groups(**groups), ssp_data, ...).

Return type:

SEDModel

Raises:

ParameterError – If redshift is omitted, if unknown group keys are provided, if required structural keys (like 'law' for dust) are missing, or if 'all_params': FREE has no effect.

Notes

Grammar rules:

  • Every group dict must have a 'type' key (except foreground, which has no registry).

  • 'all_params' is the only wildcard. The retired '*' raises TypeError.

  • Parameter names auto-resolve to their full prefixed forms. Short forms ('beta' in sfh, 'tau_bc' in dust) are preferred.

  • Unknown keys raise with suggestions via difflib.

  • A group dict with keys but no 'type' raises.

  • 'all_params': FREE on a group with no free-parameter models raises (e.g., radio={'type': 'sfonly', 'all_params': FREE}). Use explicit priors instead: radio={'q10': Uniform(...)}.

The resolved model configuration can be inspected and edited via:

>>> config = model.spec.to_groups()  # dict with all groups
>>> model.spec.summary()  # print with provenance tags

See also

tengri.parse_groups

The underlying nested-dict parser that returns

a

class:Parameters spec.

tengri.recipes

Pre-built configuration dicts for common cases (star-forming galaxies, AGN, high-z, etc.).

tengri.FREE, tengri.Fixed, tengri.DEFAULT

SEDModel.from_dict

Load a model from a serialized config dict.

SEDModel.from_file

Load a model from a config file (JSON or YAML).

model_configuration

Reference documentation for the grammar.

Examples

Minimal star-forming galaxy (fixed redshift, photometry only):

>>> from tengri import SEDModel, FREE, DEFAULT, Uniform, Fixed
>>> model = SEDModel.build(
...     ssp_data=ssp,
...     sfh={"type": "dpl", "all_params": FREE},
...     dust_attenuation={
...         "type": "two_component",
...         "law": "calzetti",
...         "all_params": Fixed(DEFAULT),
...         "tau_bc": 0.5,
...         "tau_diff": 0.3,
...     },
...     dust_emission={"type": "dale2014", "all_params": Fixed(DEFAULT)},
...     neb={"type": "cue", "all_params": Fixed(DEFAULT)},
...     redshift=Fixed(0.05),
...     filters=["sdss_u", "sdss_g", "sdss_r"],
... )

High-z stochastic SFH with free metallicity and photo-z:

>>> model = SEDModel.build(
...     ssp_data=ssp,
...     sfh={"type": "dpl", "all_params": FREE},
...     met={"type": "ramp", "all_params": FREE},
...     dust_attenuation={
...         "type": "two_component",
...         "law": "calzetti",
...         "tau_bc": Uniform(0, 1),
...         "tau_diff": Uniform(0, 0.5),
...     },
...     neb={"type": "cue", "logZ_gas": Uniform(-1, 0)},
...     redshift=Uniform(2, 4),  # photo-z
...     observation=obs,
... )

Composable AGN with selective freedom:

>>> model = SEDModel.build(
...     ssp_data=ssp,
...     sfh={"type": "dpl", "all_params": Fixed(DEFAULT), "alpha": Uniform(0.5, 3)},
...     agn={
...         "type": "composable",
...         "disc": {"type": "powerlaw", "all_params": Fixed(DEFAULT)},
...         "torus": {"type": "skirtor", "all_params": FREE},
...         "nlr": {"type": "cue", "logZ_gas": -0.3},
...         "norm": "cigale_joint",
...     },
...     igm={"type": "inoue"},
...     redshift=Fixed(0.3),
...     observation=obs,
... )

Recipe + tweak (start with a built-in template, customize):

>>> from tengri import recipes
>>> config = recipes.star_forming_photometry()
>>> config["dust_attenuation"]["tau_bc"] = 0.8  # override default
>>> config["neb"]["logZ_gas"] = Uniform(-0.5, 0)  # photo-z on gas metallicity
>>> model = SEDModel.build(ssp_data=ssp, observation=obs, **config)
compile_signature() → tuple[source]

Return a hashable signature identifying JIT-graph shape and structure.

Two SEDModel instances with the same compile_signature() will produce identical XLA compilation graphs (for identical Fitter configurations), enabling cross-galaxy engine reuse in PopulationFitter and CatalogFitter.

The signature captures every JIT-affecting field: SSP array shapes, filter grid dimensions, dust/AGN/nebular model identities, and all configuration flags that determine the control flow during inference.

Returns:

Hashable immutable signature: (type_qualname, version, entries, tail) from tengri._cache_keys.derive_key. Still a plain hashable, equality-comparable tuple, so everything downstream that treats the signature as an opaque cache key (Fitter._engine_cache_key, the module-level engine cache) is unaffected by this method’s internals.

Return type:

tuple

Notes

Memoized on the instance (self._signature_memo): after the first call, every later call on the SAME model returns the identical object rather than recomputing the ledger. Only two methods change a model’s STRUCTURE after construction – _validate_and_freeze_param_map() and enable_fast_nebular() – and both call _invalidate_signature() to clear the memo. A source-level guard test walks every other SEDModel method that assigns self.<attr> outside a constructor helper and fails if one touches a non-excluded row without also invalidating (tests/contract/test_compile_signature_invariants.py).

The signature is derived from a policy ledger over every model attribute (tengri.forward._signature_policy.SIGNATURE_POLICY), not a hand-written field list. Each attribute is classified as content (hash the value), shape (hash shape+dtype only), or excluded (a memo cache or the runtime state container, both recomputed from already-keyed structure). An attribute the ledger does not classify is a bug, never a hand-edit here: add a row to _signature_policy.py and nothing else changes. tengri._cache_keys.assert_policy_complete fails the day a new, unclassified attribute appears, which is what closes the class of bug that motivated this rewrite – #1122 (n_subbands missing from the hand list), #1462 (seven AGN block selectors missing), #2145 (the SSP metallicity GRID VALUES missing), #2237 (the live dust shape-parameter set missing) – each a field nobody remembered to add, each silently sharing one model’s compiled kernel with a structurally different one.

“Structure” includes precision. The structural-kernel cache in _get_or_build_predict_observables_jit() returns a closure that captured self, so a signature collision hands one model’s compiled kernel (and its wavelength grid) to another. A float64/float32 collision used to reach the components as a float64 wave under jax.enable_x64(False), which switched off every dtype-keyed float32 path downstream and produced NaN gradients with nothing raised (#1392). Precision is a JAX session setting, not a vars(self) attribute, so it rides the tail passed to derive_key (x64, backend) rather than a ledger row.

The spectroscopy projector’s structural axes – resample mode, calibration order, and whether a banded resolution matrix or the Gaussian LSF applies – are exactly the #1135/#1149/#1166 cache-collision class this whole mechanism guards against (two models differing only in one of these must never share a compiled kernel). They are keyed through Spectroscopy.cache_key(), delegated via the observation row below, not re-derived here.

property config: dict

Return the model configuration as a nested-dict (fully resolved).

declared_parameters()[source]

Free-parameter declarations for this SED chain.

Returns:

One entry per free parameter, lifted from self.spec.

Return type:

list of tengri.protocols.ParamDeclaration

Notes

Satisfies tengri.protocols.SubModel.

property dl_cm_fixed

Fixed luminosity distance [cm] when redshift is fixed, else None.

Public accessor for the internal _dl_cm_fixed attribute. Used by inference to detect a redshift-fixed forward model eligible for the fast precomputed-photometry path.

enable_fast_nebular(target_wavelengths, *, n_grid=16, ranges=None)[source]

Attach a per-Q_H nebular grid so lines + photometry skip the Cue forward.

Builds the adaptive-axis nebular grid (precompute_nebular_grid()) from this model, running the Cue forward once per grid point at build time, then attaches it to the nebular component. Afterwards:

  • predict_photometry() reconstructs the nebular broadband contribution as \(Q_H \times \mathrm{interp}(\text{grid})\), and the Cue forward becomes dead for the photometry channel (XLA prunes it);

  • predict_line_fluxes() reconstructs the emission lines the same way.

Both are SED-free in \(Q_H\) (the stellar-published nion). The grid axes are whichever of met_logzsol / neb_logU / neb_logZ_gas are FREE, PLUS neb_logU whenever DIG mixing could be active (neb_dig_frac free, or fixed non-zero, with a non-degenerate DIG-shifted image – #2222), even when neb_logU itself is Fixed; every other fixed ionization param is baked.

Parameters:
  • target_wavelengths (array_like, shape (n_lines,)) – Rest-frame vacuum line wavelengths [Angstrom] the grid tabulates and predict_line_fluxes() serves.

  • n_grid (int or dict, default 16) – Grid points per free ionization axis. Denser → tighter interpolation. A dict {axis_name: n} resolves met_logzsol / neb_logU / neb_logZ_gas independently; omitted axes take 16 and an unrecognized key raises (#1311). Build cost is the product over free axes.

  • ranges (dict, optional) – Override {param: (lo, hi)} grid bounds (defaults to each free param’s prior support). ranges['neb_logU'] is treated as the HII support, not the final axis: whenever DIG mixing could be active it is still extended to cover the DIG-shifted query point (never clipped, never bypassed) – passing the prior support verbatim here no longer disarms the extension (#2222 review I2; before this fix an explicit range silently clipped the DIG lookup, measured 5.4e-2, above this module’s 3e-2 parity ceiling).

Returns:

self (configured in place), for chaining.

Return type:

SEDModel

Raises:

ValueError – If no Q_H-linear nebular backend (Cue) is configured.

Notes

Approximation. Reconstruction is exact at grid nodes and node-exact PCHIP between them. Photometry error stays ~1 % on the total (nebular is subdominant in broadband). Line-flux accuracy depends strongly on which ionization params are free (#950 convergence study):

  • Gas axes (logU + neb_logZ_gas) drive smooth per-Q_H line changes and converge with n_grid.

  • Free ``met_logzsol`` used to be the pathological case, and is no longer. The old text here (retained in spirit because the reasoning is still worth knowing) said the exact Cue forward was discontinuous in metallicity, it took the ionizing-spectrum shape from a single argmax-chosen age bin, so [OIII] stepped ~33 % whenever the dominant bin flipped, and no interpolant crosses a jump: a dense sweep gave [OIII] worst-case ~10-23 % at any n_grid. #1019 removed that argmax. The shape is now a luminosity-additive mix over every ionizing age bin (cue.py), so the forward is smooth in metallicity and the grid converges. Measured on the shipped bare SSP: 0.42 % between nodes, 0.21 % at a node, identical on linux/x86 and macOS/arm64.

Warning

That stale ~10-23 % figure is a trap. It happens to bracket both the 20.9 % photometry and 14.7 % line-flux drifts reported in #1154, so it offers a ready-made (and wrong) explanation for them. It cost a full debugging session. When a number in a docstring matches your bug suspiciously well, check that the mechanism behind it still exists before you believe it: this one was removed by #1019.

Caveat that #1019 introduced. Making the shape a luminosity-weighted mix also made it depend on the SFH, the old argmax forced d(shape)/d(SFH) = 0, and removing it was the point. But the SFH is not a grid axis here (only met_logzsol / logU / neb_logZ_gas are), so L = Q_H * l(...) assumes a shape-independence the exact forward no longer has. Q_H carries the number of ionizing photons, not their hardness. In practice the residual is small (the 0.42 % above is measured across free-SFH draws), but it is an approximation, not an identity.

Validate accuracy with a dense sweep strictly inside the grid range: random parameter draws under-sample structure and report optimistic bounds.

For the photometry channel the model must be built with approx=WavePrecomp() (so the grid can capture the intrinsic filter-integrated nebular L_nu); without it only the line channel is reconstructed and photometry stays on the exact path.

With a free redshift (redshift=Uniform(...)) or a runtime redshift (WavePrecomp(catalog_z_range=...)), the grid serves line fluxes only and band fluxes stay on the exact nebular path. The per-Q_H grid integrates through observed bands at the build redshift; a runtime redshift shifts which filter wavelengths the grid tabulates, introducing worst-case band errors of 7.35e-2 if applied. Constrain redshift to a fixed value to enable grid-served photometry.

Known limitations.

  • When a dust component takes the nebular emission from the grid (has a stellar energy-balance LUT), its dust-channel fields are published: observed and rest-frame sub-band nebular photometry, flux-weighted wavelength, and dust-absorbed nebular luminosity per unit Q_H. Dust components without a stellar energy-balance LUT (free attenuation-curve shape, WG00, or a free redshift with a redshift-reading law) cannot take the nebular from the grid; the grid serves line fluxes only while photometry takes the exact nebular path.

  • The grid applies neb_fesc and neb_fdust_frac at reconstruction (computed per-galaxy from parameters), not at table build (which uses zero for both); every other free nebular parameter held at the build value (neb_fesc_lya, ionspec_*, gas_*, neb_eline_sigma_kms, neb_log_nH, neb_co, neb_dno, neb_hbfrac) is refused by enumeration of the namespace.

  • The grid holds the ionizing spectrum shape at the reference star formation history. For a population with no recent star formation and zero birth-cloud optical depth the u bands were off by 3.3e-2 on one prior draw of configuration I; over 32 prior draws as drawn the worst band is 3.9e-3 (I) and 1.1e-2 (II); posterior draws are within 7.2e-4 (I) and 1.3e-3 (II).

JIT-compatible: the resulting predict_photometry() / predict_line_fluxes() are JIT- and gradient-safe; the one-time grid build is eager.

filter_coverage_at(z: float) → ndarray | None[source]

Per-band out-of-axis fraction at redshift z (#2620).

Parameters:

z (float) – Redshift [dimensionless].

Returns:

Fraction of each band’s weighted transmission beyond the observed axis (see filter_coverage_fraction()); None when the model has no photometry.

Return type:

ndarray, shape (n_filters,) or None

filter_coverage_redshifts() → tuple[float, ...][source]

Redshifts at which the band-coverage check is made (#2620).

The fixed redshift, or the finite ends of a free redshift prior, together with the ends of catalog_z_range when one is set. Duplicates are dropped and the order is preserved.

Returns:

Redshifts [dimensionless], possibly empty when no redshift is declared.

Return type:

tuple of float

property filter_trans

Read-only view of photometric filter transmission curves.

Delegates to self.observation.photometry.filter_trans if available. Returns None if no photometry is configured.

Notes

Deprecated: Access filters through self.observation.photometry directly. Direct assignment is discouraged.

property filter_waves

Read-only view of photometric filter wavelengths.

Delegates to self.observation.photometry.filter_waves if available. Returns None if no photometry is configured.

Notes

Deprecated: Access filters through self.observation.photometry directly. Direct assignment is discouraged.

fit_batch(catalog, flux_cols: list[str], err_cols: list[str], redshift_col: str | None = None, method: str = 'vi', n_workers: int = 1, verbose: bool = True, output_dir: str | None = None, id_col: str | None = None, **kwargs) → list[source]

Fit a batch of galaxies from a catalog (DataFrame, Table, or list of dicts).

Parameters:
  • catalog (DataFrame, Table, or list of dict) – Input catalog.

  • flux_cols (list of str) – Column names for per-band flux values.

  • err_cols (list of str) – Column names for per-band 1-sigma uncertainties.

  • redshift_col (str or None) – If provided, use this column as per-row redshift.

  • method (str) – Inference method. Default "vi".

  • n_workers (int) – Currently ignored (reserved for multiprocessing). Default 1.

  • verbose (bool) – Print per-galaxy progress. Default True.

  • output_dir (str or None) – If provided, save each Posterior to {output_dir}/{id}.h5.

  • id_col (str or None) – Column name for galaxy identifiers in checkpoint filenames.

  • **kwargs – Forwarded to Fitter.run().

Returns:

One result per galaxy in catalog.

Return type:

list of Posterior

Notes

Sequential fitting (no parallelization yet). For 1000+ galaxies, consider using fit() in a loop with a multiprocessing pool.

Examples

>>> import pandas as pd
>>> cat = pd.read_csv("catalog.csv")
>>> results = model.fit_batch(
...     cat,
...     flux_cols=["f_u", "f_g", "f_r", "f_i", "f_z"],
...     err_cols=["e_u", "e_g", "e_r", "e_i", "e_z"],
...     redshift_col="z",
... )
fit_population(observations_list: list, method: str = 'vi', population_prior: dict | None = None, **kwargs)[source]

Fit a population of galaxies with shared PSD hyperparameters.

Parameters:
  • observations_list (list) – Each element is a (flux, noise) tuple or dict with flux_obs/noise keys.

  • method (str) – Hierarchical inference method. Default "vi".

  • population_prior (dict or None) – Hyperpriors on shared PSD parameters.

  • **kwargs – Forwarded to PopulationFitter.run().

Returns:

Hierarchical inference results with population-level and per-galaxy posteriors.

Return type:

PopulationPosterior

Notes

Enables population-level constraints on shared PSD hyperparameters (e.g., shared burst timescale across a sample). All galaxies must use the same model configuration.

Examples

>>> obs_list = [(flux1, noise1), (flux2, noise2), ...]
>>> result = model.fit_population(obs_list, method="vi")
classmethod from_config(ssp, sfh=Ellipsis, dust_attenuation_law=Ellipsis, nebular=Ellipsis, agn=Ellipsis, redshift=Ellipsis, filters: list[str] | None = None, wave_obs=None, priors: dict | None = None, **model_kwargs) → SEDModel[source]

Build a SEDModel from a grouped configuration dict.

For the common case: instead of constructing Parameters, SSPData, Observation, and SEDModel separately, provide a single grouped config and receive a fully configured SEDModel.

Parameters:
  • ssp (str or SSPData) – Path to SSP HDF5 file, or a pre-loaded SSPData instance.

  • sfh (str) – SFH family name, e.g. "tsnorm", "dpl", "dpl+field".

  • dust_attenuation_law (str) – Dust attenuation law applied to BOTH screens (birth cloud + diffuse ISM) of the default two-component model, e.g. "calzetti", "kl04". "charlot_fall" (the default) is an alias for "power_law" on both screens – the classic Charlot & Fall (2000) model – not a law-registry name. dust= is a deprecated alias for this parameter.

  • nebular (str or None) – Nebular emission backend. "baked_in", "cloudy_grid", "cb19", "gutkin16", "mappings", "cue", "shock", or None.

  • agn (str or None) – AGN model. None (disabled) or any AGN model name.

  • redshift (float or str) – Fixed redshift (float), or "free" to add a free redshift parameter.

  • filters (list of str, optional) – Filter names for photometry, e.g. ["sdss_u", "sdss_g", "sdss_r"].

  • wave_obs (array, optional) – Observed-frame wavelength array for spectroscopy.

  • priors (dict, optional) – Parameter priors. Keys may be short names ("log_total_mass"), universal short names ("logzsol"), or full prefixed names. Short names are expanded automatically.

  • **model_kwargs – Forwarded to SEDModel.__init__().

Returns:

Fully initialized model ready for prediction or fitting.

Return type:

SEDModel

Notes

Ellipsis (...) placeholders in optional parameters map to defaults from defaults.toml. For example, dust_attenuation_law=... uses the default dust attenuation law.

Examples

>>> model = tengri.SEDModel.from_config(
...     ssp="data/ssp.h5",
...     sfh="dense_basis",
...     filters=["sdss_u", "sdss_g", "sdss_r"],
...     redshift=0.1,
...     priors=dict(
...         log_total_mass=tengri.Uniform(8, 12),
...         log_sfr_inst=tengri.Uniform(-2, 3),
...         logzsol=tengri.Uniform(-2, 0.2),
...     ),
... )
classmethod from_dict(config: dict, ssp_data, *, filters=None, observation=None, **model_kwargs) → SEDModel[source]

Build an SEDModel from a serialized config dict.

See also

SEDModel.to_dict

The introspection-side pair – a LIVE model’s own nested-dict grammar (self.spec.to_groups()), not the JSON/YAML-serialized form this method deserializes (tengri.config.serialize.deserialize_config). Round-trip a model you already built with SEDModel.build(ssp_data=ssp, **model.to_dict()); use from_dict/from_json/from_yaml for a config that arrived serialized (a file, a wire payload).

classmethod from_file(path: str | Path, ssp_data, *, filters=None, observation=None, **model_kwargs) → SEDModel[source]

Build an SEDModel from a config file (JSON or YAML).

classmethod from_json(json_str: str, ssp_data, *, filters=None, observation=None, **model_kwargs) → SEDModel[source]

Build an SEDModel from a JSON string.

classmethod from_yaml(yaml_str: str, ssp_data, *, filters=None, observation=None, **model_kwargs) → SEDModel[source]

Build an SEDModel from a YAML string.

property has_fixedz_photometry_precompute: bool

Whether this is a fixed-z photometry model (vmap-batch / fast-path eligible).

Replaces the legacy model.precomputed.photometry is not None proxy (the PrecomputedData container is being retired, #620). The legacy container’s photometry slot was populated exactly when a fixed redshift and filters were configured, so this reproduces that boolean without the container. The LUT fast path itself is opt-in via approx=WavePrecomp() and lives in the component chain.

line_model_sigma_frac(target_wavelengths, *, tolerance_aa: float = 5.0) → ndarray[source]

Fractional 1-sigma model error of the predicted line fluxes, per target.

Host-side NumPy, never traced: the result is data for the likelihood, not a function of the parameters. Each target is matched to the nearest line the nebular backend publishes, within tolerance_aa, and the matched catalog entry’s fractional sigma is returned. The same cloudyfsps_only flag as predict_line_fluxes() selects the catalog, so the errors align with the lines the model predicts.

Parameters:
  • target_wavelengths (array_like, shape (n_lines,)) – Rest-frame vacuum wavelengths of the observed lines [Angstrom].

  • tolerance_aa (float, optional) – Maximum allowed distance from a target to its matched catalog line [Angstrom]. None disables the check. Default 5.0, as in predict_line_fluxes().

Returns:

Fractional 1-sigma model error per target [dimensionless]. Zero where the backend publishes no error, so the likelihood reduces to the observation-only error.

Return type:

ndarray, shape (n_lines,)

Raises:

ValueError – If a target has no catalog line within tolerance_aa, or the hook returns an array misaligned with published_line_wavelengths.

Notes

Generic hook, not a Cue special case. A backend may provide published_line_model_sigma(*, cloudyfsps_only) returning a fractional sigma aligned element-for-element with published_line_wavelengths(cloudyfsps_only=...) (vacuum Angstrom), or None when the weights carry no errors. A backend without the hook has no model sigma and yields zeros. If the hook exists but returns None, an AdvisoryWarning says the weights need refreshing.

Only line fluxes take a model sigma. Line ratios and spectral indices do not: the per-line errors are correlated within a sub-network (for example [O III] 4959/5007 is fixed by atomic physics), and upstream publishes no covariance, so propagating them in quadrature would invent errors.

measure_line_fluxes(params, line_defs=None, *, approx=False, state=None, fixed_values=None, fast=<unset>)[source]

Emission-line fluxes measured from the model spectrum, catalog-style.

The counterpart to predict_line_fluxes(): where predict_* returns what the galaxy emits (the backend’s nebular line luminosity → flux), measure_* applies the operator a spectroscopic pipeline applies to data, estimate a local continuum from side-bands, subtract it, integrate the emission, to the model’s own rest-frame SED. It works for an additive photoionized backend (Cue, CloudyGrid) and for a baked-in wNE SSP grid (nebular emission already in the flux tables, neb={'type': 'ssp'}); for either it yields a quantity directly comparable to a catalog’s continuum-subtracted line flux and carries the stellar Balmer absorption under the line self-consistently. With an explicit neb={'type': 'none'} it measures the stellar continuum/absorption at the line’s rest wavelength, which is a legitimate use (e.g. isolating non-nebular physics from a nebular-emission channel) but carries no nebular emission whatsoever – unlike a bare-stellar grid paired with neb={'type': 'ssp'} (or the omitted-neb= default, which makes the same baked-in assumption), which never reaches this method at all: BakedInBackend.__init__ already raises at model-construction time rather than silently returning that same continuum-only number under a nebular-emission-line method’s name (#2540).

Parameters:
  • params (dict) – Parameter values (public names). redshift sets the luminosity distance for the observed flux.

  • line_defs (sequence of LineDef, optional) – Lines + continuum windows to measure. Defaults to the lines this model’s observation declares (Observation.line_fluxes), and only to tengri.observation.line_measurement.DESI_LINES when nothing declares a set. Before #1500 the DESI list was used unconditionally, so a model built with an eight-line LineFluxData silently returned five fluxes, for different lines, in a different order.

  • approx (bool, default False) –

    Route through the window-LUT path (measure_line_fluxes_from_window_lut()): SED-free SFH weights × precomputed SSP line-window integrals × the per-age dust screen, no full-grid SED. Bit-exact with the exact path for the supported configuration (stellar + two-component/no dust + baked-in/no nebular, delta metallicity, parametric non-field SFH) and raises otherwise (same contract as predict_spectral_indices() approx=True). An additive Cue backend is not eligible, its emission is not in the SSP window integrals, so use approx=False for Cue.

    Named for the build-time approx=FeaturePrecomp(...) it selects. Spelled fast until 2026-08.

  • state (ForwardState, optional) – Pre-computed forward state to measure on (exact path only).

  • fixed_values (dict, optional) – Fixed parameter values (evaluation-time only). When supplied, these are consulted during redshift resolution to support per-galaxy or per-call redshift overrides that do not appear in the free params.

  • fast (bool, optional) – Deprecated spelling of approx. Removed in v1.0.

Returns:

Observed emission-line fluxes [erg/s/cm^2], in line_defs order.

Return type:

jnp.ndarray, shape (n_line,)

Warns:

:class:`~tengri.components.nebular.baked_in.BakedInNebularGridWarning` – If the configured nebular backend contributes no nebular flux of its own (BakedIn, i.e. neb={'type': 'ssp'} or the model’s default) and the SSP grid’s nebular metadata is not 'included' (#2540): the measured flux is stellar continuum/absorption only, indistinguishable from neb={'type': 'none'}. A 'bare'-stamped grid in this mode cannot reach this method at all – BakedInBackend.__init__ already raises BakedInNebularBareError (a ValueError) at model-construction time. Never warns for an explicit neb={'type': 'none'} (see Notes): nothing about that mode asserts the grid carries baked-in emission in the first place.

Notes

JIT-compatible / differentiable: yes.

Continuum caveat. The side-band continuum carries the stellar absorption around the line; for baked-in nebular the Balmer flux is continuum-sensitive exactly as a real pipeline’s is. See the tengri.observation.line_measurement module docstring.

mock(params, snr=20.0, key=None)[source]

Generate mock photometric observation with noise.

Parameters:
  • params (dict) – Parameter values.

  • snr (float) – Signal-to-noise ratio. Default 20.0.

  • key (PRNGKey, optional) – Random key for noise. If None, returns noiseless.

Returns:

Mock photometric observation.

Return type:

MockData

Notes

Requires model to have filters configured (filters= or observation= in constructor).

Examples

>>> key = jax.random.PRNGKey(0)
>>> mock = model.mock(params, snr=15.0, key=key)
>>> print(mock.flux.shape)  # (n_filters,)
mock_batch(params_batch, snr=20.0, key=None)[source]

Generate batch of mock photometric observations.

Parameters:
  • params_batch (dict of arrays) – Each value has leading batch dimension.

  • snr (float) – Signal-to-noise ratio. Default 20.0.

  • key (PRNGKey, optional) – Random key for noise. If None, returns noiseless.

Returns:

Mock observations with shape (N, n_filters).

Return type:

MockData

Notes

Uses jax.vmap() over mock() for vectorized generation.

Examples

>>> params_batch = {
...     k: jnp.tile(v[None], (1000,) + (1,) * (len(v.shape)))
...     for k, v in posterior.samples.items()
... }
>>> mocks = model.mock_batch(params_batch, snr=15.0, key=key)
mock_spectrum(params, wave_obs, snr=30.0, key=None)[source]

Generate mock spectroscopic observation with noise.

Parameters:
  • params (dict) – Parameter values.

  • wave_obs (array) – Observed wavelength grid [Angstrom].

  • snr (float) – Signal-to-noise ratio per pixel. Default 30.0.

  • key (PRNGKey, optional) – Random key for noise. If None, returns noiseless.

Returns:

Mock spectroscopic observation.

Return type:

MockData

Notes

Noise is drawn from Gaussian distribution with standard deviation = flux/snr.

Examples

>>> wave_obs = np.linspace(4000, 5500, 1000)
>>> mock = model.mock_spectrum(params, wave_obs, snr=10.0, key=key)
>>> print(mock.flux.shape)  # (1000,)
property n_grid

PSD-grid resolution for stochastic SFH, else 0.

Public accessor for the internal _n_grid attribute. Non-zero only when the model uses a stochastic SFH (correlated-field prior on the SFH); used by inference to size the latent grid.

name: str = 'sed'
nebular_grid_can_serve_photometry() → bool[source]

Whether the per-Q_H nebular grid can serve this model’s photometry.

Serving photometry from the grid zeroes sed_nebular, so it requires that nothing read the continuum: no component, and no spectrum projected by the observation (_observation_reads_nebular_continuum()). A dust component reads it, unless it can take the nebular from the grid instead (_dust_can_take_nebular_from_grid()); then it does not count.

Returns:

True when no continuum consumer remains after that exclusion. The redshift may be fixed, free or a runtime catalog_z_range value: the grid’s band photometry follows the evaluation redshift.

Return type:

bool

observed_axis_range(z: float) → tuple[float, float][source]

Span of the model’s observed-frame wavelength axis at redshift z (#2620).

Parameters:

z (float) – Redshift [dimensionless].

Returns:

(min, max) of wavelengths * (1 + z) [Angstrom].

Return type:

tuple of float

plot_sfh_posterior(posterior, true_params=None, ax=None, n_draws=50, color='C0', label='Posterior')[source]

Plot posterior SFH with percentile fill and sample lines.

Parameters:
  • posterior (Posterior) – Inference results with samples (if available) or params.

  • true_params (dict, optional) – True parameter values (if known) to overlay on plot.

  • ax (matplotlib.axes.Axes, optional) – Axes object to plot on. If None, creates new figure.

  • n_draws (int) – Number of posterior samples to show as thin lines. Default 50.

  • color (str) – Color for posterior lines. Default “C0” (first color in style).

  • label (str) – Label for posterior. Default “Posterior”.

Returns:

ax – The matplotlib Axes object with the plot.

Return type:

matplotlib.axes.Axes

Notes

Shows 16th and 84th percentiles as filled region, with individual sample curves in light color. If true_params provided, shows truth in black with dashed line for smooth SFH (parametric part).

Examples

>>> result = model.fit(flux, noise)
>>> ax = model.plot_sfh_posterior(result)
>>> ax.set_yscale("log")
predict(params)[source]

Create a lazy prediction object for all derived physical quantities.

Returns a Prediction object that computes and caches derived quantities on first access. This is the recommended API for interactive exploration of a single galaxy’s properties, trading speed for convenience.

For batch computation over posterior chains or mock catalogs, use predict_properties(), the one JIT/vmap-safe surface for derived quantities, with jax.vmap() instead (up to 1000× faster for large batches).

Parameters:

params (dict) – Free parameters only, using public parameter names; a key the spec declared Fixed is refused with ParameterError (#2296), not merged or silently overridden.

Returns:

Lazy caching wrapper with property groups:

  • .sfh : SFH-derived quantities (stellar mass, SFR, age, metallicity)

  • .sed : SED-derived quantities (luminosities, colors, indices)

  • .lines : Emission line properties (luminosities, fluxes, ratios)

  • .radio : Radio SED properties (if radio=True)

  • .xray : X-ray SED properties (if xray=True)

  • .ionizing : Ionizing photon budget properties

Return type:

Prediction

Notes

Not JIT-compatible: Uses Python-side caching and object attribute access. Useful for interactive exploration, not for inference loops. For inference, use predict_photometry() (the hot path) or predict_properties() with jax.vmap().

Lazy evaluation: Quantities are computed only when accessed. Repeated access to the same property reuses cached results. This is transparent to the user.

NaN handling: Some quantities (e.g., stellar_mass_surviving, l_dust_absorbed) may return NaN if required data/parameters unavailable (e.g., no mass-remaining table, dust_model=’none’). The Prediction object handles NaN gracefully (returns None when data required to compute the quantity is absent).

Examples

Single-galaxy exploration (lazy, on-demand):

>>> pred = model.predict(params)
>>> pred.sfh.stellar_mass  # triggers SFH computation, caches result
Array(1.23e10, dtype=float64)
>>> pred.sfh.mass_weighted_age_gyr  # reuses cached SFH
Array(2.34, dtype=float64)
>>> pred.sed.l_bol  # triggers SED computation
Array(2.5e10, dtype=float64)
>>> pred.sed.uv_slope_beta  # reuses cached SED
Array(-1.8, dtype=float64)
>>> pred.lines.halpha  # triggers nebular computation
Array(4.23e-15, dtype=float64)

Batch computation (JIT-compatible, faster for large N):

>>> import jax
>>> params_batch = spec.sample(jax.random.PRNGKey(0), n=10000)
>>> sfh_fn = jax.vmap(lambda p: model.predict_properties(p, names=("stellar_mass",)))
>>> sfh_batch = sfh_fn(params_batch)
>>> sfh_batch["stellar_mass"].shape  # (10000,)
>>> sfh_batch["stellar_mass"].mean()

See also

predict_properties

JIT/vmap-safe derived quantities for batch.

Prediction.rest_sed()

Full rest-frame SED for custom analysis.

Prediction.lines

Emission-line luminosities.

predict_line_fluxes(params, target_wavelengths=None, tolerance_aa=5.0, *, redden=True, state=None, fixed_values=None, params_are_resolved=False)[source]

Predict observed emission line fluxes (dust-reddened by default).

The model’s nebular line emission: calls the photoionization backend (Cue / CloudyGrid) for line luminosities, applies dust attenuation at each line wavelength (Charlot & Fall birth-cloud + diffuse), and converts to observed flux L / (4 pi d_L^2) [erg/s/cm^2].

See also measure_line_fluxes(), which instead measures line fluxes off the model spectrum the way a spectroscopic pipeline measures data (continuum-subtract + integrate), works for any backend (including baked-in wNE) and carries the stellar Balmer absorption self-consistently. The distinction: predict_line_fluxes = what the galaxy emits; measure_line_fluxes = what a pipeline would extract from its spectrum.

For interactive access to individual named lines (luminosities, ratios, BPT diagnostics), see model.predict(params).lines.halpha etc.

Parameters:
  • params (dict) – Free parameters only (public names). A key the spec declared Fixed is refused with ParameterError (#2296).

  • target_wavelengths (array, shape (n_target,), optional) – Rest-frame vacuum wavelengths (Angstrom) of lines to predict. Each wavelength is matched to the nearest backend line. If None, returns all lines from the nebular backend.

  • tolerance_aa (float or None, default 5.0) – Maximum allowed wavelength delta [Angstrom] between a requested target and the matched catalog line. Raises ValueError on any miss, listing the offending targets. Pass None to disable (recovers legacy nearest-line-no-matter-what behavior).

  • redden (bool, default True) – Apply dust attenuation to the lines (HII regions see birth-cloud + diffuse dust; Charlot & Fall 2000). True returns observed fluxes comparable to a raw catalog; set False for intrinsic (un-reddened) fluxes, e.g. when fitting extinction-corrected catalog line fluxes. (Before 2026-07 this was always intrinsic, silently omitting the line reddening; redden=True is the fix.)

  • state (ForwardState, optional) – A pre-computed forward state to read the discrete line catalog from (shares one predict_state across channels, e.g. the joint loss’s line-flux + line-ratio + index channels). When None, this method runs its own predict_state (unless a fast per-Q_H grid is attached, which never needs one).

  • fixed_values (dict, optional) – Evaluation-time fixed values (e.g., a Fitter’s runtime redshift under catalog_z_range), forwarded to _evaluation_params() / _get_dl_cm() and to any internal predict_state call. When supplied, these win over the spec’s own declared Fixed values during resolution.

  • params_are_resolved (bool, default False) – Internal escape hatch for a build-time probe whose params is already a complete dict (free values plus a deliberately overridden Fixed key), not the free-only dict a user supplies. When True, params is used as the merged parameter dict directly and the Fixed-key refusal (#2296) is skipped entirely, rather than attempted and discarded. Not for user-facing calls: a caller with an ordinary free-only params should leave this False so a genuine Fixed-key override is still refused.

Returns:

fluxes – Observed line fluxes in erg/s/cm^2.

Return type:

array, shape (n_target,) or (n_all_lines,)

Raises:

ValueError – If no nebular backend is configured.

Notes

JIT-compatible: no, delegates to nebular backend.

Shock component limitation (#927): When a model includes both an active shock component and a photoionized backend (Cue/CloudyGrid), the shock’s discrete line luminosities are not published to the returned catalog. MAPPINGS V bakes shock lines into the continuum SED only (sed_shock), which is invisible to this catalog-reading surface. The shock will constrain only through continuum (broadband/spectrum), with zero gradient from line-flux channels. Use measure_line_fluxes() (pipeline-style flux extraction from the spectrum) to measure shock lines self-consistently with the stellar continuum.

Observed flux is calculated from luminosity via:

\[F = \frac{L}{4\pi d_L^2}\]

where \(L\) is the line luminosity [erg/s] and \(d_L\) is the luminosity distance [cm].

predict_line_ratios(params, line_ratio_data, *, state=None, fixed_values=None)[source]

Predict emission line ratios for a LineRatioData set.

Computes the model flux ratio F(numerator) / F(denominator) for each requested pair, in the same space (linear or log10) as the data. Runs the forward chain once and selects both the numerator and denominator lines from the published catalog, so the likelihood loop pays a single chain evaluation per step, not two.

Works identically on the exact and SpectrumPrecomp paths: line luminosities are grid-independent and survive the LUT path.

Parameters:
  • params (dict) – Parameter values (public names).

  • line_ratio_data (LineRatioData) – The observed ratio set; supplies numerator_waves / denominator_waves for matching and the log_space flag.

  • fixed_values (dict, optional) – Fixed parameter values (evaluation-time only). When supplied, these are consulted during redshift resolution to support per-galaxy or per-call redshift overrides that do not appear in the free params.

Returns:

Model ratios (log10 when line_ratio_data.log_space).

Return type:

ndarray, shape (n_ratios,)

Raises:

ValueError – If no nebular backend publishes a discrete line catalog.

Notes

JIT-compatible: no, delegates to the nebular backend via predict_state().

predict_observables(params, *, ssp_data=None, template_data=None, ztable_data=None)[source]

Project the orchestrator state into every configured observable.

Single bit-exact entry point: runs the SEDComponent chain and delegates to Observation.predict() for projection. Returns an Observables NamedTuple with one field per configured observation sub-block (phot_fnu, phot_rest_fnu, spec_fnu).

Warning

This is the exact wave-grid path: it bypasses the WavePrecomp LUT even when the model was built with approx=WavePrecomp(...). If you only need photometry, predict_photometry() returns the same phot_fnu through the LUT at roughly 16.5x the speed. Reach for this one when you need several channels from one pass, or when you specifically want the exact path.

Parameters:

params (Mapping) – Free-parameter dict.

Returns:

NamedTuple with fields keyed by configured sub-blocks: phot_fnu [erg/s/cm²/Hz] shape (n_filters,), phot_rest_fnu [erg/s/cm²/Hz] shape (n_filters,), spec_fnu [erg/s/cm²/Hz] shape (n_pixels,).

Return type:

Observables

Notes

JIT-compatible: yes. Not self-JIT’d, wrap with jax.jit() for hot loops, or call predict_observables_jit() for the pre-cached version.

Synthesized per-model at __init__() from observation contents; missing channels raise AttributeError on access.

predict_observables_jit(params, *, ssp_data=None, template_data=None, ztable_data=None)[source]

Self-JIT’d, structurally-cached version of predict_observables().

Bit-exact with predict_observables() (same orchestrator chain, same Observation.predict() projection). The compiled function is cached on compile_signature(), so two SEDModel instances with identical structure (same physics, same filter set, same observation shape) share one compile across galaxies.

Parameters:

params (Mapping) – Free-parameter dict.

Returns:

NamedTuple with fields keyed by configured sub-blocks.

Return type:

Observables

Notes

JIT-compatible: yes, this method IS the JIT entry point.

2026-05-20: self.spec.get_fixed_values() is now passed as a JIT runtime input rather than closure-captured. Two SEDModels with the same structural config but different per-galaxy fixed values (e.g., redshift=Fixed(0.1) vs redshift=Fixed(0.5)) share a compile_signature() and reuse the same compiled function, per-galaxy values flow through at call time.

For per-galaxy fixed redshifts, build with approx=WavePrecomp(z_min=catalog_z_min, z_max=catalog_z_max) so the ztable covers the catalog range; runtime params['redshift'] is then a fast interpolation lookup.

See also

predict_observables : un-JIT’d version (debug / one-shot). compile_signature : structural fingerprint controlling cache reuse.

2026-05-20: self.ssp_data is now passed as a JIT runtime input rather than closure-captured. The SSP grid becomes a Parameter op in the compiled HLO instead of a Constant op, reducing compile size and time.

2026-05-21: nebular backend grids and weights are now passed as JIT runtime inputs. Backend grids become Parameter ops instead of Constant ops, reducing compile size for Cue and CloudyGrid.

predict_photometry(params, *, ssp_data=None, template_data=None, ztable_data=None)[source]

Compute observed photometric flux densities through all filters.

Convolves the SED (redshifted and IGM-absorbed) through filter transmission curves, returning flux densities in the AB system at the source. Routes through predict_observables_jit(), the JIT-safe orchestrator with SSP threading.

Raw forward-pass output. For interactive use with cached derived quantities, see model.predict(params).photometry(). For batched photometry over posterior chains, use predict_photometry_batch().

Parameters:
  • params (dict) – Free parameters only, using public parameter names (e.g., sfh_tsnorm_log_total_mass, met_logzsol, redshift). See Parameters for canonical names. A key the spec declared Fixed is refused with ParameterError (#2296).

  • ssp_data (SSPData | None, keyword-only, optional) – SSP grid to thread in as a traced argument. None (default) uses self.ssp_data, which is correct for every ordinary call. Pass it explicitly only when you wrap this method in your own JAX transform, see the JIT note below.

  • template_data (Any | None, keyword-only, optional) – Template arrays (nebular grids, dust IR LUTs, AGN libraries) to thread in. None (default) uses _template_data_for_jit(). Same rationale as ssp_data.

Returns:

flux_density – Observed flux densities in erg/s/cm²/Hz (AB system, rest-frame reference frame corrected for luminosity distance and (1+z) redshift factor).

Return type:

array, shape (n_filters,)

Raises:

ValueError – If no filters configured in the model (pass filters or observation= to constructor).

Notes

JIT-compatible: yes. Safe inside jax.grad() for parameter gradients.

Threading across a JIT boundary you own (#1753). This method is already self-JIT’d and structurally cached, and it threads the SSP grid as an argument, so tengri’s own compiled programs never bake it. That guarantee does not survive being wrapped in a caller’s transform:

predict = jax.jit(model.predict_photometry)  # grid is BAKED

The inner jit inlines into the outer trace and self.ssp_data, read as a concrete array, becomes a Constant of your computation. On a real SSP that is 66.89 MB inlined, and the persistent-cache entry grows from 0.23 MB to 58.82 MB, a factor of 256, the mechanism behind the 141 GB cache in #1507. Pass the grid in to keep it an invar instead:

predict = jax.jit(lambda ssp, p: model.predict_photometry(p, ssp_data=ssp))
flux = predict(model.ssp_data, params)

Only the exact wave-grid path pays: under approx=WavePrecomp() the cube is dead code and XLA eliminates it before codegen. And if you are not composing this into a larger jitted program, do not wrap it at all; the plain call is already compiled and cached.

Approximation accuracy: Driven by the build-time approx= policy. WavePrecomp swaps in the SSP×filter LUT, which is ~0.4 % accurate for the stellar photometry (Zacharegkas+2025 [tengri.SEDModel.predict_photometry-1]) but re-applies dust as a first-order Taylor projection across each filter (#617). That linear-in-λ model is accurate in the optical/IR, where the attenuation curve is smooth across a band, but biases bands sampling the rest-UV (steep, extrapolated attenuation), by an order of magnitude for far-UV bands at moderate/high redshift. Such configurations emit a build-time UserWarning; use approx=None for unbiased blue-band photometry, or validate against it. SpectrumPrecomp applies attenuation per pixel and is unaffected. The orchestrator path is itself bit-exact for the configured policy.

Filter wavelengths: All filters loaded via load_filter_set() or Photometry are assumed to be in observed frame (redshifted). The model auto-redshifts rest-frame SED by \((1+z)\) before filter integration.

See also

predict

Lazy prediction object for all derived quantities.

predict_spectrum

Spectral flux at arbitrary wavelengths.

Prediction.magnitudes()

AB magnitudes (uses photometry internally).

Examples

>>> flux = model.predict_photometry(params)
>>> mags = model.predict(params).magnitudes()
>>> # For the fast LUT path, build with ``approx=WavePrecomp()``.

References

[tengri.SEDModel.predict_photometry-1]

A. Zacharegkas et al., “Fast Photometry with Precomputed Stellar Population Grids,” ApJ, (2025).

predict_photometry_batch(params_batch, *, ssp_data=None, template_data=None, chunk_size=32)[source]

Compute photometry for a batch of parameter sets, in chunks of galaxies.

Use this method for posterior chains / mock catalogs (batched forward pass). For interactive single-galaxy use, access model.predict(params).photometry().

Parameters:
  • params_batch (dict of arrays) – Each value has shape (N, …) with leading batch dimension.

  • chunk_size (int, keyword-only, default 32) – Galaxies per compiled chunk [galaxies]. Peak memory scales with the chunk, about n_age * n_wave * 8 bytes per galaxy [bytes].

Returns:

Photometric flux for each galaxy.

Return type:

array, shape (N, n_filters)

Notes

JIT-compatible: yes, uses jax.vmap() over predict_photometry().

Examples

>>> import jax
>>> key = jax.random.PRNGKey(0)
>>> params_batch = {
...     k: jnp.tile(v[None], (100,) + (1,) * (len(v.shape)))
...     for k, v in posterior.samples.items()
... }
>>> flux_batch = model.predict_photometry_batch(params_batch)
predict_properties(params, names=None, *, ssp_data=None, template_data=None, ztable_data=None)[source]

Compute derived properties from the forward state.

Properties are computed from the same orchestrator ForwardState that powers all other predictions, so their values are consistent with photometry, spectrum, and SED quantities. This method routes through predict_state(), enabling JIT/vmap/grad by treating property names as static arguments.

Parameters:
  • params (dict) – Free parameters only, using public parameter names. A key the spec declared Fixed is refused with ParameterError (#2296).

  • names (tuple[str] or list[str], optional) – Property names to compute. If None, computes all available properties. Each name must be in available_properties, else KeyError is raised.

  • ssp_data (Any | None, keyword-only, optional) – The JIT-threading channel, forwarded to predict_state(). Pass these only when wrapping this method in your own jax.jit / vmap / grad, where closure-captured grids would otherwise bake into your compiled program as constants, see predict_photometry() for the measured cost (#1753). None (default) uses the model’s own arrays.

  • template_data (Any | None, keyword-only, optional) – The JIT-threading channel, forwarded to predict_state(). Pass these only when wrapping this method in your own jax.jit / vmap / grad, where closure-captured grids would otherwise bake into your compiled program as constants, see predict_photometry() for the measured cost (#1753). None (default) uses the model’s own arrays.

Returns:

Mapping of property name to JAX scalar value [various units]. Returned as a plain dict with JAX array values.

Return type:

dict[str, scalar]

Raises:

KeyError – If any name in names is not in available_properties. The error message lists the available names.

Notes

JIT/vmap/grad-compatible: jax.jit() and jax.vmap() handle this method correctly provided names is treated as a static argument (the function parameter itself is not JIT-traced). Wrap the call like:

@jax.jit
def compute_stellar_mass(p):
    return model.predict_properties(p, names=("stellar_mass",))["stellar_mass"]

The returned dict has JAX-array values, so downstream operations on the scalars are fully differentiable.

Single-galaxy interactive use: for exploration, use predict() and access the Prediction.properties catalog with attribute syntax (e.g., pred.stellar_mass) to share cached state across multiple property accesses.

Legacy compatibility: predict_sfh_quantities() and predict_sed_quantities() remain unchanged and use independent computation paths; agreement is documented per test.

Examples

Compute one property:

>>> model = SEDModel.build(...)
>>> params = {...}
>>> props = model.predict_properties(params, names=("stellar_mass",))
>>> print(props["stellar_mass"])

Compute all properties:

>>> all_props = model.predict_properties(params)
>>> print(f"Stellar mass: {all_props['stellar_mass']} Msun")
>>> print(f"SSFR: {all_props['ssfr']} yr^-1")

Under jax.jit with vmap:

>>> vmap_props = jax.vmap(lambda p: model.predict_properties(p, names=("stellar_mass",)))(
...     params_batch
... )
>>> print(vmap_props["stellar_mass"].shape)  # (N,)

See also

available_properties

List of properties available in this model.

predict

Lazy Prediction object with attribute-access syntax.

predict_sfh(params, n_linear=1000, grid='linear')[source]

Compute SFH on a uniform linear-time grid (plots) or the native log-age grid.

Evaluates the SFH parameterization at n_linear evenly-spaced points in lookback time, returning both the smooth parametric component (sfr_mean) and the full SFH including GP-field modulation (sfr_full, if stochastic SFH enabled).

Raw forward-pass output intended for plotting. For SFH-derived scalars (stellar mass, recent SFR, age), see model.predict(params).sfh.* or predict_properties() for the JIT-compatible form.

Parameters:
  • params (dict) – Parameter values using public parameter names.

  • n_linear (int, optional) – Number of output grid points, evenly spaced in lookback time. Default 1000 (sufficient for smooth visualization). Ignored when grid="native".

  • grid ({"linear", "native"}, optional) – "linear" (default, backward compatible) resamples onto a uniform lookback-time grid for plotting. "native" returns the SFH on the model’s own log_age_grid nodes, unresampled, use this for any QUANTITATIVE work (residuals, coverage, chi2 against a truth).

Returns:

  • "t_gyr" : ndarray, shape (n_linear,) or (n_grid,). Lookback time [Gyr], from 0 (now) to ~13.8 (Big Bang).

  • "sfr_mean" : ndarray, shape (n_linear,) or (n_grid,). Parametric mean SFR [M☉/yr] (no GP modulation).

  • "sfr_full" : ndarray, shape (n_linear,) or (n_grid,). Full SFH including GP field [M☉/yr]. Identical to sfr_mean if stochastic SFH not enabled.

Return type:

dict with keys

Notes

JIT/vmap-compatible: yes (#715). jax.jit(jax.vmap(model.predict_sfh)) traces for every SFH family, on both grids, with no host conversion; a batch of draws is evaluated in one compiled call. Use tengri.vmap_chunked() rather than a bare vmap over thousands of draws. For integrated quantities (stellar mass, age, etc.) use predict_properties().

Time grid: with grid="linear" the output is resampled onto a uniform linear-time (lookback) grid, not the internal log-age grid. This makes visualization cleaner, but it is lossy at young ages and must not be used for quantitative scoring. The step is age_max / n_linear, at the default n_linear=1000 and a 13.8 Gyr span that is 13.8 Myr, so a 16-node log-age grid whose five youngest nodes all lie below 15 Myr collapses into ~2 samples there. Resampling also interpolates linearly between log-age nodes, so a log-axis plot shows corners at the nodes; that is the interpolant, not the model.

Scoring an SFH residual on the linear grid silently reweights it: every megayear counts equally, so 15-500 Myr swamps the <15 Myr bins where emission lines carry nearly all of their information. Measured on the field-SFH recovery study, that reweighting turned a real +54% improvement from adding line fluxes into an apparent 0%. Pass grid="native" for residuals, coverage, or any comparison against a known truth.

SFH mean vs. full: When correlated-field (stochastic) SFH is enabled, sfr_mean shows the smooth parametric trend (e.g., exponential decline), while sfr_full adds GP modulation for realistic burstiness. If parametric-only SFH is used, they are identical.

Physical units: Output SFR is in M☉/yr. Lookback time is in Gyr (cosmic time before today).

Examples

>>> sfh = model.predict_sfh(params)
>>> print(sfh.keys())
dict_keys(['t_gyr', 'sfr_mean', 'sfr_full'])
>>> import matplotlib.pyplot as plt
>>> plt.plot(sfh["t_gyr"], sfh["sfr_mean"], label="Smooth")
>>> if "sfr_full" in sfh:
...     plt.plot(sfh["t_gyr"], sfh["sfr_full"], alpha=0.5, label="With bursts")

See also

predict_properties

Integrated SFH quantities, JIT/vmap-safe.

predict

Lazy access to SFH and all derived quantities.

predict_spectral_indices(params, index_defs, *, state=None, approx=False, fast=<unset>, fixed_values=None, broaden=True)[source]

Predict spectral index values from the model SED.

Generates a rest-frame spectrum covering the index wavelength ranges and measures each index (EW or break ratio). Suitable for JIT/batch loops; for interactive use, access individual indices via model.predict(params).sed.dn4000 etc.

Parameters:
  • params (dict) – Parameter values (public names).

  • index_defs (tuple of SpectralIndexDef) – Index definitions to measure.

  • state (ForwardState, optional) – A pre-computed forward state to measure on (shares one predict_state across channels). Ignored when approx=True.

  • fixed_values (dict, optional) – Evaluation-time fixed values (e.g., runtime redshift from a Fitter’s params_override). When supplied, these override the spec’s declared Fixed values. Required to be a complete fixed-value dict (one entry per spec’s Fixed parameter); absent keys will raise KeyError during evaluation. Threaded to internal merge_fixed_params calls in both the fast (approx=True) and exact paths, ensuring evaluation-time overrides (such as a runtime redshift affecting the cosmic age and SFH truncation) reach all internal computations.

  • approx (bool, default False) –

    Route through the FeaturePrecomp window-LUT path (_feature_fast_indices()): contract precomputed SSP window integrals with SED-free SFH weights and the model’s per-age dust screen, instead of reconstructing the full-grid SED. ~17x faster per evaluation (measured, wNE grid) and bit-exact for the supported configuration (a Lick equivalent width is evaluated at the window grid points, as the exact path evaluates it), stellar + two-component (or no) dust + baked-in (or no) nebular, delta metallicity, parametric non-field SFH. Any other configuration (additive nebular, AGN, non-delta metallicity, GP-field SFH) raises ValueError rather than silently falling back, because approx=True is an explicit opt-in; use approx=False there. Slope indices are filled from the exact SED (they are not window-LUT-expressible).

    Named for the build-time approx=FeaturePrecomp(...) it selects. Spelled fast until 2026-08.

  • fast (bool, optional) – Deprecated spelling of approx. Removed in v1.0.

  • broaden (bool, default True) – Measure each index on the rest-frame SED broadened by the model’s sigma_v_kms (#3466), so the model index is comparable with an observed index measured at its own dispersion. broaden=False measures the unbroadened SED, the \(\sigma = 0\) index, for data already corrected to \(\sigma = 0\). At sigma_v_kms = 0 the two are identical. The broadening is broaden_index_sed(). The window-LUT path (approx=True) does not broaden, so it raises for a broadened measurement with a nonzero sigma_v_kms.

Returns:

Predicted index values.

Return type:

jnp.ndarray, shape (n_indices,)

Notes

JIT-compatible: yes, both paths are pure jnp. The approx path builds its window LUT once (cached on the model) from concrete SSP data, so it is safe to call under jax.jit.

Measures spectral indices (equivalent width or break ratio) from a rest-frame spectrum covering all wavelength ranges in index_defs. The spectrum is \(L_\nu\); a Lick equivalent width converts it to \(F_\lambda\) and builds the sideband straight-line pseudo-continuum (Trager et al. 1998, ApJS 116, 1, Eqs. 1-3; see pseudo_continuum).

predict_spectrum(params, wave_obs=None, wave_chunk_size=None, *, ssp_data=None, template_data=None, ztable_data=None)[source]

Compute observed spectrum at given wavelengths with LSF convolution.

Evaluates the full SED at custom wavelengths in observed frame, applies velocity dispersion broadening (if sigma_v in spec), convolves with instrument line-spread function, and optionally applies multiplicative Chebyshev calibration polynomial.

Raw forward-pass output. For interactive use, see model.predict(params).spectrum. For batched spectra, use predict_spectrum_batch().

Parameters:
  • params (dict) – Parameter values using public parameter names.

  • wave_obs (array, optional) –

    Observed-frame wavelength grid [Angstrom]. If None, uses:

    1. The grid bound at construction from observation.spectroscopy.wave_obs

    2. Raises ValueError if no grid is available

  • wave_chunk_size (int, optional) – If specified, split observed-frame wavelength axis into chunks of this size and evaluate via jax.lax.map to reduce per-chunk HLO size for XLA compilation. Default None (no chunking, exact behavior). For spectroscopy with R~500 at N≥64 galaxies, typical value is 32–64 to avoid XLA compilation wall-clock.

  • ssp_data (Any | None, keyword-only, optional) – The JIT-threading channel, see predict_photometry() for what it is for and what baking costs (#1753). Honored on the configured- spectroscopy route (the inference hot path, taken when wave_obs is None and the model has a spectroscopy channel). An explicit wave_obs grid routes through _predict_obs_sed instead, which does not yet carry the channel, that route still closure-captures.

  • template_data (Any | None, keyword-only, optional) – The JIT-threading channel, see predict_photometry() for what it is for and what baking costs (#1753). Honored on the configured- spectroscopy route (the inference hot path, taken when wave_obs is None and the model has a spectroscopy channel). An explicit wave_obs grid routes through _predict_obs_sed instead, which does not yet carry the channel, that route still closure-captures.

Returns:

flux – Observed spectral flux density [erg/s/cm²/Hz] in the AB system at the specified wavelengths.

Return type:

array, shape (n_pix,)

Raises:

ValueError – If wave_obs is None and no precomputed wavelength grid available.

Notes

JIT-compatible: yes, routes through predict_observables_jit() (the JIT-safe orchestrator).

Velocity dispersion: When sigma_v is in free params, applies line-of-sight broadening via Gaussian convolution at FWHM = 2.355 × sigma_v. Implemented as wavelength-space Gaussian convolution (valid for linear pixels; use apply_lsf() for log-wavelength pixels).

Line-spread function: Composition of:

  • Velocity dispersion broadening (σ_v-dependent)

  • Instrument LSF (resolution R-dependent, Gaussian approximation)

  • Chebyshev multiplicative calibration (optional)

All three are convolved in the forward model.

Precomputed wavelength grid: When the model is built with Observation(spectroscopy=Spectroscopy(wave_obs=...)) the SSP is resampled onto that fixed grid at construction, so each forward spectrum is a cached weighted sum (~1 ms warm) and wave_obs need not be passed on every call.

Wavelength-axis chunking: Set wave_chunk_size to split the observed-frame wavelength axis into ~N/chunk_size chunks and evaluate independently via lax.map. Each chunk’s HLO is ~1/K of the full HLO (K = chunk_size / min_chunk_width), reducing XLA compile-time superlinearly. Numerical output is bitwise-identical to unchunked. Typical runtime overhead: +5–20% per galaxy due to map overhead.

Examples

>>> wave_obs = np.linspace(4000, 5500, 1000)  # observed frame [Å]
>>> flux = model.predict_spectrum(params, wave_obs)
>>> import matplotlib.pyplot as plt
>>> plt.plot(wave_obs, flux)
>>> plt.xlabel("Wavelength (Å)")
>>> plt.ylabel("Flux (erg/s/cm²/Hz)")

For large spectroscopy sets with many galaxies, use chunking:

>>> flux = model.predict_spectrum(params, wave_obs, wave_chunk_size=64)

See also

predict_photometry

Filter-integrated flux (simpler, faster).

predict

Lazy access to all SED and SFH quantities.

predict_photometry

Filter-integrated flux (simpler, faster).

predict_spectrum_batch(params_batch, *, ssp_data=None, template_data=None, chunk_size=32)[source]

Compute spectra for a batch of parameter sets via jax.vmap.

Use this method for batched spectra over posterior chains. For interactive single-galaxy use, access model.predict(params).spectrum.

Parameters:

params_batch (dict of arrays) – Each value has leading batch dimension.

Returns:

Spectral flux for each galaxy.

Return type:

array, shape (N, n_pix)

Notes

JIT-compatible: yes, uses jax.vmap() over predict_spectrum().

Examples

>>> params_batch = {
...     k: jnp.tile(v[None], (1000,) + (1,) * (len(v.shape)))
...     for k, v in posterior.samples.items()
... }
>>> flux_batch = model.predict_spectrum_batch(params_batch)
>>> flux_batch.shape
(1000, n_pix)
predict_state(params, fixed_values=None, ssp_data=None, template_data=None, ztable_data=None, *, observables_only=False)[source]

Forward pass via the SEDComponent orchestrator.

Builds a component chain from this model’s structural settings (self.spec + self.ssp_data + dust / nebular / AGN / radio / X-ray / IGM flags) and threads params through tengri.forward.run_components(). Returns the final tengri.protocols.ForwardState, not a legacy Prediction, callers wanting the legacy shape should keep using predict_photometry()/predict_spectrum() until the full integration adapter ships.

Not a public surface, despite what this docstring used to say (#1736). The prediction contract, docs/dev/NAMING_CONTRACT.md §4b, binding on code, docs, notebooks and examples, names three: predict(), predict_photometry() and predict_properties(). predict_state is not among them. It is the internal bridge from this model’s configuration surface to the orchestrator, called by predict_observables_jit() and by ForwardModel.predict_observables; its return type and the keys on it carry no stability guarantee and may change without notice.

It is not on the removal path either; it has production callers and is classified UNSANCTIONED rather than retired (tests/contract/test_public_api_surface.py). Do not describe it with the d-word: test_predict_surface_classification.py derives that label by searching this docstring for the substring, so the wording here is the classification.

If you reached for this to get per-component SEDs, use pred.sed.components instead:

comp = model.predict(params).sed.components
comp["sed_intrinsic"]  # stellar, pre-dust  [erg/s/Hz]
comp["sed_dust_ir"]  # and sed_nebular, sed_agn, sed_total, ...

That is the supported decomposition, it reuses the prediction’s cached forward state (no second forward pass), and it returns a plain dict of named arrays rather than a pipeline object. Reaching through predict_state instead hands you a ForwardState, whose derived dict CLAUDE.md explicitly documents as internal, so the convenient path out of this method leads directly into an object the conventions tell readers not to touch.

Parameters:
  • params (Mapping) – Free parameters keyed by canonical name (sfh_*, met_*, dust_*, agn_*, radio_*, xray_*, igm_*, redshift).

  • fixed_values (Mapping | None, optional) – Fixed parameter values. When provided, overrides self.spec.get_fixed_values(). Used by predict_observables_jit() to thread per-galaxy fixed values as JIT runtime inputs.

  • ssp_data (Any | None, optional) – SSP grid. When provided, passed to components that need it as a JIT runtime input instead of using closure capture. Defaults to None, which causes components to use their internal self.ssp_data.

  • template_data (Any | None, optional) – Nebular backend grids and weights. When provided, passed to components as JIT runtime inputs instead of closure capture. Defaults to None, which causes components to use their internal template data.

  • ztable_data (Any | None, optional) – Precomputed photometric redshift table. When provided, passed to components as JIT runtime inputs instead of closure capture, preventing XLA from materializing the z-table as a constant. Defaults to None, which causes components to use their internal z-table.

  • observables_only (bool, keyword-only, optional) –

    Declare that the caller reads only the projected observables (photometry and spectra off the LUT) and never the SED arrays or derived publications. Components may then take publication shortcuts: the per-Q_H nebular grid zeroes sed_nebular because skipping the Cue forward is the whole saving (#1596).

    Default False, so the returned state is complete. Only predict_observables_jit() sets it, and that is the point: correctness is what you get by default and the optimization is the thing that has to be asked for. Setting it while reading the SED costs the entire nebular continuum, measured at 97 % of the peak on a dust-free Cue model, in float64 and silently (#1673).

Returns:

Threaded state after the chain runs. sed_intrinsic is the rest-frame total SED in erg/s/Hz; sed_observed is populated when an IGM component is present; derived carries every cross-component publication (L_ir, L_agn_bol, log_mstar, lnu_age, etc.).

Return type:

ForwardState

Notes

JIT-compatible: yes, run_components() and every adapter’s apply are pure JAX.

self.spec.mean_sfh_type is a list (e.g. ["tsnorm"], ["dpl", "field"]); the first entry is the mean SFH model, and "field" anywhere in the list enables the GP-field branch. Anything else (burst, etc.) is currently unmapped and will raise downstream.

prior_predictive(n: int = 500, seed: int = 42, chunk_size: int = 32) → PriorPredictive[source]

Sample from the prior and evaluate forward model on each draw.

Parameters:
  • n (int) – Number of prior samples. Default 500.

  • seed (int) – Random seed. Default 42.

Returns:

Object containing flux, SFH, and parameter draws with model reference.

Return type:

PriorPredictive

Notes

Useful for prior predictive checks: visualizing what the model predicts under the prior without conditioning on data.

Examples

>>> pp = model.prior_predictive(n=100, seed=42)
>>> # Access photometry, SFH, and parameters from the prior
recommend_method() → str[source]

Return the recommended inference method string for this model.

Returns:

Canonical method name for Fitter.run() or model.fit().

Return type:

str

Notes

Based on model dimensionality, complexity, and available precomputation. Use as input to model.fit(method=model.recommend_method()).

Examples

>>> method = model.recommend_method()
>>> result = model.fit(flux, noise, method=method)
record_decline(name: str, slot: str, reason: str) → Decline[source]

Record the refusal of a table gate in the one memo, and return the record.

The band-table providers return a Decline that _band_table() stores. A gate that is not a provider (the energy-balance LUT, the FeaturePrecomp top-up of approx='auto') records its refusal through here, so every outcome is one Decline in _band_tables[name][slot] and the engagement report only reads it.

Parameters:
  • name (str) – Gate or component name, for example "energy_balance" or "approx".

  • slot (str) – The gate’s slot, for example "lut" or "feature_precomp".

  • reason (str) – Why the table is not applicable; required.

Returns:

The stored record.

Return type:

Decline

run(state, params, *, ssp_data=None, template_data=None)[source]

Run the SED forward chain. Pure JAX.

SED is the head of the per-population orchestration; in the tracer-bullet single-population path, state is an empty tengri.protocols.ForwardState with just the wavelength grid. The method delegates to predict_state() for the actual physics.

Parameters:
  • state (ForwardState) – Incoming state (empty for SED as the head of the chain).

  • params (Mapping) – Free parameter values.

Returns:

State with SED contributions populated.

Return type:

ForwardState

Notes

Satisfies tengri.protocols.SubModel. Threading non-empty upstream state is reserved for a future ResolvedSEDModel mode that needs SED to read spatial keys; today the contract is “incoming state ignored, output state freshly built.”

ssp_data/template_data are the JIT-threading channel, forwarded to predict_state(); both keyword-only and both defaulting to None, so the SubModel call shape run(state, params) is unchanged for every existing caller (#1753).

summary() → str[source]

Return a human-readable summary of the model configuration.

Returns:

Formatted summary showing SSP grid, filters, precomputation, fused kernel status, and enabled components.

Return type:

str

Notes

Similar to tree() but focuses on computational configuration and precomputation status rather than physics parameters.

Examples

>>> print(model.summary())
threaded_template_inputs()[source]

Return (ssp_data, template_data, ztable_data) for a traced per-galaxy forward.

Builds and caches the component chain first, so the call is made outside any JAX trace: a caller that threads these grids into its own jit or vmap must not build the chain inside the trace. Used by the batched spectroscopic stack (#2845) through ForwardModel, which delegates this method to its inner SED.

to_dict() → dict[source]

Return this model’s nested-dict grammar (thin alias of self.spec.to_groups()).

The introspection-side pair to from_dict(): a round-trip SEDModel.build(ssp_data=ssp, observation=obs, **model.to_dict()) reproduces model.predict_photometry bit-exactly (D9, task-12 public-API audit – from_dict existed with no such counterpart, so the working round-trip was the less-discoverable model.spec.to_groups() directly).

Returns:

Nested-dict suitable for SEDModel.build(ssp_data=ssp, **result) or tengri.parse_groups(**result). Live Distribution/ sentinel objects, NOT the JSON/YAML-serialized form from_dict consumes – see from_dict().

Return type:

dict

See also

tengri.parameters.parameters.Parameters.to_groups

What this delegates to.

SEDModel.from_dict

The serialized-config-side counterpart.

SEDModel.config

Equivalent property (kept for back-compat); this method is the discoverable, symmetric-with-from_dict spelling.

to_json(path: str | Path | None = None) → str[source]

Serialize the model configuration to JSON format.

to_yaml(path: str | Path | None = None) → str[source]

Serialize the model configuration to YAML format.

tree() → str[source]

Return a human-readable physics tree showing the model hierarchy.

Shows the active sub-models at each physical layer (SFH, SPS, Dust, Nebular, AGN, Observation), the free parameters at each layer, and the recommended inference method.

Returns:

Multi-line formatted tree string.

Return type:

str

Notes

Useful for inspecting model configuration before fitting or inference.

Examples

>>> print(model.tree())
Model  [D=7, stochastic=False]
...
property uses_stochastic_sfh: bool

True if the SFH is a stochastic correlated-field model.

Public accessor for the internal _uses_stochastic_sfh flag. Stochastic SFH adds an additional psd_xi latent of shape (n_grid,) to the free-parameter set.

property wave_obs

Configured observed-frame spectroscopy wavelength grid, or None.

Reports the grid the model predicts spectra on by consulting the configured observation.spectroscopy.wave_obs (the source of truth, #389/#620). Returns None only when no spectroscopy grid is configured anywhere.

Returns:

Observed-frame wavelength grid [Angstrom], shape (n_pix,).

Return type:

ndarray or None

property wavelengths

Rest-frame wavelength grid (Angstrom).

Returns the SSP grid by default, or the extended panchromatic grid when radio or X-ray emission is enabled.

Returns:

Rest-frame wavelength grid [Angstrom].

Return type:

ndarray, shape (n_wave,)

Notes

This is the grid used by Prediction.rest_sed() by default when no custom wave is passed. Updated when radio/X-ray components are added to the model.

Examples

>>> print(model.wavelengths[0], model.wavelengths[-1])
>>> # Default SSP range, e.g. 91.2 to 160000 Å
with_approx(approx, *, observation=None)[source]

Return a copy of this model built with a different approx policy.

Parameters:
  • approx (WavePrecomp or SpectrumPrecomp or FeaturePrecomp or tuple or None) – Approximation policy for the clone, with the same grammar as the approx= constructor argument: None for the exact wave-grid path, a single precompute config for one LUT family, or a composite tuple (at most one of each) such as (WavePrecomp(), FeaturePrecomp()).

  • observation (Observation, optional) – Observation for the clone. Defaults to this model’s own. Passing a different one rebuilds the LUT against its filters, the seam ForwardModel.build() uses to make its authoritative observation win (#1367, spec §5).

Returns:

A new model sharing this model’s spec, ssp_data, observation and build settings, differing only in approx (and observation when given). Returns self unchanged when approx=None is requested on a model that is already exact and no observation override is given (a no-op).

Return type:

SEDModel

Notes

Building the clone only rebuilds the approximation LUT, which the tengri_precomp cache persists (content-hashed on SSP grid, filters, and z-grid), so repeat clones of the same combination are cheap. The inference layer uses this to fit on the fast LUT path while leaving the user’s (exact) model untouched. JIT-compatible: build-time only.

with_fixed_redshift(redshift)[source]

Return a copy of this model built at a different Fixed redshift.

Every build-time table that captures the redshift (the fixed-z stellar photometry LUT, IGM band factors, the nebular grid reference, the dust-IR band response, the energy-balance LUT, the radio/X-ray term responses, the precomputed luminosity distance, the line-catalog snapping) is rebuilt by construction, so the clone is exactly the model a user would have built with redshift=Fixed(redshift).

Parameters:

redshift (float) – The new constant redshift.

Returns:

A new model sharing ssp_data, observation and build settings, on the same approx policy. self when the redshift already equals this model’s.

Return type:

SEDModel

Raises:

Notes

Costs one model construction, the same as with_approx() (the precompute LUT is re-run; the tengri_precomp cache persists it per z-grid). JIT-compatible: build-time only.

with_runtime_redshift(z_range=None)[source]

Return a copy that takes redshift as a runtime input (#3505).

The copy reads params["redshift"] on every call, so one compiled kernel serves any number of redshifts. The spec’s Fixed value stays as a placeholder and is never read. self is returned unchanged when redshift is already free in the spec, since it is already a runtime input.

Parameters:

z_range (tuple of float or None, optional) – (z_lo, z_hi) redshift table range [dimensionless]. Required for a tabulated (WavePrecomp) model unless the model already carries a catalog_z_range; must be None for an exact model, which has no table.

Returns:

A new model on the same approx policy and build settings, with the runtime-redshift flag set. self when redshift is already free.

Return type:

SEDModel

Raises:

ValueError – If z_range is given for an exact model, or a tabulated model has no range from either z_range or catalog_z_range.

Notes

Costs one model construction. JIT-compatible after construction: the returned model takes a traced redshift in params like any free-z model.

property z_fixed

Fixed redshift value if redshift is not a free parameter, else None.

Public accessor for the internal _z_fixed attribute. Set at construction from spec.get_fixed_values().get('redshift').

Approximation policies

The approx= argument to build() selects a build-time lookup table in place of the exact per-evaluation forward. Each targets a different output channel and they compose: WavePrecomp serves photometry, SpectrumPrecomp the spectrum, FeaturePrecomp the emission lines. approx=None (the default) keeps the exact wave-grid path.

Wave precomp

class tengri.WavePrecomp(n_z: int = 250, z_min: float | None = None, z_max: float | None = None, catalog_z_range: tuple[float, float] | None = None, igm_fold: str = 'auto', band_integration: str | None = None, n_subbands: int | None = None, taylor_correction: bool | None = None, fast_dust_emission: bool = False)[source]

Bases: object

Configuration for the wave_precomp approximation method.

Pass this to SEDModel via approx= to override the default redshift grid used when the model has a free redshift parameter. The SSP × filter integral is precomputed on the wavelength grid; for free redshift the result is interpolated through a (n_z,) table built on the same LUT.

Parameters:
  • n_z (int, default 250) –

    Number of grid points in the ztable. Higher → finer redshift interpolation, slower precompute. Default 250 holds the ztable’s own contribution below 1 % across all bands over z ∈ [0, 1.5] with ~37s build overhead (#1134).

    That is a bound on the redshift interpolation alone, not on the LUT’s total error, and the two are not close. Measured on a 12-band tsnorm + two-component-dust model against the exact projector, raising n_z 250 → 1000 moves the GALEX FUV error at z = 1.5 by nothing at all (10.410 % → 10.402 %), while n_subbands=32 cuts the same number ~9× (→ 1.150 %). The dominant term is band_integration, because the Lyman break is a step inside the bandpass and quadrature converges as 1/K² only on smooth integrands. Reach for n_z to fix a wobble along the redshift axis; reach for the band-integration knobs to fix a band whose SED has an edge in it.

  • z_min (float or None, default None) – Lower bound of the ztable grid. None → pull from the redshift prior with 1 % padding. Ignored when redshift is Fixed unless catalog_z_range is set.

  • z_max (float or None, default None) – Upper bound of the ztable grid. None → pull from the redshift prior with 1 % padding. Ignored when redshift is Fixed unless catalog_z_range is set.

  • catalog_z_range (tuple of float or None, default None) – Catalog-fit reuse knob (Approach A, 2026-05). When set to (z_min, z_max), the ztable mechanism is forced on even when redshift is Fixed in the spec. The Fixed value is then treated as a runtime input to the JIT-compiled forward pass, so a single SEDModel instance handles a catalog of per-galaxy Fixed(redshift) values with one compile instead of one compile per row. Compile time amortizes across the catalog; runtime cost per fit is the ztable interpolation (~µs).

  • igm_fold (str, default "auto") –

    How to integrate IGM transmission into sub-band photometry.

    "node"

    Evaluate the transmission at the sub-band quadrature node and multiply. Fast and exact for smooth transmission, but forms <S><T> when transmission varies inside a band (GALEX FUV near Lyman break). Measured error: ~10% GALEX FUV at z=1.5, ~83% at z=3.

    "exact"

    Integrate transmission inside the bandpass integral: ∫ S·T_IGM·T_b·w dλ. Slower build (recomputes sub-band integrals per redshift node), cost amortized over inference. Exact when T_IGM(λ, z) is tabulated. Works with both fixed and free redshifts. Fails loudly if free parameters (patchy reionization, DLAs) make transmission non-tabulated.

    "auto" (default)

    "exact" wherever it can be built, "node" everywhere else. The exact fold refuses a transmission carrying free parameters (patchy reionization, DLAs), but supports free redshift. "auto" asks for the exact fold and takes the node fold where it is unavailable, without raising. An explicit "exact" still raises in those cases: a mode named by the caller is never silently downgraded.

    "auto" resolves at build time; the fold actually built is reported under precompute_engagement_report(model).observed_facts["igm_fold"] (None when no fold was built).

Examples

>>> SEDModel(..., approx=WavePrecomp())  # default ztable sampling
>>> SEDModel(..., approx=WavePrecomp(n_z=200))  # finer ztable
>>> SEDModel(..., approx=WavePrecomp(z_min=0.01, z_max=3.0, n_z=200))
>>>
>>> # Catalog fit: 10⁴ galaxies at per-galaxy known z.
>>> sed = SEDModel.build(
...     ...,
...     redshift=Fixed(DEFAULT),  # per-galaxy value supplied by the redshift column
...     approx=WavePrecomp(catalog_z_range=(0.05, 1.5), n_z=200),
... )
>>> forward = ForwardModel.build(sed=sed, observation=obs)
>>> posteriors = Catalog(forward, table, flux_unit="cgs_fnu", redshift_col="z").fit(
...     method="map", key=key
... )

Notes

This example used to read model.fit(row.data, params={"redshift": row.z}) in a Python loop, a documented invocation that raised TypeError until #1384 plumbed params= through SEDModel.fit (it now forwards to the same per-fit override ForwardModel.fit takes, and on a catalog_z_range model the redshift rides data_args as a runtime input, #1316). Catalog remains the taught surface for a table of galaxies with a redshift column: one ingest, one validation, one compiled program.

Accuracy has an SNR ceiling, not just a percentage (#1671). The LUT’s forward photometry bias (measured 0.13-0.26 % on a 4-band reference model) is constant in SNR (so no forward check can see it) but it enters the posterior gradient multiplied by SNR: ~5 % relative gradient error at SNR 30, ~50 % at SNR 300 on the same model. It is a bias, not noise: it moves the posterior mode, and better data makes it worse. Fits price this automatically, at run time one exact-vs-LUT forward estimates max(bias x SNR) and a PrecompBiasWarning fires with the number when it is material. For final inference at high SNR, rerun with approx=None (exact path) or compare the two posteriors. The spectroscopy analog (SpectrumPrecomp) was measured as a ~1-sigma posterior shift on a 50-pixel, 5 %-noise fixture (#1688).

band_integration: str | None = None

How the multiplicative dust screen is integrated through each bandpass.

One of:

"quadrature" (default)

The screen is evaluated at n_subbands quadrature nodes per band and summed against the sub-band SSP x filter tensors (#1122). Converges as 1/K^2. This is the accurate scheme and the one to use for science.

"taylor"

First-order spectral-moment expansion about the filter effective wavelength, A(lam_eff)*Phi + A'(lam_eff)*Psi (Zacharegkas+2025, #617). Retained for reproducing pre-#1122 published results and for comparison work. Biases the rest-UV badly, see taylor_correction.

"effective_wavelength"

Zeroth order, A(lam_eff)*Phi. The cheapest and least accurate.

None (the default) resolves to "quadrature", or to whichever scheme the legacy n_subbands / taylor_correction pair describes when either was passed explicitly.

Naming the scheme here is the supported way to pick one. The legacy pair selected it only implicitly, through an interaction that was easy to get wrong in one direction specifically: taylor_correction=True alone left the quadrature on and the flag inert, so a caller who asked for Taylor by name silently received quadrature unless they also knew to set n_subbands=0.

Examples

>>> WavePrecomp()                                  # quadrature, K=5
>>> WavePrecomp(band_integration="taylor")         # actually Taylor
>>> WavePrecomp(band_integration="quadrature", n_subbands=8)
cache_key() → tuple[source]

Return a hashable cache key for this configuration, field by field.

Returns:

(type_qualname, ((field_name, baked_value), ...)). Explicit rather than relying on tengri._cache_keys.baked’s generic frozen-dataclass fallback, so a resolved config always keys the same way regardless of how it is reached.

Return type:

tuple

catalog_z_range: tuple[float, float] | None = None
fast_dust_emission: bool = False

Approximate the dust IR re-emission band projection when its exact, fast form is unavailable. For a modified_blackbody with fixed shape (dust_T, dust_beta_ir, dust_epsilon_mbb) and fixed redshift, the template is linear in L_ir and its per-band integral R is precomputed once (CIGALE dl2014 style): the exact L_ir × R projection is then used automatically, fastest and exact, no flag needed. This flag only bites when that constant R cannot be formed (free emission shape / redshift, or structured templates): True then samples the self-normalizing template at the filter effective wavelength instead of integrating it through each bandpass, much cheaper than the exact per-band integral (#622), at a band-shape approximation (smooth on a modified blackbody; up to a few percent on a band crossing a steep IR rise or a PAH complex). The energy balance is unaffected either way.

igm_fold: str = 'auto'
n_subbands: int | None = None

Sub-bands per filter for the multiplicative dust quadrature (#1122).

The dust screen is evaluated at n_subbands quadrature nodes per band rather than extrapolated from a single effective wavelength. Each node is the template’s own flux-weighted centroid in its sub-band, and both the nodes and the sub-band SSP × filter integrals are build-time constants, so the exact factorization of the fast path is preserved.

Converges as 1/K². Worst case over z ≤ 1, τ ≤ 2 (GALEX FUV): K=1 → 8.7 %, K=3 → 1.4 %, K=5 → 0.6 % (default), K=8 → 0.3 %. Runtime is cheaper than the Taylor form it replaces (0.93× its gradient at K=5), because that form carries a second tensor and a pow with a traced exponent.

Defaults to 5 when band_integration is "quadrature", and to 0 otherwise. Setting it to 0 explicitly is the legacy spelling of band_integration="effective_wavelength" (or "taylor", if taylor_correction=True accompanies it); prefer naming the scheme.

Only the multiplicative stellar screen needs this. Additive emitters (dust IR, radio, X-ray, AGN) factorize exactly through the rank-1/rank-K band response of #1107/#1117 and are unaffected. Nebular is not affected either, for the opposite reason: it never had a sub-band tensor to size, and since #1738 it does not need one, its screen is integrated through the band exactly, from the reddened continuum a dusty model materializes anyway. (This said “stellar + nebular” for as long as the nebular bucket was in fact screened at a single wavelength per band, which is the error #1738 removed.)

n_z: int = 250
taylor_correction: bool | None = None

First-order spectral-moment (Ψ) correction to the effective-wavelength dust attenuation (Zacharegkas+2025, #617). Superseded by n_subbands and off by default since #1122.

It applies A(λ_eff)·Φ + A'(λ_eff)·Ψ, i.e. it extrapolates the attenuation linearly away from one point per band. That is fine in the optical/IR and diverges in the rest-UV where the curve steepens: the residual is not the ~0.3 % once claimed here but +45 % (z=0.05) to +215 % (z=1) in GALEX FUV.

Deprecated since version Use: band_integration="taylor". This flag selected the scheme only in combination with n_subbands=0; on its own it was silently inert, which meant asking for Taylor returned quadrature.

z_max: float | None = None
z_min: float | None = None

Spectrum precomp

class tengri.SpectrumPrecomp(n_z: int = 100, z_min: float | None = None, z_max: float | None = None, taylor_correction: bool = True)[source]

Bases: object

Configuration for spectrum-grid LUT precomputation.

Pass this to SEDModel via approx= to enable spectroscopic LUT precomputation. The SSP × dust × IGM stack is precomputed at spectrum pixel centers (effective wavelengths in the galaxy rest frame) and cached per redshift. This is analogous to the photometric WavePrecomp LUT path but for spectroscopy.

The pixel grid is inherited from Observation.spectroscopy.wave_obs. For a free redshift, a redshift table is built so the rest-frame pixel grid wave_obs / (1 + z) can be interpolated at runtime; n_z / z_min / z_max tune that table (mirroring WavePrecomp). When redshift is Fixed, these are ignored.

The LUT applies the same three stages, in the same order, as the exact spectrum path: (1) the stellar velocity dispersion sigma_v_kms, a Gaussian in \(\ln\lambda\) applied to the stellar family on the model grid, before the pixels are sampled; (2) the IGM transmission; (3) the instrument kernel on the pixel grid, \(\sigma_{\rm eff} = \sqrt{\sigma_{\rm inst}^2\,s^2 - \sigma_{\rm lib}^2}\) on the stellar bucket (s is lsf_scale) and \(\sigma_{\rm inst}\,s\) on the dust-attenuated nebular bucket. Stage 1 acts on the model grid because point sampling aliases sharp stellar features, so broadening after sampling is not equivalent. With a fixed redshift and a fixed sigma_v_kms, every SSP template is broadened once at build and the per-draw cost is one weighted sum over the pixel table. With a free sigma_v_kms or a free redshift, the stellar weighted sum is formed on the full model grid, broadened with the draw’s dispersion and then sampled; the per-age family read by two-component dust is broadened row by row, which dominates the cost (a gradient step with free sigma_v_kms is roughly 15 times the exact path’s on the line-rich test fixture). A banded resolution_matrix cannot be carried by a per-pixel table: the model warns and uses the exact path. The model is differentiable in sigma_v_kms and lsf_scale.

Two routing rules follow from that cost. With a fixed sigma_v_kms and a free redshift, the SSP cube is broadened once at build (the velocity kernel does not depend on redshift) and each draw only interpolates it, so the cost is the unbroadened LUT’s; this holds unless a 4-D alpha grid or a free AGB weight modifies the cube per draw, which keeps the full-grid sum. With a free sigma_v_kms, an explicit SpectrumPrecomp() stays on the lookup table and warns once about the cost, and a joint observation’s photometry WavePrecomp() is not promoted onto the spectrum channel, which stays exact and says so once; approx="auto" selects the table only where it serves the pixels exactly (_spectrum_lut_serves_exactly()).

Parameters:
  • n_z (int, default 100) – Number of grid points in the free-z redshift table.

  • z_min (float or None) – Bounds of the free-z table. When None, taken from the redshift prior with 1% padding. Ignored for fixed redshift.

  • z_max (float or None) – Bounds of the free-z table. When None, taken from the redshift prior with 1% padding. Ignored for fixed redshift.

Notes

Emission lines are not representable by the per-pixel effective-wavelength LUT (they are delta-like). When a line-publishing nebular backend (Cue, CloudyGrid, CB19, MAPPINGS, Cue-NLR) is present, its discrete line luminosities are rasterized onto the pixel grid separately at projection time (design-doc option A); the smooth continuum still uses the LUT.

Examples

>>> from tengri import SEDModel, SpectrumPrecomp, WavePrecomp
>>> SEDModel(..., approx=SpectrumPrecomp())  # spectrum LUT path
>>> SEDModel(..., approx=SpectrumPrecomp(n_z=200))  # finer free-z table
>>> # Joint fit, accelerate both channels with independent LUT configs:
>>> SEDModel(..., approx=(WavePrecomp(n_z=200), SpectrumPrecomp()))
cache_key() → tuple[source]

Return a hashable cache key for this configuration, field by field.

Returns:

(type_qualname, ((field_name, baked_value), ...)).

Return type:

tuple

n_z: int = 100
taylor_correction: bool = True

Kept for API symmetry with WavePrecomp. The spectrum LUT evaluates dust attenuation at each pixel wavelength exactly (a pixel is a point, not a bandpass), so there is no effective-wavelength residual to correct and this flag does not change the spectroscopy result.

z_max: float | None = None
z_min: float | None = None

Feature precomp

class tengri.FeaturePrecomp(n_grid: int | dict[str, int] = 16, lines: tuple[float, ...] | None = None, ranges: dict | None = None)[source]

Bases: object

Configuration for the nebular precompute (the feature LUT path).

Pass this to SEDModel via approx= to serve the nebular calculation from a build-time lookup instead of the per-evaluation forward. It composes with WavePrecomp (photometry) and SpectrumPrecomp (spectroscopy).

Warning

The name misleads: this is not a line-channel-only optimization. For the Cue backend the grid replaces the emulator call itself, so a fit with no line channel at all benefits, often the most, because a photometry-only Cue fit otherwise re-runs Cue on every likelihood evaluation. Measured on a 10-parameter Cue model with free neb_logU / neb_logZ_gas, against an A/A control whose noise floor was 1.23x: a photometry-only fit’s compiled MAP step goes 0.645 s to 0.093 s (7x) on adding this to WavePrecomp. That saving needs a model with no sed_nebular consumer, so dust withdraws it. On a dusty Cue model also fitting a line channel, the pair is worth nothing over WavePrecomp alone: measured 1.642 s to 1.647 s against a 1.00x A/A floor, where the exact wave grid is 3.593 s (notebook 10_fastspecfit_joint_fit, compiled MAP step, fit-time approx= varied) — the photometry LUT carries all 2.19x of it. The line channel does not rescue it either: the table-served line path is the measured-line route of a backend whose lines sit in the SSP templates, and on a Cue fit the line channel is only ~8% of the compiled gradient to begin with, so the table has little to remove (see #2377). Earlier readings of “no gain with lines” timed arms that fit() had already resolved to one configuration; see the trap below. Measure before assuming either way, and quote a ratio only against its own noise floor; see docs/dev/api_migration_v0.x.md for the grid.

That a photometry-only fit was slower than the same fit with an extra data channel was a defect, not a property of the method, #1596, fixed: the "auto" fit policy now attempts this LUT for any photometry-only fit whose backend can tabulate, and #1683 extended that to a model built with approx=WavePrecomp(), which both fit resolvers had returned untouched.

Passing it explicitly still matters for prediction. No fit policy reaches model.predict_photometry / SEDModel.predict(), which run whatever the build-time approx= says, so a build-time opt-in is what a forward-model benchmark or a mock-generation loop is choosing. The converse is the trap: Fitter(approx="auto") (the default) re-resolves the build-time knob, so fit arms that differ only in SEDModel.build(approx=...) can be one configuration wearing three labels.

The line wavelengths default to those of Observation.line_fluxes, the model already knows which lines it is being fitted against, so the common case needs no arguments at all.

Which machinery is built depends on the nebular backend, because the two backends put their lines in physically different places:

  • Cue (and any backend publishing discrete line luminosities). Lines are linear in the ionizing photon rate, \(L_{\rm line} = Q_H \times \ell(\theta)\), with \(\ell\) independent of the SFH shape. A grid of \(\ell\) over the free ionization axes is built once (one Cue forward per node), and each evaluation reduces to \(Q_H \times \mathrm{interp}(\text{grid})\). Nothing downstream needs the full-wavelength SED, so XLA prunes the stellar einsum entirely.

  • Baked-in / wNE. The lines are inside the SSP templates, so they must be measured off the spectrum. A per-line window LUT of SSP integrals is built instead, and the measurement contracts it with SED-free SFH weights and the dust screen at the window centers.

Parameters:
  • n_grid (int or dict, default 16) –

    Grid points per free ionization axis (Cue backend only; ignored for baked-in, whose window LUT has no ionization axes). Denser is tighter.

    A scalar resolves every free axis alike. A dict {axis_name: n} resolves them independently, the griddable axes are met_logzsol, neb_logU and neb_logZ_gas, omitted axes take 16, and any other key raises rather than being silently ignored. Build cost is the product over free axes, so per-axis resolution is what keeps a model with several free axes affordable: spend points on the axis whose lines actually move, not on the one you barely vary.

  • lines (array_like or None, optional) – Rest-frame vacuum line wavelengths [Angstrom] to tabulate. None (default) takes them from Observation.line_fluxes.

  • ranges (dict, optional) – Override {param: (lo, hi)} grid bounds (Cue only). Defaults to each free parameter’s prior support. ranges['neb_logU'] is the HII support, not necessarily the final axis: whenever DIG mixing could be active it is still extended to cover the DIG-shifted query point, never clipped and never bypassed by supplying a range explicitly (#2222 review I2).

Notes

Explicit opt-in, by design. This is a lossy approximation, so it never activates on its own, a model acquires it only because the user asked for it. An observation that merely contains lines does not switch it on.

Accuracy (Cue). Reconstruction is exact at grid nodes and node-exact between them. Balmer lines are recombination lines (\(\propto Q_H\)) and converge quickly. Collisionally excited lines ([OIII], [NII], [SII]) depend on the shape of the ionizing spectrum, which varies along the metallicity axis; validate with a dense sweep strictly inside the grid range, never with random draws (they under-sample the structure and report bounds that are optimistic by orders of magnitude).

Accuracy (baked-in). The window LUT reconstructs the stellar + dust-screen spectrum only, so any component adding rest-frame flux is excluded, with one measured exception. A dust-IR component contributes a smooth continuum that is common to the line window and its sidebands, and so cancels in the continuum subtraction: the bias on the measured line flux is \(< 10^{-7}\) even at \(\tau_{\rm bc}=4,\ \tau_{\rm diff}=3\), against a 3% contamination of the continuum level itself. Dust IR is therefore allowed for lines. It is not allowed for spectral indices, where a break is a flux ratio and a smooth additive offset does not cancel.

Accuracy. Reproduces measured line fluxes to 4.8e-5–1.0e-3 relative (max over five prior draws on the wNE grid, #2376); against typical 5 % line errors that is ≲0.002 σ. The photometry half’s fidelity is measured separately (WavePrecomp, #1671).

DIG mixing (#2222). Served from this same table by two lookups – HII at neb_logU, DIG at neb_logU + neb_dig_delta_logU – mixed by neb_dig_frac: mix_dig_grid_reconstruction(). neb_logU joins the grid axes, and its range extends to cover the shifted query – even a range given explicitly via ranges= (review I2) – whenever neb_dig_frac is free or fixed non-zero, even when neb_logU is itself Fixed, UNLESS the extension is degenerate (neb_logU Fixed and neb_dig_delta_logU Fixed at exactly 0.0: the HII and DIG query points then coincide, DIG mixing is arithmetically the HII term, and no axis is built at all – review I3). Measured worst-case relative error over 10 seeds against the exact path: 1.17e-3 (photometry) / 1.41e-3 (lines) at neb_dig_frac = 0.3, versus 1.72e-3 / 2.04e-3 at neb_dig_frac = 0 on the same fixture – DIG mixing costs no accuracy relative to the table’s own baseline. Before #2222 a build with neb_dig_frac free or fixed non-zero raised ValueError here rather than reconstructing it; that refusal is gone.

JIT-compatible: the resulting line prediction is JIT- and gradient-safe; the one-time build is eager.

Examples

>>> from tengri import FeaturePrecomp, SEDModel, WavePrecomp
>>> # lines from the observation, photometry on the LUT path too:
>>> SEDModel.build(..., approx=(WavePrecomp(), FeaturePrecomp()))
>>> SEDModel.build(..., approx=FeaturePrecomp(n_grid=24))  # denser Cue grid
>>> # per-axis: dense where the lines move, coarse where they do not
>>> SEDModel.build(..., approx=FeaturePrecomp(n_grid={"met_logzsol": 24, "neb_logU": 8}))
cache_key() → tuple[source]

Return a hashable cache key for this configuration, field by field.

Returns:

(type_qualname, ((field_name, baked_value), ...)).

Return type:

tuple

lines: tuple[float, ...] | None = None
n_grid: int | dict[str, int] = 16
ranges: dict | None = None

Parameters

class tengri.Parameters(**kwargs)[source]

Bases: object

Parameter specification defining all model parameters and their priors.

A Parameters object defines the complete parameter set for a SEDModel, including both the mean SFH model(s) and all optional components (dust, nebular emission, AGN, etc.). Parameters can be sampled (for mock data generation) or used as priors for inference.

Parameters are specified as keyword arguments, each of which can be:

  • Scalar (int/float) → Fixed(value): parameter is constant

  • Tuple (lo, hi) → Uniform(lo, hi): shorthand for uniform prior

  • Distribution object: Uniform, Gaussian, LogUniform, LogNormal, StudentT, or Fixed

A Parameters object also stores model configuration settings (mean_sfh_type, dust_law, nebular mode, etc.) that control which components are enabled. These are not fittable parameters.

Parameters:

**kwargs (keyword arguments) – Model parameters (distribution objects or shorthands) and settings (see “Settings” section below).

Variables:
  • mean_sfh_type (list[str]) – Active SFH model(s). Read-only.

  • n_grid (int) – Grid size for stochastic SFH. Read-only.

  • stochastic (bool) – True if mean_sfh_type includes ‘field’. Read-only.

  • all_params (list[str]) – All valid parameter names (free + fixed).

  • free_params (list[str]) – Non-fixed parameter names (to be inferred).

  • fixed_params (list[str]) – Fixed parameter names (constants).

  • n_free (int) – Number of free parameters.

  • nebular_mode (str) – Nebular emission backend: ‘off’, ‘ssp’, ‘cue’, ‘cloudy’, ‘cb19’, ‘gutkin16’, ‘mappings’ or ‘mappings_agn’.

  • dust_model (str) – Dust model: ‘two_component’ or ‘single_component’.

  • dust_emission (str or None) – Dust emission template: ‘modified_blackbody’, ‘casey2012’, ‘dale2014’, etc.

  • agn_model (str or None) – AGN SED model, e.g. ‘kubota_done’, ‘skirtor’, ‘qsogen’.

  • apply_igm (bool) – If True, apply IGM absorption (Inoue+2014).

  • radio (bool) – If True, include radio synchrotron + AGN jet emission.

  • xray (bool) – If True, include X-ray (XRB + AGN) emission.

Raises:
  • ValueError – If parameter names are invalid for the selected mean_sfh_type.

  • ValueError – If nebular/dust/AGN settings are mutually incompatible.

Notes

Not JAX-traced: Parameters is the central user-facing object for configuring model parameters and their priors. Parameters objects cannot be created or modified inside a JAX gradient tape (jax.grad, jax.vmap, jax.jit). Create all Parameters objects at the Python level before tracing. Once created, a Parameters object is immutable; use the with_params() method to create modified copies.

Parameter auto-detection: If mean_sfh_type is not explicit, it is inferred from the parameter name prefixes (e.g., ‘sfh_dpl_alpha’ implies ‘dpl’ is active). The inferred type is normalized to a sorted list.

Mirror parameters: A parameter can be tied to another by passing the target name as a string instead of a distribution. Example: neb_logZ_gas="met_logzsol" ties gas metallicity to stellar.

Settings (model configuration, not fittable parameters)

mean_sfh_typestr or list[str]

SFH model(s). Composable: ["dpl", "field"]. Options: dpl, tsnorm, snorm, norm, lnorm, const, exp, dexp, burst, field. Default: ["dpl", "field"].

n_gridint

Grid size for stochastic SFH (latent dimensions). Default: 64.

stochasticbool

DEPRECATED. Use mean_sfh_type with/without ‘field’ instead.

Dust Attenuation Settings

dust_law_bcstr

Attenuation curve for birth cloud. Default: "power_law". Options: power_law, calzetti, kriek_conroy, smc, cardelli, salim, li08.

dust_law_diffstr

Attenuation curve for diffuse ISM. Default: same as dust_law_bc. Can be different for per-component control.

dust_law_nebstr or None

Attenuation curve for the nebular birth cloud. Default None: inherit dust_law_bc so the nebular continuum is reddened exactly like the youngest stars (bagpipes/FSPS/CIGALE). Set it to give HII-region emission its own birth-cloud curve while still sharing the diffuse ISM screen (dust_law_diff) with the stars.

dust_nebular_screenstr

Which screen attenuates the nebular continuum, the line catalog, and the fast-nebular fallback grid (#2234). One of "birth_cloud" (default), "diffuse", "none"/"off".

dust_shock_screenstr

Which screen attenuates the MAPPINGS V shock SED. One of "birth_cloud", "diffuse" (default), "none"/"off".

dust_agn_screenstr

Which screen attenuates AGN light. One of "birth_cloud", "diffuse", "none"/"off" (default): the AGN component runs after dust, unattenuated, and carries its own polar-dust screen (CIGALE convention). When screened, the AGN component runs before dust instead, and the absorbed AGN power joins the dust energy balance. Refused together with agn_norm="cigale_joint" (the default AGN cross-block normalization), which already reads the dust energy balance – see Parameters.__init__().

Dust Emission Settings

dust_emissionstr or None

IR emission model. Default: None (disabled). Options: "modified_blackbody", "casey2012", "dale2014", "draine_li2007", "draine_li2014", "dl07_tabulated", "astrodust", "bosa", "themis", "draine2021_pah".

dl07_grid_pathstr

Path to DL07 HDF5 template grid (for "dl07_tabulated").

Nebular Emission Settings

nebular_sspbool

Use SSP files with pre-included nebular emission (wNE files). No free nebular parameters. Default: False.

nebularbool

Enable CLOUDY grid nebular emission. Requires cloudy_grid_path. Default: False.

nebular_cuebool

Enable Cue neural emulator. Default weights loaded automatically. Default: False.

cloudy_grid_pathstr

Path to CLOUDY HDF5 grid. Required when nebular=True.

cue_weights_pathstr

Override default Cue weights path.

neb_ionizationstr

Ionization source for Cue: "ssp" (default), "agn" (future), "ssp+agn" (future).

AGN Settings

agn_modelstr or None

AGN SED model. Default: None (disabled). Options: "composable" (modular blocks), or deprecated monolithic names like "kubota_done_full" (physical disc), "qsogen" (empirical quasar), "skirtor" (clumpy torus templates).

Multi-wavelength Settings

radiobool

Enable radio synchrotron + AGN jet emission. Default: False.

xraybool

Enable X-ray (XRB + AGN corona) emission. Default: False.

IGM Settings

apply_igmbool

Apply Inoue+2014 IGM absorption. Default: True.

Metallicity Settings

evolving_metallicitybool

Replace met_logzsol with met_logzsol_0 (old stars) and met_logzsol_final (young stars) for a linear-in-log Z(t) ramp. Default: False.

met_interpstr

Metallicity interpolation method. Default: "smooth".

  • "smooth": Triweight kernel (same as DSPS, Hearin+2023). 8.5x smoother gradients at <1% speed overhead. Recommended.

  • "linear": 2-point linear in log(Z) (same as FSPS/Prospector).

lgmet_scatterfloat

Triweight kernel bandwidth in dex for met_interp="smooth". Default: 0.1 (DSPS default). Physically: intrinsic Z scatter.

Fittable Parameters (always available)

Parameter

Default

Description

met_logzsol

Uniform(-2, 0.2)

Stellar metallicity log10(Z/Zsun)

met_alpha_fe

Fixed(0.0)

[alpha/Fe] enhancement (dex)

dust_tau_bc

Uniform(0, 4)

Birth cloud V-band optical depth

dust_tau_diff

Uniform(0, 3)

Diffuse ISM V-band optical depth

dust_slope

Fixed(-0.7)

Power-law index (for power_law curve)

dust_f_obscuration

Fixed(0.0)

Unobscured fraction (Lower+2022)

dust_bump_strength

Fixed(0.0)

UV 2175A bump (Kriek&Conroy/Salim)

dust_delta

Fixed(0.0)

Attenuation slope modification

dust_Rv

Fixed(3.1)

R_V (Cardelli curve)

redshift

Fixed(0.1)

Source redshift

noise_frac_cal

Fixed(0.0)

Fractional calibration noise floor

noise_dof

Fixed(0.0)

Student-t degrees of freedom

Conditional Parameters (added when modules enabled)

Nebular (nebular=True):

neb_logU

Fixed(-3.0)

Ionization parameter log10(U)

neb_logZ_gas

Fixed(-0.3)

Gas metallicity (None = tie to stellar)

neb_fesc

Fixed(0.0)

Ionizing photon escape fraction

neb_fesc_lya

Fixed(1.0)

Ly-alpha escape fraction

Dust emission (dust_emission != None):

dust_T

Fixed(35)

Dust temperature (K) for graybody

dust_beta_ir

Fixed(1.6)

Emissivity index

dust_alpha_mir

Fixed(2.0)

MIR slope (Casey 2012)

dust_alpha_dale

Fixed(2.0)

Dale+2014 alpha

dust_umin

Fixed(1.0)

DL07/DL14 minimum radiation field

dust_gamma_dl

Fixed(0.01)

DL07/DL14 PDR fraction

dust_qpah

Fixed(2.5)

DL07/DL14 PAH mass fraction (%)

dust_alpha_dl14

Fixed(2.0)

DL14 radiation field slope (1-3)

dust_eta_balance

Fixed(1.0)

Energy balance deviation factor

AGN (agn_model != None):

agn_lum_ratio

Fixed(1.0)

L_AGN / L_stellar_bol (1.0 = full AGN)

agn_log_lbol

Fixed(10.0)

AGN log L_bol [log10(L_sun)] (parametric)

agn_alpha

Fixed(-1.0)

Disc power-law slope

agn_T_torus

Fixed(1000)

Torus temperature (K)

agn_tau_torus

Fixed(5.0)

Torus optical depth at 9.7 um

agn_torus_frac

Fixed(0.5)

Torus covering fraction

agn_log_mbh

Fixed(7.0)

Black hole mass log10(M/Msun)

agn_log_ledd

Fixed(-1.0)

Eddington ratio log10(L/L_Edd)

agn_tau_skirtor

Fixed(7.0)

SKIRTOR 9.7 um optical depth

agn_p_skirtor

Fixed(1.0)

SKIRTOR radial density gradient

agn_q_skirtor

Fixed(1.0)

SKIRTOR polar density gradient

agn_oa_skirtor

Fixed(40)

SKIRTOR opening angle (degrees)

agn_cos_inc

Fixed(0.5)

Cosine of inclination (0=edge-on)

Radio (radio=True):

radio_q_ir

Fixed(2.64)

FIR-radio correlation (Bell 2003)

radio_alpha_sf

Fixed(0.8)

SF synchrotron spectral index

radio_loudness

Fixed(0.0)

AGN radio-loudness log10(L_5GHz/L_B)

radio_alpha_agn

Fixed(0.7)

AGN radio spectral index

X-ray (xray=True):

xray_gamma_agn

Fixed(1.8)

AGN X-ray photon index

xray_delta_alpha_ox

Fixed(0.0)

Offset to L_2500-derived alpha_ox [dex]

Evolving metallicity (evolving_metallicity=True):

met_logzsol_0

Uniform(-2, 0.2)

Initial metallicity (oldest stars)

met_logzsol_final

Uniform(-2, 0.2)

Final metallicity (present-day)

Examples

Minimal parametric model:

spec = Parameters(
    mean_sfh_type="dpl",
    sfh_dpl_alpha=Uniform(0.5, 3.0),
    sfh_dpl_beta=Uniform(0.5, 3.0),
    sfh_dpl_tau_gyr=Uniform(0.5, 13.0),
    sfh_dpl_log_total_mass=Uniform(8.0, 12.5),
    met_logzsol=Uniform(-2.0, 0.5),
    dust_tau_bc=Uniform(0.0, 2.0),
    dust_tau_diff=Uniform(0.0, 2.0),
    redshift=Fixed(0.1),
)

Full model with all physics:

spec = Parameters(
    mean_sfh_type=["dpl", "field"],
    n_grid=256,
    # Dust attenuation
    dust_law_bc="kriek_conroy",
    dust_f_obscuration=Uniform(0.0, 0.5),
    dust_bump_strength=Uniform(0.0, 5.0),
    # Dust emission (DL07 tabulated templates)
    dust_emission="dl07_tabulated",
    dl07_grid_path="data/dl07_templates.h5",
    dust_umin=Uniform(0.1, 25.0),
    # Nebular (Cue neural emulator)
    nebular_cue=True,
    neb_logU=Uniform(-4.0, -1.0),
    neb_fesc_lya=Uniform(0.0, 1.0),
    # AGN (qsogen empirical quasar)
    agn_model="qsogen",
    agn_log_lbol=Uniform(6.42, 12.42),
    # IGM
    apply_igm=True,
    # Radio + X-ray
    radio=True,
    xray=True,
    # Evolving metallicity
    evolving_metallicity=True,
    met_logzsol_0=Uniform(-2.0, 0.2),
    met_logzsol_final=Uniform(-2.0, 0.2),
    met_alpha_fe=Uniform(-0.2, 0.6),
)
property all_params: list[str]

All parameter names (sorted, excludes settings).

Returns:

Sorted list of all fittable and fixed parameters (free_params + fixed_params).

Return type:

list[str]

cache_key() → tuple[source]

Return a hashable cache key for this parameter specification.

Returns:

Cache key derived from all parameter attributes.

Return type:

tuple

Notes

Includes which parameters are fixed/free via a tail entry; prior bounds and values are structural and covered through the Fitter engine’s key (#1972). Excludes _distributions and _param_registry as they are computed from parameter names alone.

property fixed_params: list[str]

Names of fixed parameters.

Returns:

Sorted list of parameter names with constant values (not varied during sampling or inference).

Return type:

list[str]

fixed_value(name: str) → float | str | None[source]

Get the fixed value of a parameter.

Parameters:

name (str) – Parameter name (e.g., "redshift").

Returns:

The fixed value. Numeric values are returned as float; string-valued enums as str; None if the parameter is not fixed or if the fixed value is None.

Return type:

float | str | None

Raises:
  • KeyError – If the parameter name is not in the specification.

  • ValueError – If the parameter is not fixed.

Examples

>>> from tengri import Parameters, Fixed
>>> spec = Parameters(redshift=Fixed(0.1))
>>> spec.fixed_value("redshift")
0.1
property free_params: list[str]

Names of free (non-fixed) parameters.

Returns:

Sorted list of parameter names that are not fixed (vary during sampling and inference).

Return type:

list[str]

get_distribution(name: str) → Distribution[source]

Get the prior distribution object for a parameter.

Parameters:

name (str) – Parameter name.

Returns:

The prior distribution object (Uniform, Gaussian, LogUniform, etc.) or Fixed for non-free parameters.

Return type:

Distribution

Raises:

KeyError – If parameter name is not valid for this model configuration.

Notes

For fixed parameters, the returned Distribution has is_fixed=True. For free parameters, the returned Distribution is one of Uniform, Gaussian, LogUniform, LogNormal, StudentT, or other prior types.

Examples

>>> from tengri import Parameters, Uniform
>>> spec = Parameters(
...     dust_tau_bc=Uniform(0, 4),
...     redshift=0.1,
... )
>>> prior = spec.get_distribution("dust_tau_bc")
>>> print(prior)
Uniform(0.0, 4.0)
get_fixed_values() → dict[str, float][source]

Extract all numeric fixed parameter values as a dict.

Fixed (non-free) parameters are constants that do not vary during inference. This method returns only the numeric ones; categorical Fixed parameters (strings) are excluded.

Parameters:

None

Returns:

Mapping of numeric fixed parameter names to their constant values. String-valued Fixed parameters are not included because they cannot be represented as float.

Return type:

dict[str, float]

Notes

This is useful for freezing parameters before optimization, or for passing to upstream code that requires a flat parameter vector.

Examples

>>> from tengri import Parameters
>>> spec = Parameters(
...     redshift=0.1,
...     dust_tau_bc=(0, 4),
... )
>>> fixed = spec.get_fixed_values()
>>> fixed["redshift"]
0.1
is_fixed(name: str) → bool[source]

Check whether a parameter is fixed (non-free).

Parameters:

name (str) – Parameter name (e.g., "redshift", "met_logzsol").

Returns:

True if the parameter is fixed; False if free.

Return type:

bool

Raises:

KeyError – If the parameter name is not in the specification.

Examples

>>> from tengri import Parameters, Uniform, Fixed
>>> spec = Parameters(
...     redshift=Fixed(0.1),
...     dust_tau_bc=Uniform(0, 4),
... )
>>> spec.is_fixed("redshift")
True
>>> spec.is_fixed("dust_tau_bc")
False
property mean_sfh_type: list[str]

SFH model type(s) as a list of strings.

Returns:

Normalized, sorted list of active SFH model names (e.g., [‘dpl’, ‘field’]).

Return type:

list[str]

merge_observation_params(**extra_params: Distribution) → Parameters[source]

Return a copy augmented with extra observation-level parameters.

Used by inference to inject emission-line amplitude parameters so they flow through bounds, prior penalty loops, and summary output without requiring special-casing in downstream code.

Parameters:

**extra_params (Distribution) – Mapping of parameter name → Distribution to add (e.g., eline_EW_Halpha=Uniform(0, 1000)).

Returns:

New Parameters instance with extra_params included in free_params. The original instance is not modified (immutable pattern).

Return type:

Parameters

Notes

This is distinct from with_params() in that all extra parameters are unconditionally added, whereas with_params() respects user-provided settings.

Examples

>>> from tengri import Parameters, Uniform
>>> spec = Parameters(redshift=0.1)
>>> spec_aug = spec.merge_observation_params(
...     eline_EW_Halpha=Uniform(0, 1000),
...     eline_EW_OIII=Uniform(0, 500),
... )
>>> print(spec_aug.n_free - spec.n_free)
2
property mirrors: dict[str, str]

{target_name: source_name}.

Returns:

Mapping of tied parameter names to their source parameters. When resolved, the target takes the value of the source.

Return type:

dict[str, str]

Type:

Parameter mirrors

property n_free: int

Number of free parameters (excludes sfh_field_xi).

Returns:

Count of all non-fixed parameters available for inference.

Return type:

int

property n_grid: int

GP grid size (only relevant when stochastic=True).

Returns:

Number of latent dimensions for stochastic SFH field.

Return type:

int

property n_latent: int

Flattened dimensionality of all free parameters (#1408).

Sum of each free parameter’s flattened size, including vector latents (e.g., sfh_field_xi). This is the true sampled dimension for MCMC/VI (what samplers actually see), as opposed to n_free which counts named parameters only.

Returns:

Flattened size of the free-parameter pytree. Equals n_free for scalar-only specs; exceeds n_free when vector latents are present (e.g., stochastic SFH fields).

Return type:

int

Notes

Used by auto-pick methods to choose NUTS vs raytrace (#1408): a field model with few named parameters but hundreds of field latents must route to the high-D sampler, not NUTS (dense mass matrix OOM risk).

Mirrors the accounting of Fitter._initialize_unbounded; the two must stay in agreement (asserted against the engine’s d_total in tests/inference/test_noise_broadcast_fix_1303.py). sample() is NOT the right source: its tree carries fixed/default parameters too, and the field latent under a non-free name.

resolve_mirrors(params: dict) → dict[source]

Copy mirrored parameter values from source to target.

For each mirror target → source, copies the sampled source value to the target parameter. Used after sampling to ensure tied parameters have identical values. Returns a new dict (immutable pattern).

Parameters:

params (dict[str, ndarray]) – Parameter name → sampled value. Must include all source parameters.

Returns:

New dict with mirrored values filled in. For each target, the sampled value of the source parameter is assigned. Non-mirrored parameters are unchanged.

Return type:

dict[str, ndarray]

Notes

Parameter tying: Mirrors are specified in __init__ by passing a source parameter name as a string instead of a distribution:

Parameters(
    neb_logZ_gas="met_logzsol",  # Gas Z tied to stellar Z
    ...
)

This is more elegant than using Fixed(0) + manual post-hoc copying.

Examples

>>> from tengri import Parameters
>>> spec = Parameters(
...     met_logzsol=(-2, 0.5),
...     neb_logZ_gas="met_logzsol",  # Mirror: neb → met
... )
>>> params = {"met_logzsol": -0.3, "neb_logZ_gas": 0.0}
>>> resolved = spec.resolve_mirrors(params)
>>> print(resolved["neb_logZ_gas"])
-0.3
sample(key: Array) → dict[str, Array][source]

Draw one random sample from free parameter prior distributions.

Samples free parameters from their priors and (if stochastic) generates the latent field ξ ~ N(0,I). Fixed parameters are not included. Mirrors are resolved (target ← source value).

A params dict carries free parameters only (#2296); fixed parameters are read from get_fixed_values() or Posterior.fixed_values.

Parameters:

key (jax.Array (PRNGKey)) – Random key for sampling.

Returns:

Free parameter name → sampled value. Sampled from their prior distributions. If stochastic, sfh_field_xi is an array of shape (n_grid,). Dictionary is immutable-ready (no direct mutation of values).

Return type:

dict[str, ndarray]

Notes

JIT-compatible: yes, safe to call inside jax.jit() on the key and parameters only (not on branching logic).

Stochastic SFH: When the model includes a GP field, sfh_field_xi is an independent N(0,1) vector of length n_grid. The SED model uses this to generate the stochastic log-SFR perturbations.

Examples

>>> import jax.random
>>> from tengri import Parameters, Uniform, Fixed
>>> spec = Parameters(
...     sfh_dpl_alpha=Uniform(0.5, 3.0),
...     sfh_dpl_beta=Uniform(0.5, 3.0),
...     redshift=Fixed(0.1),
... )
>>> key = jax.random.PRNGKey(42)
>>> samples = spec.sample(key)
>>> {"sfh_dpl_alpha", "sfh_dpl_beta"} <= set(samples)
True
Per-parameter substreams

Each parameter is drawn from a substream derived from its name (fold_in(key, crc32(name))), not from its position in a jax.random.split. This guarantees that a given parameter samples to the same value for a given key regardless of which other parameters are free in the spec.

Without this, two specs sharing a free parameter but differing in their free-parameter set (e.g. one adds dust_emission → free dust_T/dust_beta_ir) would split the key differently and draw the shared parameter to different values; a silent footgun that surfaced in #548 (an eta=0 “energy-balance” inequivalence that was really two galaxies with different sampled sfh_dpl_age_gyr) and #563. crc32 (not the salted built-in hash) keeps the mapping reproducible across processes.

sample_batch(key: Array, n: int) → dict[str, Array][source]

Draw n random samples from all parameter prior distributions.

Vectorized sampling via jax.vmap(). Each parameter becomes a batch of n independent samples.

Parameters:
  • key (jax.Array (PRNGKey)) – Random key for sampling.

  • n (int) – Number of independent samples to draw.

Returns:

Parameter name → array of samples. Each entry has shape:

  • (n,) for scalar parameters

  • (n, n_grid) for sfh_field_xi (stochastic SFH only)

Return type:

dict[str, ndarray]

Notes

JIT-compatible: yes. The function is implemented via jax.vmap() applied to the single-sample method.

Memory: For n=1000, a 20-parameter model, and n_grid=64 (stochastic), the output dict occupies roughly 100 KB.

Examples

>>> import jax.random
>>> from tengri import Parameters, Uniform
>>> spec = Parameters(
...     sfh_dpl_alpha=Uniform(0.5, 3.0),
...     dust_tau_bc=Uniform(0, 4),
... )
>>> key = jax.random.PRNGKey(0)
>>> batch = spec.sample_batch(key, n=100)
>>> print(batch["sfh_dpl_alpha"].shape)
(100,)
property stochastic: bool

Whether the model includes a GP field component.

Returns:

True if ‘field’ is in mean_sfh_type, False otherwise.

Return type:

bool

summary() → None[source]

Print a human-readable summary of the model configuration.

Displays SFH type, enabled components (nebular, dust, AGN, etc.), dimensionality, and a table of all parameters grouped by category (free first, then fixed). Useful for printing model status before fitting.

Use summary_str() if you need the underlying string (e.g. for logging); summary() itself prints and returns None, matching the rest of the discovery API (tengri.summary(), tengri.help(), etc.).

Parameters:

None

Returns:

Output is printed to stdout.

Return type:

None

Notes

Output includes:

  • SFH type and composition

  • Dimensions (n free, latent ξ, mirrored, fixed)

  • Enabled optional modules (nebular, dust_emission, AGN, etc.)

  • Tabular list of parameters with their distributions/values

Examples

>>> from tengri import Parameters, Uniform
>>> spec = Parameters(
...     mean_sfh_type="dpl",
...     sfh_dpl_alpha=Uniform(0.5, 3),
...     dust_tau_bc=Uniform(0, 4),
... )
>>> spec.summary()
Parameters  SFH: dpl
...
summary_str() → str[source]

Return the summary as a string (e.g. for logging or tests).

to_groups() → dict[source]

Convert this Parameters to nested-dict form.

Inverts tengri.parse_groups() by reconstructing the nested-dict structure that would reproduce this Parameters when re-parsed. Uses provenance metadata to collapse wildcard-expanded parameters and preserve explicit overrides.

Returns:

Nested-dict suitable for re-passing to tengri.parse_groups(**result) or SEDModel.build(ssp, **result).

Return type:

dict

See also

tengri.parse_groups

The inverse operation.

tengri.SEDModel.build

End-to-end model construction from nested dicts.

Notes

Provenance-aware collapsing: If this Parameters was built via parse_groups, provenance tags are used to collapse parameters that shared the same wildcard marker (FREE or Fixed(DEFAULT)) back into a single wildcard entry, with explicit overrides listed separately.

Wildcard emission convention: per-parameter entries are emitted first, then the wildcard LAST. It is spelled 'all_params' when it is the group’s only parameter directive, and 'other_params' when explicit per-param entries coexist beside it – reading as “the others” after the named overrides. Both spellings are exact synonyms on input; this only governs which spelling and position to_groups produces.

Flat-built fallback: If this Parameters was built via flat-kwarg Parameters(...), all parameters are listed explicitly (no wildcard).

Roundtrip guarantee: The output dict, when passed to parse_groups(**output), produces a Parameters with identical free/fixed partitions and distributions, and identical structural settings: including every group’s type.

The wording here used to stop at “distributions”, and that narrowness is why two rounds of structural loss went unnoticed: the guarantee was true as written while sfh['age_kernel'] (#964) and then the whole AGN block and neb={'type': 'ssp'} (#1777) were silently reverting to their defaults. Keep this sentence and parameters_to_groups’s copy of it in step.

Examples

A bare 'all_params': Fixed(DEFAULT) genuinely collapses to the sole-directive spelling. ('all_params': FREE on a bare sfh group would NOT collapse this cleanly: its met_* parameters – pinned via a special case when no met block is given – carry a wildcard tag that mismatches the rest of the group’s, so groups["sfh"] would list them explicitly instead.)

>>> from tengri import parse_groups, Fixed, DEFAULT
>>> spec = parse_groups(
...     sfh={"type": "dpl", "all_params": Fixed(DEFAULT)},
...     redshift=Fixed(0.05),
... )
>>> groups = spec.to_groups()
>>> groups["sfh"] == {"type": "dpl", "all_params": Fixed(DEFAULT)}  # sole directive
True
>>> roundtripped = parse_groups(**groups)
>>> spec.free_params == roundtripped.free_params
True
property valid_param_names: frozenset

Set of valid parameter names for this model configuration.

Returns:

Immutable set of all parameter names allowed for this configuration, excluding settings and model configuration keys.

Return type:

frozenset

validate(params: dict[str, Array]) → None[source]

Check that all parameter values respect their distribution bounds.

Useful before inference or after optimization to ensure no parameter has drifted outside its valid range.

Parameters:

params (dict[str, ndarray or float or str]) – Parameter name → value (sampled or optimized).

Returns:

Returns nothing. Raises an exception if validation fails.

Return type:

None

Raises:

ValueError – If any parameter is outside its bounds. Fixed parameters are always valid.

Notes

Missing parameters (not in dict) are silently ignored; this allows checking partial parameter sets.

Examples

>>> from tengri import Parameters, Uniform
>>> spec = Parameters(dust_tau_bc=Uniform(0, 4))
>>> params_valid = {"dust_tau_bc": 2.0}
>>> spec.validate(params_valid)  # OK
>>> params_bad = {"dust_tau_bc": 5.0}
>>> spec.validate(params_bad)  # Raises ValueError
Traceback (most recent call last):
    ...
ValueError: Parameter 'dust_tau_bc' = 5.0 is outside bounds [0.0, 4.0]
with_fixed_value(name: str, value: float) → Parameters[source]

Return a copy in which the Fixed parameter name is pinned to value.

Parameters:
  • name (str) – Name of a parameter that is currently Fixed.

  • value (float) – The new constant.

Returns:

New instance; the original is not modified. Unchanged (self) when value already equals the current constant.

Return type:

Parameters

Raises:

ParameterError – If name is unknown or is a free parameter (a free parameter has a prior, not a constant, so there is nothing to re-pin).

Notes

The seam a model rebuild uses to answer “the same model at a different constant” without touching the caller’s spec (e.g. the Fitter’s params_override={"redshift": z}). JIT-compatible: build-time only.

with_params(**kwargs) → Parameters[source]

Return a new Parameters with additional parameters merged in.

Creates an independent copy of this Parameters with extra parameters added (usually observation-level parameters like calibration or noise). User-defined parameters take precedence; if a name already exists in this spec, the new value is silently skipped (user intent is preserved).

Typically used internally by SEDModel to auto-inject noise and calibration parameters into the specification.

Parameters:

**kwargs – Parameter name → Distribution (or scalar/tuple shorthand). Only params not already explicitly provided by the user are added.

Returns:

New instance with merged parameters. The original is not modified (immutable pattern).

Return type:

Parameters

Notes

Immutability: The original Parameters object is never modified. A new Parameters instance is created via copy.copy(), with internal mutable structures (dicts) replaced with copies.

Parameter priority: User-provided parameters (via __init__) take absolute precedence. Auto-merged parameters are added only if their name is not in the user-provided set.

Examples

>>> from tengri import Parameters, Uniform
>>> spec = Parameters(redshift=0.1)
>>> # Merge in observation-level calibration parameters
>>> spec_aug = spec.with_params(
...     cal_offset_aper=Uniform(-0.1, 0.1),
...     noise_frac=Uniform(0, 0.05),
... )
>>> print(sorted(set(spec_aug.all_params) - set(spec.all_params)))
['cal_offset_aper', 'noise_frac']

Prediction

class tengri.Prediction(model, params)[source]

Bases: object

Lazy prediction object with on-demand computation of derived quantities.

Created via model.predict(params). Properties are computed on first access and cached. The cache is shared across all property groups (sfh, sed, lines, radio, xray, ionizing), so related quantities share the expensive intermediates.

Parameters:
  • model (SEDModel) – The tengri SEDModel instance.

  • params (dict) – Parameter values (public names).

Variables:
  • sfh (SFHProperties) – Star formation history derived quantities. Lazy accessor.

  • sed (SEDProperties) – Spectral energy distribution derived quantities. Lazy accessor.

  • lines (LineProperties) – Emission line luminosities and diagnostic ratios. Lazy accessor.

  • radio (RadioProperties) – Radio-derived quantities from empirical relations. Lazy accessor.

  • xray (XRayProperties) – X-ray derived quantities from empirical relations. Lazy accessor.

  • ionizing (IonizingProperties) – Ionizing photon budget quantities. Lazy accessor.

Returns:

Lazy prediction object with cached computed quantities.

Return type:

Prediction

Notes

This class is NOT JIT-compatible due to Python-level caching. For batch computations over many parameter sets (MCMC chains, mock catalogs), use SEDModel.predict_properties(), the one JIT/vmap-safe surface for derived quantities, or SEDModel.predict_photometry() on an inference hot path. Both return plain JAX values suitable for jax.vmap(), jax.jit(), and jax.grad().

Examples

Two equivalent ways to access derived quantities:

>>> pred = model.predict(params)
>>> pred.stellar_mass  # flat shortcut
>>> pred.sfh.stellar_mass  # grouped form (same value)
>>> pred.dn4000  # flat
>>> pred.sed.dn4000  # grouped
>>> pred.halpha  # flat
>>> pred.lines.halpha  # grouped

The grouped form (pred.sfh, pred.sed, pred.lines, pred.radio, pred.xray, pred.ionizing) exposes every derived quantity. The top-level shortcuts cover the most-used quantities for quick access; for less-common ones use the grouped form. Both share the same lazy cache, so accessing a quantity by either route triggers computation only once.

Accessing the full SED or photometry:

>>> pred.sed_array  # shape (n_wave,)
>>> pred.photometry()  # shape (n_filters,) -- call it, it is a method

For batch computation, use JIT-compatible methods instead:

>>> batch = jax.vmap(lambda p: model.predict_properties(p, names=("stellar_mass",)))(
...     params_batch
... )
property balmer_break

Balmer break flux ratio. Same as pred.sed.balmer_break.

property balmer_decrement

Hα/Hβ flux ratio. Same as pred.lines.balmer_decrement.

property dn4000

D_n(4000) break ratio. Same as pred.sed.dn4000.

property fuv_flux

FUV flux at 1500 Å [erg/s/cm²]. Same as pred.sed.fuv_flux.

property fuv_flux_intrinsic

Dust-free FUV flux. Same as pred.sed.fuv_flux_intrinsic.

property halpha

Hα 6564 Å luminosity [Lsun]. Same as pred.lines.halpha.

property hbeta

Hβ 4862 Å luminosity [Lsun]. Same as pred.lines.hbeta.

ionizing
property irx

Infrared excess L_TIR / L_UV(1600 Å). Same as pred.sed.irx.

property l_bol

Bolometric luminosity [L☉]. Same as pred.sed.l_bol.

property l_dust_absorbed

Dust-absorbed luminosity [L☉]. Same as pred.sed.l_dust_absorbed.

property l_tir

Total infrared (8–1000 μm) luminosity [L☉]. Same as pred.sed.l_tir.

lines
property log_q_h

log10 ionizing photon production rate [dex re s⁻¹].

Same as pred.ionizing.log_q_h.

property luminosity_weighted_age_gyr

Luminosity-weighted age [Gyr]. Same as pred.sed.luminosity_weighted_age_gyr.

Both pred.sfh and pred.sed define this; the top-level shortcut forwards to the SED version (canonical “luminosity-weighted” using the attenuated stellar SED).

property luminosity_weighted_metallicity

Luminosity-weighted log₁₀(Z/Z☉).

Same as pred.sed.luminosity_weighted_metallicity.

property m_uv

Absolute magnitude at 1500 Å. Same as pred.sed.m_uv.

magnitudes(filters=None, approx=False, *, fast=<unset>)[source]

AB magnitudes through filters.

Computes AB magnitudes by converting observed flux densities from photometry() using the AB magnitude system.

Parameters:
  • filters (sequence of str or FilterCurve, optional) – Filter names or FilterCurve objects. If None, uses the filters configured at model build time.

  • approx (bool, optional) – If True, use the build-time WavePrecomp LUT (20–50× faster, and an approximation). Only valid when the model was built with approx=WavePrecomp(...). If filters is also provided, raises ValueError. Default: False (exact path). See photometry() for the measured size of the approximation.

  • fast (bool, optional) – Deprecated spelling of approx. Removed in v1.0.

Returns:

AB magnitudes [dimensionless].

Return type:

ndarray, shape (n_filters,)

Raises:
  • ValueError – If the model was not built with approx=WavePrecomp(...) but approx=True is requested, or if both filters and approx=True.

  • ValueError – If no photometry is configured on the model.

  • TypeError – If both approx and the deprecated fast are passed with contradictory values.

Notes

JIT-compatible: no, Python method delegating to photometry(). Use in postprocessing, not inside jax.jit().

Semantics: Computes photometry() in the requested mode (exact, approximate, or runtime filters), then converts flux densities to AB magnitudes via:

\[m_{\mathrm{AB}} = -2.5 \log_{10}(f_\nu / f_0)\]

where f_0 = 3.631×10⁻²⁰ erg s⁻¹ cm⁻² Hz⁻¹ is the AB zeropoint.

References

Oke & Gunn 1983, ApJ, 266, 713, AB magnitude definition.

Examples

>>> pred = model.predict(params)
>>> mags = pred.magnitudes()  # AB mags, shape (n_filters,)
>>> mags[0]  # first filter AB magnitude
20.5
property mass_weighted_age_gyr

Mass-weighted stellar age [Gyr]. Same as pred.sfh.mass_weighted_age_gyr.

property mass_weighted_metallicity

Mass-weighted log₁₀(Z/Z☉). Same as pred.sfh.mass_weighted_metallicity.

property nuv_flux

NUV flux at 2300 Å [erg/s/cm²]. Same as pred.sed.nuv_flux.

property nuv_flux_intrinsic

Dust-free NUV flux. Same as pred.sed.nuv_flux_intrinsic.

property obs_sed

pred.obs_sed().

The rest-frame SED moved onto the observed-frame wavelength axis, with IGM (and DLA) absorption applied. “Observed” refers to the frame, not to a flux conversion.

Parameters:

wave_obs (array_like, shape (n_out,), optional) – Observed-frame wavelength grid to resample onto [Angstrom], the same frame as wave_obs, and as spectrum(). Default None returns the SED on the model’s own grid.

Returns:

Luminosity density L_nu [erg/s/Hz], not a flux.

Return type:

ndarray, shape (n_wave,)

Notes

Units, read this. This returns L_nu [erg/s/Hz], exactly like rest_sed(). It does NOT apply the cosmological dimming factor (1+z) / (4 pi d_L^2). The only differences from rest_sed() are the wavelength axis and IGM absorption; at z = 3 the two arrays are identical everywhere above rest-frame Lyman-alpha.

The distance is applied at the projection step, not here, see observation/redshift_kernel.py. The surfaces that return a genuine flux F_nu [erg/s/cm^2/Hz] are photometry(), magnitudes() and spectrum(). Integrating obs_sed() as if it were a flux is wrong by ~57 orders of magnitude.

(This docstring previously claimed the opposite, “Returns F_nu, not L_nu … accounts for the (1+z)/(4 pi d_L^2) dimming factor”. It was false, and the claim had propagated into the naming contract. Measured, not assumed.)

JIT-compatible: no, a postprocessing accessor.

Naming contract: SED = panchromatic model-grid array (rest_sed() / obs_sed()); spectrum = instrument-grid, LSF-convolved, calibrated observable (spectrum()).

Wavelength frame: observed-frame (rest x (1+z)) [Angstrom]; the matching axis is wave_obs.

Absorption: Includes:

  • IGM Lyman absorption (Inoue et al. 2014 [tengri.Prediction.obs_sed-1]) when igm=True

  • DLA (damping wing absorption) when dla=True

  • Reionization epoch (CGM) when configured

  • Patchy reionization when configured

References

[tengri.Prediction.obs_sed-1]

Inoue A. K., et al. 2014, MNRAS, 442, 1805, IGM absorption tables and mean transmission.

Examples

>>> pred = model.predict(params)
>>> fnu = pred.obs_sed()  # the model's own grid
>>> fnu = pred.obs_sed(np.logspace(3, 5, 500))  # your grid
>>> plt.loglog(pred.wave_obs, pred.obs_sed())

See also

rest_sed

Rest-frame SED (no absorption, no redshift).

wave_obs

The observed-frame wavelength axis this SED lives on.

spectrum

Instrument-grid observable (LSF-convolved).

Type:

Observed-frame panchromatic SED, call it

property oiii_5007

[O III] 5007 Å luminosity [Lsun]. Same as pred.lines.oiii_5007.

photometry(filters=None, approx=False, *, fast=<unset>)[source]

Observed-frame photometric flux densities.

Integrates the model SED through each filter and applies the cosmological dimming, returning \(F_\nu\) in the observer frame. For the same quantity as AB magnitudes, see magnitudes().

Exact by default, approximate by choice. The default integrates the full SED, including on a model built with approx=WavePrecomp(...), where the lean predict_photometry() would instead read the lookup table. That is deliberate: pred.photometry() must mean the same thing on every model. The LUT is an approximation carrying real error, so you reach it only by asking for it, with approx=True.

The keyword is spelled approx because it selects exactly the object installed at build time by SEDModel.build(..., approx=WavePrecomp(...)) one mechanism, one name at both ends. It was called fast until 2026-08, which named the benefit and hid the cost; that spelling still works and emits a DeprecationWarning.

Parameters:
  • filters (sequence of str or FilterCurve, optional) – Filter names (e.g., ["jwst_f356w", "jwst_f444w"]) or FilterCurve objects. If None, uses the filters configured at model build time.

  • approx (bool, optional) – If True, use the build-time WavePrecomp LUT (20–50× faster, and an approximation). Only valid when the model was built with approx=WavePrecomp(...). If filters is also provided, raises ValueError. Default: False (exact path).

  • fast (bool, optional) – Deprecated spelling of approx. Removed in v1.0.

Returns:

Observed-frame flux densities [erg/s/cm²/Hz].

Return type:

ndarray, shape (n_filters,)

Raises:
  • ValueError – If the model was not built with approx=WavePrecomp(...) but approx=True is requested, or if both filters and approx=True.

  • ValueError – If no photometry is configured on the model.

  • TypeError – If both approx and the deprecated fast are passed with contradictory values.

Notes

JIT-compatible: no, Python method with caching. Use in postprocessing, not inside jax.jit().

Default (exact) path: integrates state.sed_intrinsic through each filter via project_photometry(), the same kernel the likelihood uses, on the ForwardState this Prediction already cached, so it costs the filter integration and not a second forward pass.

Approximate path (approx=True): Uses the precomputed photometric LUT (filter effective wavelengths × SSP grid). Requires approx=WavePrecomp(...) at model build time. Runtime cost is ~150 μs per forward model (20–50× speedup for typical models).

How wrong is it? Measured against this exact path on a 12-band tsnorm + two-component-dust model, worst band per redshift: 0.085 % at z = 0.05, 1.5 % at z = 1, 10.4 % at z = 1.5, 83 % at z = 3, but the large numbers are all GALEX FUV, which by z = 2 is below the Lyman break and carries 1e-7 of the g-band flux. On bands carrying flux the error is 1e-4 to 1e-2 (sdss_g is 1.38 % at z = 3). The error is set by WavePrecomp’s band_integration, not by n_z (measured: 250 -> 1000 nodes moves it by nothing). It is a bias, so per #1671 it enters the posterior gradient multiplied by SNR. Full numbers: bench/reports/2026-08-17_wave_precomp_accuracy.md.

Runtime filters (filters=...): Constructs a runtime Photometry object from filter names or objects. Cached on self._photometry_cache keyed by filter tuple for zero-cost repeat calls. Issues a one-time UserWarning (exact-path cost). The exact path is always used; a LUT built for one filter set cannot cover filters it was never built for.

Examples

Default exact path:

>>> pred = model.predict(params)
>>> phot = pred.photometry()  # shape (n_filters,)
>>> phot.shape
(8,)

Approximate path (requires WavePrecomp):

>>> phot_lut = pred.photometry(approx=True)  # 20-50x faster, approximate
>>> bool(jnp.allclose(phot, phot_lut, rtol=1e-2))
True

Runtime filter set:

>>> phot_custom = pred.photometry(filters=["jwst_f356w", "jwst_f444w"])
>>> phot_custom.shape
(2,)
properties
property q_h

Retired, no alias (#1206 §C). Raises KeyError naming log_q_h.

Same as pred.ionizing.q_h.

radio
property rest_sed

pred.rest_sed().

A uniform callable with a default, like photometry(), magnitudes() and spectrum() (contract §4b.3).

Parameters:

wave (array_like, shape (n_out,), optional) – Rest-frame wavelength grid to resample onto [Angstrom]. Default None returns the SED on the model’s own grid (wave_rest), with no interpolation.

Returns:

Rest-frame luminosity density [erg/s/Hz].

Return type:

ndarray, shape (n_wave,) or (n_out,)

Notes

JIT-compatible: no, a postprocessing accessor. Use the lean model.predict_photometry / predict_properties shortcuts inside jax.jit().

Naming contract: SED = panchromatic model-grid array (rest_sed() / obs_sed()); spectrum = instrument-grid, LSF-convolved, calibrated observable (spectrum()).

Grid: the model’s SSP grid, auto-extended when dust emission, radio or X-ray components are configured. The axis is wave_rest, the SED array does not carry it.

Resampling is jnp.interp onto wave, bit-exact with the wavelength argument of the deprecated model.predict_rest_sed.

Examples

>>> pred = model.predict(params)
>>> lnu = pred.rest_sed()  # the model's own grid
>>> lnu = pred.rest_sed(np.logspace(3, 5, 500))  # your grid
>>> plt.loglog(pred.wave_rest, pred.rest_sed())

See also

obs_sed

Observed-frame SED (redshifted + IGM + DLA).

wave_rest

The wavelength axis this SED lives on.

Type:

Rest-frame panchromatic SED, call it

property rest_uv_color

top-hats 3200–3900 Å minus 5000–5800 Å.

Same as pred.sed.rest_uv_color.

Type:

U-V AB color

sed
property sed_array

Full rest-frame SED array.

Returns:

Total spectral energy distribution [erg/s/Hz].

Return type:

ndarray, shape (n_wave,)

Notes

JIT-compatible: no, Python property accessor. Use in postprocessing, not inside jax.jit().

sfh
property sfr_100myr

SFR averaged over last 100 Myr [M☉/yr]. Same as pred.sfh.sfr_100myr.

property sfr_10myr

SFR averaged over last 10 Myr [M☉/yr]. Same as pred.sfh.sfr_10myr.

spectrum(wave_obs=None, approx=False, *, fast=<unset>)[source]

Instrument-grid, LSF-convolved spectrum.

Computes the observed-frame spectrum at the instrument wavelength grid, convolved with the line-spread function and calibrated.

Parameters:
  • wave_obs (ndarray, optional) – Custom observed-frame wavelength grid [Angstrom]. If None, uses the grid configured in the spectroscopy setup at model build time.

  • approx (bool, optional) – If True, use the build-time SpectrumPrecomp LUT. Only valid when the model was built with approx=SpectrumPrecomp(...). Default False, the exact projector. Named for the object it selects, which is the same word the build takes.

  • fast (bool, optional) – Deprecated spelling of approx. Removed in v1.0.

Returns:

Observed-frame flux density [erg/s/cm^2/Hz].

Return type:

ndarray, shape (n_wave_obs,)

Raises:
  • ValueError – If no spectroscopy is configured on the model, or if approx=True on a model not built with approx=SpectrumPrecomp(...).

  • TypeError – If both approx and the deprecated fast are passed with contradictory values.

Notes

JIT-compatible: no, Python accessor delegating to SEDModel.predict_spectrum(). Use in postprocessing, not inside jax.jit().

Naming contract: SED = panchromatic model-grid array (rest_sed() / obs_sed()); spectrum = instrument-grid, LSF-convolved, calibrated observable (spectrum()).

Preprocessing: The instrument LSF (Gaussian with resolution R), velocity broadening, and calibration polynomial all apply on top of the SED redshift.

Examples

>>> pred = model.predict(params)
>>> spec = pred.spectrum()  # shape (n_wave,)
>>> spec.shape
(2048,)
property ssfr

Specific SFR [yr⁻¹]. Same as pred.sfh.ssfr.

property stellar_mass

Total stellar mass formed [M☉]. Same as pred.sfh.stellar_mass.

property stellar_mass_surviving

Surviving stellar + remnant mass [M☉]. Same as pred.sfh.stellar_mass_surviving.

property uv_slope_beta

UV slope β in f_λ ∝ λ^β. Same as pred.sed.uv_slope_beta.

property wave_obs

Observed-frame wavelength grid.

Returns the observed-frame wavelength grid, computed as the rest-frame wavelengths shifted by redshift: wave_obs = wave_rest * (1 + z). Pairs exactly with obs_sed.

Returns:

Observed-frame wavelengths [Angstrom].

Return type:

ndarray, shape (n_wave,)

Notes

JIT-compatible: no, Python property accessor. Use in postprocessing, not inside jax.jit().

The redshift value is resolved through the model’s spec:

  • If redshift is a free parameter, it is taken from params.

  • If redshift is fixed in the spec, the fixed value is used.

  • If redshift is not found in either place, raises KeyError.

This design avoids the silent bugs (#1097, #1124, #1127) that arose from using params.get("redshift", 0.0), which can silently return a default value instead of raising an error when redshift is absent.

Examples

>>> pred = model.predict(params)
>>> wave_obs = pred.wave_obs  # shape (n_wave,)
>>> sed_obs = pred.obs_sed()  # the SED is a call, not an attribute
>>> wave_obs.shape == sed_obs.shape
True
>>> # For a model with Fixed redshift:
>>> (wave_obs / wave_rest - 1).mean()  # should be z
0.1

See also

wave_rest

Rest-frame wavelength grid.

obs_sed

Observed-frame SED on this grid.

property wave_rest

Rest-frame wavelength grid.

Returns the wavelength grid on which rest_sed and obs_sed are evaluated. The grid is determined by the model’s SSP wavelength array, optionally extended for dust emission (IR), radio, and X-ray components.

Returns:

Rest-frame wavelengths [Angstrom].

Return type:

ndarray, shape (n_wave,)

Notes

JIT-compatible: no, Python property accessor. Use in postprocessing, not inside jax.jit().

Pairs exactly with rest_sed and forms the x-axis for plotting the rest-frame SED. The same wavelength grid is shared with derived properties (e.g., l_bol, l_tir, fuv_flux) that integrate over it.

Examples

>>> pred = model.predict(params)
>>> wave_rest = pred.wave_rest  # shape (n_wave,)
>>> sed_rest = pred.rest_sed()  # the SED is a call, not an attribute
>>> wave_rest.shape == sed_rest.shape
True

See also

wave_obs

Observed-frame wavelength grid.

rest_sed

Rest-frame SED on this grid.

property xi_ion

Ionizing photon production efficiency [Hz·erg⁻¹]. Same as pred.ionizing.xi_ion.

xray

Prior predictive

class tengri.PriorPredictive(flux: Array | None, sfh: Array, params: dict, _model: object = None)[source]

Bases: object

Results of a prior predictive check.

Parameters:
  • flux (jnp.ndarray or None) – Predicted photometry draws [erg/s/cm²/Hz], shape (n, n_filters). None if the model has no filters.

  • sfh (jnp.ndarray) – SFR on log-age grid [Msun/yr], shape (n, n_grid).

  • params (dict) – Drawn parameter samples, each of shape (n,).

Returns:

Results container with draws from the prior predictive distribution.

Return type:

PriorPredictive

Variables:
  • flux (jnp.ndarray or None) – Predicted photometry draws [erg/s/cm²/Hz], shape (n, n_filters). None if the model has no filters.

  • sfh (jnp.ndarray) – SFR on log-age grid [Msun/yr], shape (n, n_grid).

  • params (dict) – Drawn parameter samples, each of shape (n,).

  • _model (object) – Back-reference to the parent model.

Notes

Use check_finite() to diagnose NaN/Inf in prior draws before inference.

Examples

import jax
from tengri import SEDModel, Parameters, Uniform

spec = Parameters(sfh_dpl_alpha=Uniform(0.5, 4.0), sfh_dpl_beta=Uniform(0.5, 4.0))
model = SEDModel(spec, ssp_data, filter_names=["sdss_r", "sdss_i"])
ppc = model.prior_predictive(n=200, seed=0)
ppc.flux.shape  # (200, 2)
ppc.sfh.shape  # (200, n_grid)
check = ppc.check_finite()
check["ok"]  # True if no NaN/Inf
check_finite() → dict[source]

Check for NaN/Inf in flux draws.

Parameters:

self (PriorPredictive) – The prior predictive result container.

Returns:

Diagnostic dict with keys:

  • "n_nan": count of NaN values [dimensionless]

  • "n_inf": count of Inf values [dimensionless]

  • "frac_bad": fraction of bad (NaN or Inf) values [dimensionless]

  • "ok": bool, True if no NaN/Inf found

Return type:

dict

Notes

JIT-compatible: no, uses Python-level checking and warnings.

flux: Array | None
params: dict
sfh: Array

SED result

class tengri.SEDResult(wavelength: jnp.ndarray, sed: jnp.ndarray)[source]

Bases: NamedTuple

Rest-frame or observed-frame SED with its wavelength grid.

Container for SED predictions returned by predict_rest_sed() and predict_obs_sed().

Parameters:
  • wavelength (ndarray, shape (n_wave,)) – Wavelength grid. [Angstrom]

  • sed (ndarray, shape (n_wave,)) – Spectral luminosity density for rest-frame SED or flux density for observed-frame. [erg/s/Hz] for rest-frame, [erg/s/cm^2/Hz] for observed-frame.

Returns:

Named tuple with wavelength and SED arrays.

Return type:

SEDResult

Variables:
  • wavelength (ndarray, shape (n_wave,)) – Wavelength grid. [Angstrom]

  • sed (ndarray, shape (n_wave,)) – Spectral luminosity density for rest-frame SED or flux density for observed-frame. [erg/s/Hz] for rest-frame, [erg/s/cm^2/Hz] for observed-frame.

Notes

This is a NamedTuple (JAX pytree), making it compatible with jax.jit and jax.vmap. Fields are JAX arrays.

sed: Array

Alias for field number 1

wavelength: Array

Alias for field number 0

SFH quantities

class tengri.SFHQuantities(stellar_mass: Array, stellar_mass_surviving: Array, sfr_100myr: Array, sfr_10myr: Array, ssfr: Array, mass_weighted_age_gyr: Array, mass_weighted_metallicity: Array)[source]

Bases: NamedTuple

Derived quantities from the star formation history.

All fields are JAX arrays (scalars). This is a proper JAX pytree, so it works with jax.jit, jax.vmap, and jax.grad.

Variables:
  • stellar_mass (jnp.ndarray) – Total formed stellar mass [Msun].

  • stellar_mass_surviving (jnp.ndarray) – Surviving mass in living stars + remnants [Msun]. Returns NaN if the mass-remaining table was not loaded.

  • sfr_100myr (jnp.ndarray) – Star formation rate averaged over the last 100 Myr [Msun/yr].

  • sfr_10myr (jnp.ndarray) – Star formation rate averaged over the last 10 Myr [Msun/yr].

  • ssfr (jnp.ndarray) – Specific star formation rate SFR/M* [1/yr].

  • mass_weighted_age_gyr (jnp.ndarray) – Mass-weighted stellar age [Gyr].

  • mass_weighted_metallicity (jnp.ndarray) – Mass-weighted metallicity log10(Z), evolving-Z aware.

Returns:

  • This is a NamedTuple (JAX pytree) returned by

  • SEDModel.predict_sfh_quantities().

Notes

JAX-compatible array container. All fields are JAX arrays compatible with jax.jit and jax.vmap. Returned by SEDModel.predict_sfh_quantities() and Prediction.sfh when accessed.

Examples

>>> import jax.numpy as jnp
>>> from tengri import SFHQuantities
>>> q = SFHQuantities(
...     stellar_mass=jnp.array(1e10),
...     stellar_mass_surviving=jnp.array(6e9),
...     sfr_100myr=jnp.array(5.0),
...     sfr_10myr=jnp.array(8.0),
...     ssfr=jnp.array(5e-10),
...     mass_weighted_age_gyr=jnp.array(3.5),
...     mass_weighted_metallicity=jnp.array(-0.5),
... )
>>> float(q.stellar_mass)
10000000000.0
>>> "stellar_mass" in q._fields and "sfr_100myr" in q._fields
True
mass_weighted_age_gyr: Array

Alias for field number 5

mass_weighted_metallicity: Array

Alias for field number 6

sfr_100myr: Array

Alias for field number 2

sfr_10myr: Array

Alias for field number 3

ssfr: Array

Alias for field number 4

stellar_mass: Array

Alias for field number 0

stellar_mass_surviving: Array

Alias for field number 1

SED quantities

class tengri.SEDQuantities(l_bol: Array, l_tir: Array, l_dust_absorbed: Array, irx: Array, uv_slope_beta: Array, dn4000: Array, balmer_break: Array, m_uv: Array, fuv_flux: Array, nuv_flux: Array, fuv_flux_intrinsic: Array, nuv_flux_intrinsic: Array, rest_uv_color: Array, luminosity_weighted_age_gyr: Array, luminosity_weighted_metallicity: Array)[source]

Bases: NamedTuple

Derived quantities from the spectral energy distribution.

All fields are JAX arrays. Proper JAX pytree for jit/vmap.

Variables:
  • l_bol (jnp.ndarray) – Bolometric luminosity [Lsun].

  • l_tir (jnp.ndarray) – Total infrared luminosity 8–1000 μm [Lsun].

  • l_dust_absorbed (jnp.ndarray) – Dust-absorbed luminosity [Lsun]. Returns NaN if no intrinsic SED.

  • irx (jnp.ndarray) – Infrared excess log10(L_TIR / νLν_1600) [dimensionless].

  • uv_slope_beta (jnp.ndarray) – UV spectral slope β in range 1250–2600 Å [dimensionless].

  • dn4000 (jnp.ndarray) – Narrow 4000 Å break, Balogh et al. 1999 [dimensionless].

  • balmer_break (jnp.ndarray) – Modified Balmer break, Wang et al. 2024 [dimensionless].

  • m_uv (jnp.ndarray) – Absolute UV magnitude at rest-frame 1500 Å [AB].

  • fuv_flux (jnp.ndarray) – Mean flux density in FUV 1000–1700 Å [erg/s/Hz].

  • nuv_flux (jnp.ndarray) – Mean flux density in NUV 1700–3200 Å [erg/s/Hz].

  • fuv_flux_intrinsic (jnp.ndarray) – Dust-free FUV flux [erg/s/Hz]. Returns NaN if no intrinsic SED.

  • nuv_flux_intrinsic (jnp.ndarray) – Dust-free NUV flux [erg/s/Hz]. Returns NaN if no intrinsic SED.

  • rest_uv_color (jnp.ndarray) – U-V AB color: top-hats 3200–3900 Å minus 5000–5800 Å on rest-frame L_nu [AB magnitudes].

  • luminosity_weighted_age_gyr (jnp.ndarray) – Luminosity-weighted age [Gyr].

  • luminosity_weighted_metallicity (jnp.ndarray) – Luminosity-weighted metallicity log10(Z).

Returns:

  • This is a NamedTuple (JAX pytree) returned by

  • SEDModel.predict_sed_quantities().

Notes

JAX-compatible array container. All fields are JAX arrays compatible with jax.jit and jax.vmap. Returned by SEDModel.predict_sed_quantities() and Prediction.sed when accessed.

Examples

Access via Prediction.sed after calling SEDModel.predict():

pred = model.predict(params)
sed = pred.sed  # SEDQuantities NamedTuple
print(float(sed.l_bol))  # bolometric luminosity [Lsun]
print(float(sed.dn4000))  # 4000 Å break strength
print(float(sed.uv_slope_beta))  # UV slope beta
balmer_break: Array

Alias for field number 6

dn4000: Array

Alias for field number 5

fuv_flux: Array

Alias for field number 8

fuv_flux_intrinsic: Array

Alias for field number 10

irx: Array

Alias for field number 3

l_bol: Array

Alias for field number 0

l_dust_absorbed: Array

Alias for field number 2

l_tir: Array

Alias for field number 1

luminosity_weighted_age_gyr: Array

Alias for field number 13

luminosity_weighted_metallicity: Array

Alias for field number 14

m_uv: Array

Alias for field number 7

nuv_flux: Array

Alias for field number 9

nuv_flux_intrinsic: Array

Alias for field number 11

rest_uv_color: Array

Alias for field number 12

uv_slope_beta: Array

Alias for field number 4

Derived quantities

class tengri.DerivedQuantities(sfh: SFHQuantities, sed: SEDQuantities)[source]

Bases: NamedTuple

All derived physical quantities (convenience container).

Returned by model._predict_derived().

Variables:
  • sfh (SFHQuantities) – Star formation history derived quantities.

  • sed (SEDQuantities) – Spectral energy distribution derived quantities.

Returns:

  • This is a NamedTuple (JAX pytree) returned by

  • SEDModel.predict_derived().

Notes

JAX-compatible array container combining SFHQuantities and SEDQuantities. Compatible with jax.jit and jax.vmap. Returned by SEDModel.predict_derived().

Examples

from tengri import DerivedQuantities

derived = model._predict_derived(params)
print(float(derived.sfh.stellar_mass))  # [Msun]
print(float(derived.sed.dn4000))  # 4000 Å break
print(float(derived.sed.uv_slope_beta))  # UV slope β
sed: SEDQuantities

Alias for field number 1

sfh: SFHQuantities

Alias for field number 0

Emission lines

class tengri.EmissionLines(lya: Array, civ_1549: Array, oii: Array, hbeta: Array, oiii_4959: Array, oiii_5007: Array, nii_6548: Array, halpha: Array, nii_6584: Array, sii_6717: Array, sii_6731: Array, all_waves: Array, all_lums: Array)[source]

Bases: NamedTuple

Emission line luminosities, headline survey lines plus the full backend catalog.

Units: every field is in erg/s. This is the NamedTuple returned by SEDModel.predict_emission_lines() and built by tengri.forward.state_to_emission_lines(). It is not the Prediction.lines accessor, whose headline fields are in L_sun (LineProperties, #1206 section A).

NaN for the headline fields and empty arrays for all_* when no nebular model is active. For doublets ([O II], C IV) the headline fields sum both components.

The full ~138-line Cue catalog (and the generally smaller equivalent grids for CloudyGrid, CB19 and MAPPINGS) is exposed via all_waves / all_lums so users can read species the headline NamedTuple does not name explicitly (HeII 1640, HeI 10830, NIII] 1750, [O III] 4363, etc.). See get() for the nearest-wavelength accessor.

Variables:
  • lya (jnp.ndarray) – Lyman-alpha at 1216 Å [erg/s].

  • civ_1549 (jnp.ndarray) – C IV doublet 1548+1551 Å, summed [erg/s].

  • oii (jnp.ndarray) – [OII] doublet 3726+3729 Å, summed [erg/s].

  • hbeta (jnp.ndarray) – H-beta at 4861 Å [erg/s].

  • oiii_4959 (jnp.ndarray) – [OIII] at 4959 Å [erg/s].

  • oiii_5007 (jnp.ndarray) – [OIII] at 5007 Å [erg/s].

  • nii_6548 (jnp.ndarray) – [NII] at 6548 Å [erg/s].

  • halpha (jnp.ndarray) – H-alpha at 6563 Å [erg/s].

  • nii_6584 (jnp.ndarray) – [NII] at 6584 Å [erg/s].

  • sii_6717 (jnp.ndarray) – [SII] at 6717 Å [erg/s].

  • sii_6731 (jnp.ndarray) – [SII] at 6731 Å [erg/s].

  • all_waves (jnp.ndarray, shape (n_lines,)) – Vacuum rest-frame wavelengths of every species published by the active nebular backend [Angstrom]. Empty when the backend does not expose a discrete catalog (BakedIn, shock).

  • all_lums (jnp.ndarray, shape (n_lines,)) – Luminosities at all_waves, in the same dust regime as the headline fields (i.e. attenuated by the active dust model when present) [erg/s].

Returns:

  • This is a NamedTuple (JAX pytree) returned by

  • SEDModel.predict_emission_lines().

Notes

JAX-compatible array container. All fields are JAX arrays compatible with jax.jit and jax.vmap. All fields return NaN if no nebular model is active in the SEDModel.

Examples

lines = model.predict_emission_lines(params)  # EmissionLines, erg/s
print(float(lines.halpha))  # H-alpha luminosity [erg/s]
print(float(lines.oiii_5007))  # [OIII] 5007 Å luminosity [erg/s]
# BPT diagram
bpt_x = float(lines.nii_6584 / lines.halpha)
bpt_y = float(lines.oiii_5007 / lines.hbeta)
# Access lines outside the headline catalog via nearest-wavelength
heii_1640 = lines.get(1640.42)  # closest match in ``all_waves``

model.predict(params).lines is a different object (LineProperties): its headline fields are in L_sun, while its all_lums and get are in erg/s.

all_lums: Array

Alias for field number 12

all_waves: Array

Alias for field number 11

civ_1549: Array

Alias for field number 1

get(wavelength: float, tol_aa: float = 2.0) → Array[source]

Return the luminosity at the species nearest wavelength Å.

Parameters:
  • wavelength (float) – Rest-frame vacuum wavelength to look up [Angstrom].

  • tol_aa (float, optional) – Acceptable distance to the nearest cataloged line [Angstrom]. Returns nan if the nearest line is further than this. Default 2.0.

Returns:

Luminosity at the matched line [erg/s], or nan if no line is within tol_aa. Returns nan if the active backend did not publish a discrete catalog.

Return type:

jnp.ndarray

halpha: Array

Alias for field number 7

hbeta: Array

Alias for field number 3

lya: Array

Alias for field number 0

nii_6548: Array

Alias for field number 6

nii_6584: Array

Alias for field number 8

oii: Array

Alias for field number 2

oiii_4959: Array

Alias for field number 4

oiii_5007: Array

Alias for field number 5

sii_6717: Array

Alias for field number 9

sii_6731: Array

Alias for field number 10

Mock data

class tengri.MockData(flux_true: jnp.ndarray, flux_obs: jnp.ndarray, noise: jnp.ndarray, params: dict)[source]

Bases: NamedTuple

Container for mock galaxy observations.

Parameters:
  • flux_true (ndarray, shape (n_filters,)) – Noiseless model photometry. [erg/s/cm²/Hz]

  • flux_obs (ndarray, shape (n_filters,)) – Noisy photometry with Gaussian scatter added. [erg/s/cm²/Hz]

  • noise (ndarray, shape (n_filters,)) – 1-sigma photometric uncertainties used to draw the noise. [erg/s/cm²/Hz]

  • params (dict) – Input physical parameters used to generate the mock.

Returns:

Named tuple containing noiseless and noisy photometry.

Return type:

MockData

Variables:
  • flux_true (ndarray, shape (n_filters,)) – Noiseless model photometry. [erg/s/cm²/Hz]

  • flux_obs (ndarray, shape (n_filters,)) – Noisy photometry with Gaussian scatter added. [erg/s/cm²/Hz]

  • noise (ndarray, shape (n_filters,)) – 1-sigma photometric uncertainties used to draw the noise. [erg/s/cm²/Hz]

  • params (dict) – Input physical parameters used to generate the mock.

Notes

JIT-compatible: yes, NamedTuple is a JAX pytree.

Immutable: All fields are read-only by design. To create a modified version, use the _replace() method inherited from NamedTuple.

Examples

from tengri import SEDModel, Parameters, Uniform
model = SEDModel(spec, ssp_data, filter_names=["hst_acs_f606w", "hst_acs_f814w"])
params = {"sfh_dpl_alpha": 2.0, "sfh_dpl_beta": 1.5, ...}
mock = model.make_mock(params, snr=20.0)
mock.flux_obs.shape    # (n_filters,)
mock.plot()            # matplotlib Figure
flux_obs: Array

Alias for field number 1

flux_true: Array

Alias for field number 0

get(key: str, default=None)[source]

Return field key if present, else default (mirrors dict.get()).

items()[source]

Return (name, value) pairs, in field order.

keys()[source]

Return the field names (flux_true, flux_obs, noise, params).

noise: Array

Alias for field number 2

params: dict

Alias for field number 3

plot(filter_names=None, ax=None)[source]

Plot mock photometry with errorbars.

Parameters:
  • filter_names (list of str, optional) – Filter labels for the x-axis. Falls back to integer indices if None.

  • ax (matplotlib Axes, optional) – Axes to plot on. Creates new figure if None.

Returns:

fig – Matplotlib figure with photometry plotted as error bars (observed with noise) and markers (true noiseless).

Return type:

matplotlib Figure

Notes

JIT-compatible: no, uses matplotlib for visualization.

values()[source]

Return the field values, in field order.

generate_mock

tengri.generate_mock(model, params, key=None, snr=20.0, noise=None)[source]

Generate mock galaxy photometry with optional Gaussian noise.

Computes noiseless predicted photometry, then optionally realizes noise at a specified signal-to-noise ratio. Useful for testing data pipelines, validating inference, and parameter recovery studies.

Parameters:
  • model (object) – Any object with a predict_photometry(params) method that returns an array of flux densities.

  • params (dict[str, ndarray]) – Model parameter values (typically sampled or optimized).

  • key (jax.Array (PRNGKey), optional) – Random key for noise realization. If None, only noiseless photometry is returned (no flux_obs key in output).

  • snr (float, optional) – Signal-to-noise ratio (flux_true / noise_std). Default: 20.0. Ignored when noise is given.

  • noise (array_like, optional) – Observed 1-sigma uncertainties [erg/s/cm²/Hz] to draw each band from (CIGALE’s mock_flag (Boquien et al. 2019, A&A 622, A103): flux_obs ~ N(flux_true, |observed error|), pcigale managers/observations.py generate_mock). Must have the shape of the predicted photometry: (n_bands,) for a single parameter set, (n_batch, n_bands) for batched parameters; scalars are refused. The absolute value is taken. CIGALE draws its mock from the errors after its model-error term has been added in quadrature (additionalerror, 10 % of the flux by default), so to reproduce a CIGALE mock pass sqrt(err**2 + (0.1 * flux)**2); the raw catalog errors give less scatter. Default None: sigma = flux_true / snr.

Returns:

A dict subclass (so mock["flux_obs"] works) that also exposes its keys as attributes (so mock.flux_obs works, matching the MockData object returned by SEDModel.mock()). Keys:

  • flux_true : noiseless predicted photometry [erg/s/cm²/Hz]

  • noise : noise standard deviation per band [erg/s/cm²/Hz] (the noise argument when given, else flux_true / snr)

  • params : the input parameter values

  • flux_obs : observed (noisy) photometry (only if key is not None)

Return type:

MockDict

Raises:

ValueError – If noise does not have the shape of the predicted photometry.

Notes

Noise model: Assumes Gaussian noise with σ = flux_true / SNR (appropriate for photon-limited observations), or with the supplied per-band noise (a catalog’s observed errors).

Examples

>>> import jax.random
>>> from tengri import SEDModel
>>> model = SEDModel(...)
>>> params = {'redshift': 0.1, ...}
>>> key = jax.random.PRNGKey(42)
>>> mock = generate_mock(model, params, key=key, snr=10.0)
>>> print(f"True flux shape: {mock['flux_true'].shape}")
>>> print(f"Obs. flux shape: {mock['flux_obs'].shape}")

Observation

class tengri.Observation(photometry: Photometry | None = None, spectroscopy: Spectroscopy | None = None, noise: NoiseModel | None = None, line_fluxes: LineFluxData | None = None, spectral_indices: SpectralIndexData | None = None, line_ratios: LineRatioData | None = None, lines: object | None = None)[source]

Bases: object

Unified observation configuration.

Composes optional photometric, spectroscopic, and noise model configurations. At least one of photometry or spectroscopy must be provided.

Parameters:
  • photometry (Photometry or None) – Photometric filter configuration.

  • spectroscopy (Spectroscopy or None) – Spectroscopic instrument configuration.

  • noise (NoiseModel or None) – Noise model configuration (calibration floor, Student-t dof).

  • line_fluxes (LineFluxData or None) – Observed emission line fluxes for direct fitting. When provided, the likelihood includes an additive chi-squared term comparing model line luminosities against these fluxes.

Returns:

Validated observation container with at least one data modality.

Return type:

Observation

Variables:
  • photometry (Photometry or None) – Photometric filter configuration.

  • spectroscopy (Spectroscopy or None) – Spectroscopic instrument configuration.

  • noise (NoiseModel or None) – Noise model configuration.

  • line_fluxes (LineFluxData or None) – Observed emission line fluxes.

  • spectral_indices (SpectralIndexData or None) – Observed spectral indices for fitting.

Notes

A frozen, immutable dataclass that serves as a declarative container for all observation metadata. Never enters JAX-traced code; used solely for configuration dispatch to precomputation and inference steps. Inspired by Synthesizer’s Instrument pattern, adapted for tengri’s differentiable context.

Examples

Photometry-only:

obs = Observation(
    photometry=Photometry.from_names(["sdss_r", "sdss_i"]),
)

Joint photometry + spectroscopy:

obs = Observation(
    photometry=Photometry.from_names(["jwst_f200w", "jwst_f356w"]),
    spectroscopy=Spectroscopy.nirspec_prism(wave_obs),
    noise=NoiseModel(calibration_floor=Uniform(0.01, 0.15)),
)
cache_key() → tuple[source]

Return a hashable cache key for this observation configuration.

Returns:

Cache key derived from nested observation configurations.

Return type:

tuple

Notes

All fields are included by content; nested objects delegate to their own cache_key() methods, and None stays None.

property can_do_photometry: bool

Whether photometric filters are configured.

Returns:

True if photometry is configured.

Return type:

bool

Notes

Query method for capability checking. Safe to call even if photometry was not provided to this Observation.

property can_do_spectroscopy: bool

Whether a spectroscopic wavelength grid is configured.

Returns:

True if spectroscopy is configured.

Return type:

bool

Notes

Query method for capability checking. Safe to call even if spectroscopy was not provided to this Observation.

property data_type: str

Inferred data type string (photometry/spectroscopy/joint).

Returns:

One of "photometry", "spectroscopy", or "joint".

Return type:

str

Notes

Returns a string representation of the configured data types, useful for logging and dispatch logic.

get_all_params() → dict[str, Distribution][source]

Collect all observation-driven parameters.

Merges calibration polynomial params from spectroscopy config and noise model params from noise config.

Returns:

Parameter name → Distribution mapping. Empty if no observation params are needed (e.g. photometry-only with no noise config).

Return type:

dict

Notes

This method is called by the inference engine to set up the prior structure. Observation parameters include calibration coefficients and noise model hyperparameters, but not SED or SFH params.

property has_line_fluxes: bool

Whether observed emission line fluxes are configured.

Returns:

True if line flux data is configured.

Return type:

bool

Notes

Query method for capability checking. Safe to call even if line fluxes were not provided to this Observation.

property has_line_ratios: bool

Whether observed emission line ratios are configured.

Returns:

True if line ratio data is configured.

Return type:

bool

property has_spectral_indices: bool

Whether observed spectral indices are configured.

Returns:

True if spectral index data is configured.

Return type:

bool

Notes

Query method for capability checking. Safe to call even if spectral indices were not provided to this Observation.

property is_joint: bool

Whether both photometry and spectroscopy are configured.

Returns:

True if both photometry and spectroscopy are present.

Return type:

bool

Notes

Convenience predicate for detecting joint photometry+spectroscopy fitting (vs. photometry-only or spectroscopy-only).

line_fluxes: LineFluxData | None = None
line_ratios: LineRatioData | None = None
lines: object | None = None
property n_data: int

Total number of data points.

Returns:

Sum of all photometric, spectroscopic, line flux, line ratio, and spectral index data points.

Return type:

int

Notes

Aggregates counts across all observation modalities. Useful for data dimensionality checks and prior/posterior shape validation.

property n_data_indices: int

Number of spectral index data points.

Returns:

Number of spectral indices, or 0 if no index data configured.

Return type:

int

Notes

Returns 0 safely if spectral index data is not configured; may be used in conditional logic without prior capability checks.

property n_data_lines: int

Number of emission line flux data points.

Returns:

Number of emission lines, or 0 if no line flux data configured.

Return type:

int

Notes

Returns 0 safely if line flux data is not configured; may be used in conditional logic without prior capability checks.

property n_data_phot: int

Number of photometric data points (filters).

Returns:

Number of filters, or 0 if no photometry configured.

Return type:

int

Notes

Returns 0 safely if photometry is not configured; may be used in conditional logic without prior capability checks.

property n_data_ratios: int

Number of emission line ratio data points.

Returns 0 safely if no line ratio data is configured.

property n_data_spec: int

Number of spectroscopic data points (pixels).

Returns:

Number of spectral pixels, or 0 if no spectroscopy configured.

Return type:

int

Notes

Returns 0 safely if spectroscopy is not configured; may be used in conditional logic without prior capability checks.

noise: NoiseModel | None = None
observe_photometry(sed_result, z: float, dl_cm: float) → Array[source]

Project an observed-frame SED through photometric filters.

Parameters:
  • sed_result (SEDResult) – Observed-frame SED with wavelength and sed.

  • z (float) – Redshift.

  • dl_cm (float) – Luminosity distance [cm].

Returns:

Photometric fluxes in each filter [erg/s/Hz].

Return type:

jnp.ndarray, shape (n_filters,)

Notes

Requires photometry to be configured. Computes rest-frame wavelengths from the observed-frame input and integrates the SED against each filter transmission curve.

observe_spectrum(sed_result, z: float, dl_cm: float, sigma_v_kms: float = 0.0, cal_coeffs: Array | None = None, sigma_lib_curve: tuple[Array, Array] | None = None) → Array[source]

Project an observed-frame SED onto spectroscopic pixel grid.

Parameters:
  • sed_result (SEDResult) – Observed-frame SED with wavelength and sed.

  • z (float) – Redshift.

  • dl_cm (float) – Luminosity distance [cm].

  • sigma_v_kms (float, optional) – Intrinsic velocity dispersion [km/s]. Default 0.0.

  • cal_coeffs (ndarray, shape (order,), or None, optional) – Calibration polynomial coefficients to apply after LSF. If None (default), no calibration is applied.

  • sigma_lib_curve (tuple[ndarray, ndarray] or None, optional) – (ssp_wave_rest, ssp_resolution_kms) [Angstrom], [km/s] from the loaded SSP grid’s ssp_resolution_kms (#2518). When given, overrides self.spectroscopy.sigma_lib_kms with this per-wavelength curve, interpolated onto the observed pixel grid mapped into the rest frame. None (default) keeps the flat scalar.

Returns:

Spectroscopic flux at each pixel [erg/s/cm^2/Hz].

Return type:

jnp.ndarray, shape (n_pixels,)

Notes

Takes one pre-combined array and applies a single kernel to it, so with sigma_v_kms > 0 or nebular lines it does not reproduce the model path (predict()) to rounding.

Requires spectroscopy to be configured. Applies LSF convolution if a resolution profile is specified. Applies flux-calibration polynomial if cal_coeffs is provided. Returns data ready for likelihood evaluation against observed spectra.

Takes sed_result as one pre-combined array with no per-component breakdown, so it applies a single kernel to whatever total SED it is given; the stellar/instrument-only split of project_spectrum_kernel_split() needs a ForwardState (state.derived["sed_nebular"]/["sed_shock"]) and does not apply here.

pack_data(phot: Array | None = None, spec: Array | None = None) → Array[source]

Concatenate photometry and spectroscopy data in canonical order.

Validates array shapes against the observation configuration. Canonical order: [photometry, spectroscopy].

Parameters:
  • phot (array or None) – Photometric data, shape (n_filters,).

  • spec (array or None) – Spectroscopic data, shape (n_pixels,).

Returns:

Packed data array, shape (n_data,).

Return type:

jnp.ndarray

Raises:

ValueError – If array shapes don’t match the observation configuration.

Notes

Both arrays are optional but at least one must be provided and configured in the Observation. Useful for likelihood evaluation and parameter inference pipelines.

photometry: Photometry | None = None
predict(state, params, *, dl_cm=None, wave_obs=None, sigma_v_kms: float = 0.0, lsf_resolution=None, lsf_sigma_lib_kms: float | None = None, lsf_sigma_lib_curve: tuple[Array, Array] | None = None, lsf_n_bins: int | None = None, lsf_scale: float = 1.0, resample_z_ref: float | None = None, conserving: bool | None = None, observables_type=None, window_z: float | None = None, lattice_window: tuple[float, int] | None = None) → dict[str, Array][source]

Project an orchestrator ForwardState into observable channels.

Unified projection seam matching the ObservationModel Protocol in tengri.protocols.observation. Part of the forward-projection unification (docs/dev/archive/photometry_path_unification.md).

Parameters:
  • state (ForwardState) – Orchestrator output. Reads state.sed_intrinsic (rest-frame L_nu in erg/s/Hz) and state.wave (rest-frame Angstrom).

  • params (Mapping[str, jnp.ndarray]) – Parameter dict. Reads redshift for the cosmology calculation.

  • dl_cm (float or jnp.ndarray, optional) – Luminosity distance [cm]. If None, derived from params["redshift"] via tengri.utils.cosmology.luminosity_distance().

  • wave_obs (jnp.ndarray, optional) – Observed-frame wavelength grid for the spectrum. Defaults to self.spectroscopy.wave_obs.

  • sigma_v_kms (float, default 0.0) – Velocity dispersion [km/s] for LSF convolution.

  • lsf_resolution (float, ndarray, or None) – Override LSF resolution. None reuses self.spectroscopy.resolution.

  • lsf_sigma_lib_kms (float, optional) – Override SSP library sigma [km/s]. None reuses self.spectroscopy.sigma_lib_kms. Ignored when lsf_sigma_lib_curve is given.

  • lsf_sigma_lib_curve (tuple[ndarray, ndarray] or None, optional) – (ssp_wave_rest, ssp_resolution_kms) [Angstrom], [km/s] from the loaded SSP grid’s ssp_resolution_kms (#2518). When given, takes priority over lsf_sigma_lib_kms / self.spectroscopy.sigma_lib_kms: the per-wavelength curve is interpolated onto the observed pixel grid mapped into the rest frame and used in place of the flat scalar. None (default) keeps the flat-scalar behavior.

  • lsf_n_bins (int, optional) – Override piecewise-constant LSF bin count. None reuses self.spectroscopy.lsf_n_bins.

  • lsf_scale (float, default 1.0) – Free multiplicative scale on the instrument resolution \(\sigma_{\rm inst}(\lambda)\) (#2526), applied before the quadrature combination in apply_lsf() for both the stellar and instrument-only kernels of the #2519 split below. 1.0 (the parameter’s Fixed default, declared as lsf_scale in tengri.parameters._shared) reproduces the un-scaled kernel bit-for-bit. Not applied on the banded resolution_matrix path (see the Notes on that branch below).

  • resample_z_ref (float, optional) – Redshift at which Spectroscopy.resample="auto" compares the pixel width with the model grid (#2530): the fixed redshift, or the lowest redshift of the prior when redshift is free. None uses z when it is a concrete value and 0 when it is traced.

  • conserving (bool, optional) – The pixel-integral decision when it was already made outside a vmap (a traced model grid cannot be inspected). None resolves it here from state.wave.

  • observables_type (type or None) – If provided, a typing.NamedTuple class produced by build_observables_class(). When None, returns a dict (backward-compat). When provided, populates and returns an instance of this class.

  • window_z (float or None, optional) – Concrete redshift for the rest-grid sigma_v window (see project_spectrum_kernel_split(), #2832). It must equal the redshift of state; None keeps the full-grid pass.

Returns:

When observables_type is None: Observable channels as dict, keyed by which sub-blocks are configured:

When observables_type is provided: an instance of the passed NamedTuple class with fields populated in order: phot_fnu, phot_rest_fnu, spec_fnu, lines_flux, indices.

Return type:

dict[str, jnp.ndarray] or Observables

Notes

JIT-compatible: yes, same kernels as observe_photometry() and observe_spectrum().

Joint observations (is_joint) return both keys from a single forward pass. loss_functions._build_prediction still makes two separate calls for joint fits; collapsing that branch onto this single call is an open consolidation.

When observables_type is provided and the observation has line_fluxes or spectral_indices configured, raises NotImplementedError, those channels are not routed through this entry point yet.

predict_spectrum_via_precomp(state, params, *, observables_type=None, sigma_lib_kms=0.0, lsf_scale=1.0)[source]

Project spectrum observables via the spectrum LUT.

Opt-in fast path for approx=SpectrumPrecomp(). Sums all *_spec_lnu_precomp keys present in state.derived and applies the cosmology factor (1+z)/(4π·dl²) to convert to observed F_ν. It runs the exact path’s three stages in the same order: the stellar velocity dispersion is already in the stellar family (broadened on the model grid by the stellar component), the IGM factor multiplies next, and the instrument stage runs on the pixel grid via instrument_stage_on_pixels(). With resolution=None there is no instrument stage.

Parameters:
  • state (ForwardState) – Orchestrator state with at least spec_eff_waves and one or more *_spec_lnu_precomp entries.

  • params (Mapping[str, jnp.ndarray]) – Param dict; reads redshift.

  • observables_type (type, optional) – Per-model Observables NamedTuple class (from SEDModel.Observables()). When provided, returns an instance; when None, returns a dict.

  • sigma_lib_kms (float or ndarray, shape (n_pix,), default 0.0) – SSP library resolution [km/s] subtracted from the stellar bucket.

  • lsf_scale (float or traced scalar, default 1.0) – Multiplicative scale on the instrument width (#2526).

Returns:

spec_fnu populated from the spectrum LUT path.

Return type:

Observables or dict

Raises:

ValueError – If no *_spec_lnu_precomp keys are present.

Notes

JIT-compatible: yes, pure JAX arithmetic on the LUT entries.

predict_via_precomp(state, params, *, observables_type=None)[source]

Project observables via the photometric LUT instead of integrating sed_intrinsic.

Opt-in fast path for approx=WavePrecomp(). Sums all *_phot_lnu_lut keys present in state.derived (the rest-frame Lν contributions from each component that publishes one) and applies the cosmology factor (1+z)/(4π·dl²) to convert to observed F_ν.

Components that publish a LUT entry:

  • stellar_phot_lnu_precomp: StellarSEDComponent. For BakedIn nebular backends this already contains the nebular contribution, since the SSP grid carries baked-in nebular emission.

  • nebular_phot_lnu_precomp: NebularSEDComponent (when the backend supports filter-level precomputation; non-BakedIn backends only).

Any additional *_phot_lnu_precomp entries (AGN, …) sum in automatically.

Photometry only, spectroscopy has its own LUT path (predict_spectrum_via_precomp()).

Parameters:
  • state (ForwardState) – Orchestrator state with at least stellar_phot_lnu_precomp.

  • params (Mapping[str, jnp.ndarray]) – Param dict; reads redshift.

  • observables_type (type, optional) – Per-model Observables NamedTuple class (from SEDModel.Observables()). When provided, returns an instance; when None, returns a dict.

Returns:

phot_fnu and phot_rest_fnu populated.

Return type:

Observables or dict

Raises:
  • ValueError – If no *_phot_lnu_lut keys are present (i.e. the model was not built with approx=WavePrecomp()).

  • NotImplementedError – If the observation has spectroscopy, line_fluxes, or spectral_indices.

Notes

JIT-compatible: yes, pure JAX arithmetic on the LUT entries.

This is a second implementation of :meth:`predict`, not a spelling of it. The two are kept in sync by hand, deliberately: the speedup exists because this path reaches its answer without ever referencing the dense SED, which lets XLA dead-code-eliminate the full-resolution chain (#1109). Collapsing the two would delete the optimization. The standing goal is therefore not to merge them but to shrink and bound the divergence channel by channel, and to keep the remaining approximations named with their measured size, which is what follows.

Accuracy ledger, where this path differs from predict():

  • Stellar continuum: K-point sub-band quadrature (#1122). The screen is evaluated at each node rather than sampled once, and converges as \(1/K^2\). K=5 (default): ≲0.6 % worst case in GALEX FUV; 3.2e-05 to 7.8e-04 on an FSPS/SDSS griz reference model over \(\tau_{\rm diff} \le 2\), \(z \le 1\). This is the floor for the whole path, no other channel can do better than the bucket that dominates the broadband.

  • Lyman continuum, under a photoionized nebular backend (#2439, #2427): exact for the whole-band bucket, and now matched to each consumer’s own dense-path rule for the sub-band buckets (fix round, 2026-09; R1-R5 below). The whole-band stellar_phot_lnu_precomp is corrected by NebularSEDComponent.apply with an exact algebraic split of the SSP × filter integral at the physical 912 Å edge (stellar_phot_lnu_precomp_lyc and its per-age twin stellar_phot_lnu_per_age_precomp_lyc, R3d, built alongside the whole-band tensor in preintegrate_grid / the ztable twin, clamped at zero against catastrophic cancellation in a fully-LyC band), mirroring the dense path’s sed_intrinsic mask (components/nebular/component.py). Before the original fix, any band whose observed passband sampled rest λ < 912 Å carried the full, unabsorbed stellar Lyman continuum regardless of neb_fesc: measured +915 % (z=2 GALEX NUV) and +69 % (z=3 SDSS u) on the issue’s own model, K-invariant (the bug was never a quadrature question).

    The K-node sub-band tensors (stellar_phot_lnu_per_age_subband_precomp and its IGM-folded twin, read below as sub_per_age / sub_per_age_igm) are themselves left RAW: R1 forces an extra quadrature edge exactly at the physical 912 Å (observed-frame) boundary whenever a live nebular mask is present (lyc_gate, a build-time-only performance/cache-size gate — the correction below always applies when nebular is present, gate or not; live means a PHOTOIONIZED backend, cue/ cloudy_grid/cb19/mappings — backend="baked_in" (neb={'type': 'none'}) puts a NebularSEDComponent in the chain but returns from apply before ever reaching the neb_fesc masking block, so it does not count), so no chunk can straddle the break. R2: each consumer multiplies the raw chunks by the SAME shared factor, stellar_subband_lyc_factor_precomp — published flat by NebularSEDComponent (where(node<912, fesc, 1), the only rule available where there is no birth-cloud concept, e.g. the dust-free mean-IGM branch), then OVERWRITTEN by DustSEDComponent with its own y(age)-graded 1-y(a)(1-fesc) rule (or the flat rule under lyc_reprocessed_by='all') when a dusty model runs it — same key, so whichever component is later in the chain wins, and there is exactly one factor per model, never a double-count. R3 conservation invariants (tested explicitly, not just implied): (a) the raw partition sums to the raw whole band; (b) fesc=1 is bit-for-bit identical to no nebular component at all; (c) the corrected sub-band sum matches the corrected whole band to ~1e-9 relative; (d) the per-age LyC split sums over age to its whole-band twin. R4: every tolerance here and in the regression test is a measured floor times a stated factor, never sized to an observed residual. Measured (2026-09, synthetic fixture, K=5): dusty worst-band error 0.16-0.18 % against a K=5 fesc=1 floor of ~0.29 % (the pre-existing K-node dust-quadrature floor, unrelated to this fix); both converge together as K rises (0.02 %/0.008 % at K=16/32).

    R5: a real-grid residual remains after this fix (measured, real fsps_prsc_miles_chabrier.h5 + Cue, this fix round’s own SFH: z=2 GALEX NUV ~10 %, z=3 SDSS u ~5 %, K-invariant) — this is the EXACT PATH’s own SSP-grid-node quantization of the 912 Å edge (the dense mask cuts at whichever SSP wavelength node sits just below 912 Å, not at 912 Å itself, while this LUT’s split is exact at the TRUE physical edge), filed as #2447 and NOT fixed this round. The magnitude is SFH- and filter-dependent; re-measure, do not quote. See tests/regression/bug/test_bug_2439_precomp_lyc_mask.py.

  • Nebular, under dust_attenuation={'type': 'two_component'}: exact since #1738. That component publishes the reddened continuum integrated through each band (nebular_phot_lnu_attenuated_precomp), so there is no band-averaging error left to quote: ≤3.5e-06 against the exact path on a fixture built to maximize it. Previously screened at \(\lambda_{\rm eff}\), which inflated the total gap by up to 26x over the stellar floor while carrying only 0.8-3.5 % of the band flux.

  • Nebular, under dust_attenuation={'type': 'single_component'}: DustAttenuationSEDComponent publishes the reddened continuum integrated through each band exactly as the two-component component does, and this path prefers it over the screen at \(\lambda_{\rm eff}\). Measured on an FSPS SSP through SDSS gri against the exact path: 2.7e-04, 6.1e-04 and 5.7e-04 over the three (tau_v, z) cases of tests/contract/test_precomp_channel_drift.py, at the stellar-only floor of ~6.3e-04.

  • Shock: the worst remaining channel by two orders of magnitude, and not a band-averaging error despite what this docstring said for a long time. This path multiplies shock by a_diff·a_bc; the exact path applies no stellar dust screen to it at all, because two_component never reads sed_shock and adds the non-nebular remainder unattenuated. Measured on an FSPS SSP through SDSS gri: 4.5 % at \(\tau_{\rm bc}\)=1/z=0.05, 7.4 % at \(\tau\)=2/z=0.05, 37.7 % at \(\tau\)=2/z=1, and in the exact path shock’s contribution over its intrinsic value is 1.66e-55 whatever \(\tau\) is, i.e. the bare cosmology factor. A quadrature cannot close a factor-of-40 disagreement about whether a screen applies. Which path is right is a physics question, so the gap is bounded (tests/contract/test_precomp_channel_drift.py) rather than silently resolved.

  • IGM: igm_phot_factor band-averages \(T\) alone, forming \(\langle S\rangle\langle T\rangle\) where the flux needs \(\langle S\,T\rangle\). Across GALEX FUV at \(z\approx0.8\) the transmission runs ~1 to ~0 inside the band and that covariance term reaches −9.5 %. Folded into the sub-band weights (#1135) wherever a mean-IGM model is precomputable; patchy reionization and DLAs read free parameters, so those configs keep the live path.

  • Additive emitters (dust IR, radio, X-ray, AGN), exact via the rank-1/rank-K band response where the emitter factorizes, else a dense band integral, else a single \(\lambda_{\rm eff}\) sample; see tengri.components._band_projection.project_additive_onto_photometry for which branch a given component takes.

Re-measure rather than quoting these: every figure above is a property of an SSP grid, a filter set and a K, none of which are fixed by this method.

See also

predict

The default projection path that integrates sed_intrinsic through filters. Stays the canonical reference; the exact path remains the default (approx=None).

spectral_indices: SpectralIndexData | None = None
spectroscopy: Spectroscopy | None = None
summary() → str[source]

Return a human-readable summary of the observation.

Returns:

Multi-line summary string with filter counts, instrument config, noise settings, and total data point count.

Return type:

str

Notes

Used for logging and diagnostics. Does not execute any inference; purely informational output.

unpack_prediction(predicted: Array) → dict[str, Array][source]

Split a concatenated prediction into photometry and spectroscopy.

Inverse of pack_data: reverses the concatenation to extract predictions for each observation modality.

Parameters:

predicted (array) – Packed prediction array, shape (n_data,).

Returns:

Keys are "photometry" and/or "spectroscopy", values are the corresponding sub-arrays.

Return type:

dict

Notes

Only keys corresponding to configured observation modalities will be present in the returned dictionary.

Instrument

A named bundle of (photometry, spectroscopy, noise) defaults, so a notebook can say Instrument.JWST_NIRCam() instead of assembling those pieces by hand. list_instruments() is the menu.

class tengri.Instrument(name: str, photometry: Photometry | None = None, spectroscopy: Spectroscopy | None = None, noise: NoiseModel | None = None, description: str = '')[source]

Bases: object

A named bundle of (photometry, spectroscopy, noise) defaults.

Variables:
  • name (str) – Short identifier (e.g. "JWST_NIRCam").

  • photometry (Photometry, optional) – Photometric filter set. None for spectroscopy-only instruments.

  • spectroscopy (Spectroscopy, optional) – Spectroscopic configuration. None for photometry-only instruments.

  • noise (NoiseModel, optional) – Default noise model for this instrument. Users can override at fit time.

  • description (str) – One-line human description.

Notes

Frozen dataclass, safe to share across processes / treat as immutable.

Premade instruments live on the class itself as @classmethod factories (Instrument.JWST_NIRCam(), Instrument.SDSS(), …). They lazily construct their underlying Photometry so import is cheap; the actual filter curves only load on first call.

classmethod GALEX() → Instrument[source]

GALEX FUV + NUV ultraviolet photometry.

classmethod HERSCHEL() → Instrument[source]

Herschel PACS+SPIRE far-infrared photometry (100–500 µm).

classmethod HST_ACS_WFC3() → Instrument[source]

HST ACS+WFC3 broad-band optical/NIR photometry.

classmethod JWST_NIRCam() → Instrument[source]

JWST NIRCam wide-band photometry (8 broad bands, 0.7–4.4 µm).

classmethod SDSS() → Instrument[source]

SDSS five-band optical photometry (u, g, r, i, z).

classmethod SPITZER_IRAC() → Instrument[source]

Spitzer IRAC four-channel photometry (3.6, 4.5, 5.8, 8.0 µm).

classmethod TWOMASS() → Instrument[source]

2MASS near-infrared photometry (J, H, Ks).

classmethod UKIDSS() → Instrument[source]

UKIDSS five-band near-infrared photometry (Y, Z, J, H, K).

classmethod WISE() → Instrument[source]

WISE four-band mid-infrared photometry (W1–W4).

description: str = ''
property filter_names: tuple[str, ...]

Filter short-names for the photometric portion (empty if spectro-only).

classmethod list() → _RegistryTable[source]

Return every premade instrument as a table.

Returns:

One row per premade instrument, with columns name, n_bands and description. Returned a plain list[dict] before #1574; every discovery verb returns a table (#1285).

Return type:

_RegistryTable

Notes

Rows are built once per process and copied out, because this menu is swept by describe() and search() on every lookup. Building each instrument once per column instead of once per row cost 160.6 ms for nine rows, 99% of a 161.7 ms sweep.

name: str
noise: NoiseModel | None = None
observation() → Observation[source]

Return an Observation populated with this instrument’s pieces.

photometry: Photometry | None = None
spectroscopy: Spectroscopy | None = None

Data

One galaxy’s measurements, validated against the Observation that describes them.

class tengri.Data(photometry: tuple | None = None, spectrum: tuple | None = None, lines: dict | None = None, censor: object | None = None)[source]

Bases: object

One galaxy’s measurements, validated against an Observation.

Parameters:
  • photometry (tuple of (flux, err) or None) – Each array_like, shape (n_filters,) [erg/s/cm^2/Hz].

  • spectrum (tuple of (flux, err) or None) – Each array_like, shape (n_pix,) [erg/s/cm^2/Hz].

  • lines (dict or None) – {line_name: (value, err)}, or {line_name: (value, err, 'upper'|'lower')} [erg/s/cm^2]; names must be a subset of the observation’s LineList. The optional third element marks the flux as a censored limit rather than a detection, using the same vocabulary as from_dict(). Line limits belong here, not in censor, that field is per-photometric-band.

  • censor (array_like or None) – Per-band censoring flags, shape (n_filters,): 0 = detected, 1 = upper limit, -1 = lower limit. Boolean arrays are rejected (they silently invert the semantics).

censor: object | None = None
lines: dict | None = None
photometry: tuple | None = None
spectrum: tuple | None = None
validate_against(observation) → ValidatedData[source]

Galaxy

class tengri.Galaxy(*, ssp, observation, parameters, model_config, model=None, preset_name=None)[source]

Bases: object

User-facing facade around SEDModel + Parameters + Observation + Fitter.

Bundles SSP data, observation, parameters, and model into a single object for simplified one-liner SED fitting. Not a dataclass: it has mutable state (result after fit) and methods. Construction is via classmethods, not __init__ directly.

Variables:
  • ssp (SSPData) – Stellar population synthesis data (grid of stellar templates).

  • observation (Observation) – Observation configuration (photometry, spectroscopy, noise).

  • parameters (Parameters) – Parameter specification with priors.

  • model_config (SEDModelConfig) – Model configuration (dust, nebular, AGN, etc.).

  • model (SEDModel or None) – Forward model (lazily constructed on first forward pass or before fit).

  • result (Posterior or None) – Posterior/result after running fit().

  • preset_name (str or None) – Name of the preset used (e.g. “starforming”), if any.

build_model() → SEDModel[source]

Construct the SEDModel lazily.

Returns:

The forward model (stored in self.model).

Return type:

SEDModel

Notes

The model is JIT-compiled on the first forward pass. This method is called automatically by fit() if needed.

cite(fmt: str = 'list')[source]

Return citations for the components this Galaxy is configured to use.

Thin wrapper around bibliography. Prefer the Bibliography attribute directly for new code.

Parameters:

fmt ({"list", "short", "bibtex", "report", "bibliography"}) –

  • “list” (default): list of Citation records.

  • ”short”: newline-joined one-line forms.

  • ”bibtex”: BibTeX blocks separated by blank lines.

  • ”report”: grouped human-readable report.

  • ”bibliography”: the Bibliography container itself.

explain() → str[source]

Return a plain-English explanation of what was fit.

Returns:

Human-readable paragraph describing the fit.

Return type:

str

fit(method: str | None = None, verbose: bool = True, *, approx='auto', backend: str | None = None, **kwargs) → Galaxy[source]

Run inference and store result.

Note

Unlike tengri.ForwardModel.fit(), which defaults to "vi", this facade defaults to "map": a point estimate with no uncertainties. That difference is deliberate: Galaxy is the beginner-facing shortcut and "vi" costs ~100 s cold and ~20 GB RSS at D=6-7, which is not a reasonable thing to do by surprise. It is called out here because it used to be silent: five fit surfaces disagreed about the default and nothing said so (#1289). If you want a posterior, pass method="vi".

Parameters:
  • method (str, optional) –

    Inference method. Default "map". tengri.list_inference_methods() is the live list; “map”, “vi”, “vi_linear”, “mcmc_nuts”, “mcmc_raytrace”, “mcmc_hmc”, “mcmc_dynamic_hmc”, “mcmc_adjusted_mclmc”, “mcmc_ess”, “nss” among them.

    This docstring used to list "vi_native", which has never been a registered name and raises KeyError, alongside "mcmc_ghmc" and "mcmc_mclmc", now tier="broken" (#1287).

  • backend (str, optional) – Deprecated alias for method. Every other fit surface in the package spells this argument method; backend here was the odd one out. Passing it emits a DeprecationWarning.

  • verbose (bool) – Print progress. Default: True.

  • approx ({"auto", None} or precompute config, default "auto") – Fit-time approximation policy. “auto” routes the fit through the precompute LUT selected by data type; None forces the exact wave-grid path; an explicit config overrides. Model prediction stays exact regardless. See ForwardModel.fit().

  • **kwargs – Additional arguments passed to Fitter.run() (e.g., n_steps, n_iterations, n_samples, n_warmup, init_from, prewarm, etc.).

Returns:

Returns self for chaining.

Return type:

Galaxy

Raises:

AttributeError – If flux data not available (from_arrays required).

property flux_obs: ndarray

Observed fluxes in canonical units [erg/s/cm²/Hz].

classmethod from_arrays(*, filters: list[str], flux: list[float] | ndarray, flux_err: list[float] | ndarray, redshift: float | None = None, ssp_path: str | None = None, ssp: Any | None = None, preset: str = 'starforming', flux_unit: str = 'erg/s/cm2/Hz', model_config: SEDModelConfig | None = None) → Galaxy[source]

Build a Galaxy from plain arrays: the common entry point.

Parameters:
  • filters (list of str) – Filter names (e.g., [“sdss_u”, “sdss_g”, “sdss_r”, “sdss_i”, “sdss_z”]).

  • flux (array_like, shape (n_filters,)) – Observed fluxes [erg/s/cm²/Hz] by default.

  • flux_err (array_like, shape (n_filters,)) – Flux uncertainties (same units as flux).

  • redshift (float or None) – Redshift. If None, must be specified in preset.

  • ssp_path (str or None) – Path to SSP HDF5 file. If None, ssp must be provided.

  • ssp (SSPData or None) – Pre-loaded SSP data. If None, ssp_path must be provided.

  • preset (str) – Preset name: “starforming”, “quiescent”, “high_z”. Default: “starforming”.

  • flux_unit (str) – Flux unit. One of “erg/s/cm2/Hz”, “uJy”, “mJy”, “Jy”, “nJy”, “maggies”. Default: “erg/s/cm2/Hz”.

  • model_config (SEDModelConfig or None) – Model configuration. If None, uses preset defaults.

Return type:

Galaxy

Raises:

ValueError – If neither ssp_path nor ssp provided, or if flux_unit unknown.

classmethod from_observation(observation: Observation, *, ssp: Any | None = None, ssp_path: str | None = None, preset: str = 'starforming', redshift: float | None = None, model_config: SEDModelConfig | None = None) → Galaxy[source]

Build a Galaxy from an existing Observation object.

Parameters:
  • observation (Observation) – Pre-built Observation (photometry, spectroscopy, noise).

  • ssp (SSPData or None) – Pre-loaded SSP data.

  • ssp_path (str or None) – Path to SSP HDF5 file.

  • preset (str) – Preset name.

  • redshift (float or None) – Redshift (overrides any fixed redshift in preset).

  • model_config (SEDModelConfig or None) – Model configuration.

Return type:

Galaxy

Raises:

ValueError – If neither ssp_path nor ssp provided.

classmethod load_result(path: str)[source]

Load a FitResult previously saved by Galaxy.save.

Returns the FitResult directly (not a reconstructed Galaxy; the underlying SEDModel and Observation are not part of the HDF5 schema).

Parameters:

path (str) – Path to HDF5 file.

Returns:

The loaded result wrapper with provenance and citations.

Return type:

FitResult

Raises:
property noise: ndarray

Noise (flux uncertainties) in canonical units [erg/s/cm²/Hz].

plot(figsize: tuple[int, int] = (14, 5)) → Any[source]

Plot SED fit and SFH recovery.

Parameters:

figsize (tuple of int) – Figure size (width, height) in inches.

Returns:

The figure object.

Return type:

matplotlib.figure.Figure

Raises:

RuntimeError – If fit() has not been called yet.

predict(params, backend: str = 'legacy')[source]

Compute a forward-model prediction for params.

Unified entry point. The backend argument selects between the legacy tier-dispatch path (returns a Prediction lazy view) and the orchestrator path (returns a ForwardState).

Parameters:
  • params (Mapping) – Free parameter values keyed by canonical name.

  • backend ({"legacy", "component"}, optional) –

    "legacy" (default) returns the lazy Prediction wrapper from SEDModel.predict(), exposing the .sfh / .sed / .lines / .radio / .xray / .ionizing property groups. "component" returns a tengri.protocols.ForwardState from the SEDComponent orchestrator with all cross-component quantities published in state.derived.

    The default remains "legacy" until the v1.0 cutover. The two backends agree on the rest-frame SED at rtol ≤ 5e-2 for the configurations the stellar migration covers (stellar + dust + IGM + radio + X-ray); see docs/dev/archive/phase_ii_2_stellar_migration.md.

Returns:

Prediction for backend="legacy", tengri.protocols.ForwardState for backend="component".

Return type:

Prediction or ForwardState

Raises:

ValueError – If backend is not "legacy" or "component".

Examples

Legacy lazy view:

>>> g = Galaxy.from_arrays(filters=..., flux=..., flux_err=...)
>>> pred = g.predict(params)  # backend="legacy" (default)
>>> pred.sfh.stellar_mass

Orchestrator path:

>>> state = g.predict(params, backend="component")
>>> state.derived["log_mstar"]
predict_via_components(params)[source]

Forward pass via the SEDComponent orchestrator.

Convenience wrapper around tengri.SEDModel.predict_state() that lazy-builds the underlying SEDModel and threads the params dict through the component chain. Returns a tengri.protocols.ForwardState.

Use this when you want the orchestrator’s published cross-component derived quantities (L_ir, L_agn_bol, log_mstar, lnu_age, …) directly without going through fit(). For inference, keep using fit().

Parameters:

params (Mapping) – Free parameter values keyed by canonical name.

Returns:

See SEDModel.predict_state().

Return type:

ForwardState

See also

Galaxy.predict()

Unified entry point with a backend switch between the legacy Prediction lazy view and the orchestrator’s ForwardState (this method).

Examples

>>> g = Galaxy.from_arrays(filters=..., flux=..., flux_err=...)
>>> state = g.predict_via_components(params)
>>> state.derived["log_mstar"]
save(path: str) → None[source]

Save this Galaxy’s fit to an HDF5 file.

Requires .fit() to have been called. Wraps FitResult.save() with a Provenance snapshot plus a minimal record of the Galaxy configuration (preset name, backend used, flux/err arrays if present).

Parameters:

path (str) – Target HDF5 path.

Raises:
  • RuntimeError – If .fit() has not been called.

  • ImportError – If h5py is not installed.

  • ResultSerializationError – If any sample entry could not be written. The file is still created and holds everything writable; see tengri.results.FitResult.save().

summary() → Any[source]

Return a summary DataFrame of fitted parameters.

Returns:

One row with parameter medians and 68% credible intervals (for sampling-based backends) or point estimates (for MAP). Columns: {param}_median, {param}_lo68, {param}_hi68 (sampling), or {param}_value (MAP).

Return type:

pandas.DataFrame

Raises:

RuntimeError – If fit() has not been called yet.

Photometry

class tengri.Photometry(filters: tuple[FilterCurve, ...], names: tuple[str, ...] = (), convention: FilterConvention = FilterConvention.BESSELL, filter_waves: tuple[Array, ...] = (), filter_trans: tuple[Array, ...] = (), n_filters: int = 0, _fw_padded: Array | None = None, _ft_padded: Array | None = None, _n_valid: Array | None = None)[source]

Bases: object

Photometric observation configuration, filter set, not the fluxes.

This class holds which bands the model should evaluate. Measured fluxes and uncertainties are passed separately to tengri.Fitter (data= and noise=).

Don’t call Photometry(...) directly, use the factory:

>>> phot = tengri.Photometry.from_names(["sdss_g", "sdss_r", "sdss_i"])

or browse the bundled set:

>>> bandset = tengri.list_filters(survey="SDSS").names()
>>> phot = tengri.Photometry.from_names(bandset)

Then the full fit pattern:

obs = tengri.Observation(photometry=phot)
sed = tengri.SEDModel.build(ssp_data=ssp_data, observation=obs, redshift=tengri.Fixed(0.1))
forward = tengri.ForwardModel.build(sed=sed, observation=obs)

# Your measured fluxes and sigmas go in here, not into Photometry.
posterior = forward.fit(measured_fluxes, measured_errors, method="mcmc_nuts")
Parameters:
  • filters (tuple of FilterCurve) – Filter transmission curves.

  • names (tuple of str) – Human-readable filter names (e.g. ("sdss_r", "sdss_i")).

Returns:

Photometry instance with derived fields populated.

Return type:

Photometry

Variables:
  • filters (tuple[FilterCurve, ...]) – Filter transmission curves.

  • names (tuple[str, ...]) – Human-readable filter names.

  • filter_waves (tuple[ndarray, ...]) – Wavelength arrays for each filter [Angstrom].

  • filter_trans (tuple[ndarray, ...]) – Transmission curves for each filter [dimensionless].

  • n_filters (int) – Number of filters.

Notes

A frozen dataclass that encapsulates filter metadata and transmission curves. Provides factory methods (from_names, from_filter_set) for convenient construction. Precomputes derived fields (filter_waves, filter_trans, n_filters) at initialization for efficient SED projection.

Examples

>>> from tengri import Photometry
>>> phot = Photometry.from_names(["sdss_r", "sdss_i"])
>>> phot.n_filters
2
cache_key() → tuple[source]

Return a hashable cache key for this photometry configuration.

Returns:

Cache key derived from filters, names, and convention.

Return type:

tuple

Notes

Derived fields (filter_waves, filter_trans, n_filters, _fw_padded, _ft_padded, _n_valid) are excluded as they are computed from filters.

convention: FilterConvention = 'bessell'
filter_trans: tuple[Array, ...] = ()
filter_waves: tuple[Array, ...] = ()
filters: tuple[FilterCurve, ...]
static from_filter_set(filter_set: tuple[list[Array], list[Array], list[FilterCurve]] | list[FilterCurve] | tuple, convention: FilterConvention | str = FilterConvention.BESSELL) → Photometry[source]

Create Photometry from existing filter data.

Accepts the 3-tuple returned by load_filter_set() or a list of FilterCurve objects.

Parameters:

filter_set (tuple | list) – Either a 3-tuple (filter_waves, filter_trans, filter_curves) from load_filter_set(), or a list/tuple of FilterCurve objects.

Returns:

Configured photometry with precomputed field (filter curves, wavelengths, transmissions, and filter count).

Return type:

Photometry

Notes

Flexible constructor that accepts pre-loaded filter data. Useful when filters are already loaded or constructed by external code.

Examples

>>> from tengri.observation.filters import load_filter_set
>>> waves, trans, curves = load_filter_set(["sdss_r", "sdss_i"])
>>> phot = Photometry.from_filter_set((waves, trans, curves))
static from_names(names: Sequence[str], cache_dir: str | None = None, convention: FilterConvention | str = FilterConvention.BESSELL) → Photometry[source]

Create Photometry from filter registry short names.

Parameters:
  • names (sequence[str]) – Short names from FILTER_REGISTRY (e.g. "sdss_r", "jwst_f200w").

  • cache_dir (str or None, optional) – Directory for cached SVO filter files. None (default) resolves through tengri.observation.filters.default_filter_cache_dir(), which is independent of the working directory. The former default, the literal "data/filters", was relative to wherever the process started: from any other directory it silently missed the populated cache and re-fetched every curve from SVO (#1486).

  • convention (FilterConvention or str, optional) – Filter-convolution convention: "bessell" (default, photon-counting 1/lambda; DSPS/FSPS) or "energy" (1/lambda^2; CIGALE). See tengri.list_filter_conventions().

Returns:

Configured photometry with loaded filter transmission curves. Filters are validated against the global registry.

Return type:

Photometry

Notes

Loads filter transmission curves from the SVO filter service or local cache. Filter names are validated against the registry; unrecognized names raise a KeyError.

Examples

>>> phot = Photometry.from_names(["sdss_u", "sdss_g", "sdss_r"])
>>> phot.n_filters
3
n_filters: int = 0
names: tuple[str, ...] = ()
summary() → str[source]

Return a one-line summary of the photometry configuration.

Returns:

Filter count and comma-separated filter names.

Return type:

str

Notes

Provides concise string representation for logging and diagnostics.

Spectroscopy

class tengri.Spectroscopy(wave_obs: Array, resolution: float | Array | None = None, sigma_lib_kms: float = 70.0, lsf_n_bins: int = 16, calibration_order: int = 0, resample: str = 'auto', eline_prior_sigma: float = 100.0, eline_mode: str = 'off', eline_catalog: object | None = None, eline_prior_type: str = 'flat', eline_prior_width_dex: float = 0.3, eline_fix_doublets: bool = True, eline_broad: bool = False, eline_broad_fwhm_min_kms: float = 500.0, eline_kinematics: Mapping[str, Mapping] | tuple[tuple[str, tuple[str, ...], bool], ...] | None = None, nebular_lines: bool = True, covariance: Array | BandedMatrix | None = None, resolution_matrix: object | None = None, wave_obs_segment_sizes: tuple[int, ...] | None = None, calibration_segments: object | None = None, cal_prior: str = 'gaussian', cal_scale_prior: tuple[float, float] | None = None, cal_scale_window: tuple[float, float] | None = None, wave_unit: dataclasses.InitVar[str] = 'AA')[source]

Bases: object

Spectroscopic observation configuration.

Parameters:
  • wave_obs (jnp.ndarray) – Observed-frame wavelength grid [Angstrom], shape (n_pix,), unless wave_unit states otherwise.

  • wave_unit (str, optional) – Unit of wave_obs at construction: "AA" (default; "angstrom" is equivalent), "nm", "um" or "micron", case-insensitive. Converted to Angstrom once, here; the stored wave_obs is always Angstrom. Frequency ("Hz", "kHz", "MHz", "GHz") and energy ("eV", "keV") units are accepted, but they reverse the order, so a flux and error array must be reversed with wave_obs. A range wholly below 0.01 Å or above 3e11 Å is refused with ValueError. A range wholly in 100-1340 Å warns when the unit is Angstrom. Not a field: it is not stored on the instance.

  • wave_obs_segment_sizes (tuple[int, ...] or None) – Pixel counts for each camera segment. Multi-camera spectrographs (e.g., DESI) concatenate camera grids that overlap at seams; segment sizes enable per-camera monotonicity checks while allowing wavelength overlaps between cameras. Default: None.

  • resolution (float, jnp.ndarray, or None) – Spectral resolution R = lambda / delta_lambda. Scalar for constant R, per-pixel array for wavelength-dependent, or None to skip LSF convolution. Default: None.

  • sigma_lib_kms (float) – SSP library velocity dispersion [km/s] to subtract in quadrature when applying the LSF. Default: 70.0 (MILES).

  • lsf_n_bins (int) – Number of bins for piecewise constant approximation of variable-R LSF convolution. Default: 16.

  • resample ({"auto", "point", "conserving"}) – How the model is turned into pixel values (#2530). "point" interpolates the model at each pixel center; "conserving" takes the mean of the model over the pixel (the integral between the midpoints of neighboring pixel centers, divided by the width); "auto" takes the mean where some pixel is wider than the model-grid interval it lies in and the point sample otherwise. The decision is made once, before tracing, in the model’s rest frame at the fixed redshift (the lowest redshift of the prior when redshift is free). Default: "auto".

  • calibration_order (int) – Order of multiplicative Chebyshev calibration polynomial. 0 = no calibration (default). Order N adds N free params (cal_c1, …, cal_cN) with Gaussian(0, 0.1) priors.

  • calibration_segments (tuple[int, ...], ndarray or None) – Camera segments of the calibration multiplier: the pixel count of each segment (for example wave_obs_segment_sizes) or one integer id per pixel, the ids being 0 .. n_seg - 1. Each segment gets its own free scale in the analytic calibration marginal. Default: None (the multiplier is 1 + sum_j a_j T_j).

  • cal_prior ({"gaussian", "scale_free"}) – Prior on the calibration coefficients in the analytic marginal. "gaussian" is N(0, sigma^2) on the tilt and N(1, sigma^2) on each segment scale; "scale_free" is flat in data-flux units. Default: "gaussian".

  • cal_scale_prior (tuple[float, float] or None) – (log10_center, sigma_dex) of a log-normal prior on the mean calibration multiplier q over the window. q becomes one extra sampled latent, cal_log_q = ln q. A Gaussian in q itself at 0.3 dex would put 7 % of its mass at q < 0 and much more on the high side, which is why the log-normal is the form. Default: None.

  • cal_scale_window (tuple[float, float] or None) – (lo, hi) [Angstrom] inside the grid over which q is averaged. Default: None, every fitted pixel of the segment that contains the r band’s effective wavelength (6231 Angstrom). Needs cal_scale_prior.

  • eline_prior_sigma (float) – Width w [data units] of the zero-mean Gaussian prior on each emission-line amplitude that is marginalized. The marginal is exact at that finite width, not the improper-prior limit, so each constrained line lowers the evidence by about ln w nats; compare the evidences of models with different numbers of marginalized lines only at the same width. Default: 100.0.

  • eline_mode (str) –

    Emission line fitting mode. One of:

    • "off": No emission line fitting (default).

    • "marginalized": Analytically marginalize line amplitudes (recommended for spectroscopic fitting).

    • "fitted": Line amplitudes as free MCMC parameters.

    Default: "off".

    Retired mode: "fixed" was accepted but unused; pass "off" instead.

  • eline_catalog (LineList or None) – Line catalog. None falls back to LineList.default_13() for Use LineList.default_optical() for FastSpecFit parity. Default: None.

  • eline_prior_type (str) – Prior type for line amplitudes. One of "flat" (uninformative) or "cloudy" (CLOUDY-grid-interpolated), or "model" (a Gaussian centered on the model’s own attenuated line luminosity, on the per-galaxy and the batched path). Default: "flat".

  • eline_prior_width_dex (float) – Prior scatter in dex for the "cloudy" and "model" priors. Default: 0.3.

  • eline_fix_doublets (bool) – Enforce atomic physics doublet ratios. Default: True.

  • eline_broad (bool) – Retired; True raises. Use eline_kinematics with "add": True.

  • eline_broad_fwhm_min_kms (float) – Unused; kept so existing configurations load.

  • eline_kinematics (mapping or None) – Kinematic groups, {group: {"lines": [names], "add": bool}}. Every line of a group shares eline_sigma_kms_<group> and eline_delta_v_kms_<group>; lines named in no group keep eline_sigma_kms and eline_delta_v_kms. "add": True gives the named lines a second component with its own amplitude (a broad component). See LineList.with_kinematics(). Default: None (one group).

  • nebular_lines (bool) – Whether the predicted spectrum carries the nebular emission lines. True (default) projects the full sed_nebular. False drops the lines from spec_fnu and keeps the nebular continuum, for a likelihood that models the lines itself; photometry is unchanged. Needs a Cue nebular component built with neb={"type": "cue", "publish_line_fraction": True} and dust that republishes the reddened sed_nebular (two_component, age_binned, or no dust). Default: True.

  • covariance (jnp.ndarray, BandedMatrix or None) – Spectral covariance matrix, a dense array of shape (n_pix, n_pix) or a symmetric BandedMatrix. When provided, the likelihood whitens the residual with the Cholesky factor of the covariance instead of dividing by per-pixel sigma. A banded matrix, and a dense matrix whose entries beyond a half-bandwidth below a quarter of n_pix are zero to 1e-12 of the largest variance, is factored once at construction into a banded lower factor (banded_cholesky()). Any other dense matrix is inverted once. Default: None (diagonal noise).

Returns:

Spectroscopy instance with covariance matrix inverted and metadata set.

Return type:

Spectroscopy

Variables:
  • wave_obs (ndarray, shape (n_pix,)) – Observed-frame wavelength grid [Angstrom].

  • resolution (float, ndarray, or None) – Spectral resolution.

  • sigma_lib_kms (float) – SSP library velocity dispersion [km/s].

  • lsf_n_bins (int) – Number of LSF approximation bins.

  • calibration_order (int) – Chebyshev polynomial order.

  • eline_prior_sigma (float) – Emission line prior width.

  • eline_mode (str) – Emission line fitting mode.

  • eline_catalog (LineList or None) – Emission line catalog.

  • eline_prior_type (str) – Prior type for line marginalization.

  • eline_prior_width_dex (float) – Prior scatter [dex].

  • eline_fix_doublets (bool) – Whether to enforce doublet ratios.

  • eline_broad (bool) – Whether broad AGN component is enabled.

  • eline_broad_fwhm_min_kms (float) – Minimum broad component FWHM [km/s].

  • nebular_lines (bool) – Whether spec_fnu carries the nebular emission lines.

  • covariance (ndarray, shape (n_pix, n_pix), BandedMatrix or None) – Spectral covariance matrix.

  • chol_data (ndarray, shape (p + 1, n_pix) or None) – Bands of the lower Cholesky factor of a banded covariance.

  • chol_offsets (tuple of int or None) – Diagonal offsets (0, -1, ..., -p) of the factor.

Notes

A frozen dataclass that encapsulates spectroscopic instrument metadata, including wavelength grid, resolution profile, calibration strategy, and emission-line fitting configuration. Factors a banded covariance, or inverts a dense one, at initialization for efficient likelihood evaluation. Used by SEDModel to configure spectral prediction and by the inference engine to set up calibration priors.

Pixel values. A pixel records the mean of the spectrum over its edges. A point sample equals that mean only where the model is smooth across the pixel; for a Gaussian line of sigma = 1 Angstrom in 2 Angstrom pixels it reads 13.7 % high at the line center, and an unresolved line 166 % high. The pixel mean of the model is exact for a model that is linear between its nodes and is continuous, with a continuous derivative in redshift. In the pixel-mean modes the kinematic and Gaussian instrument broadening act on the model grid and the mean over the pixel is taken last; a banded resolution matrix acts on the pixels. The point mode resamples first. What a point sample leaves wrong on pixels wider than the model grid, as a fraction of the line peak: 3-13 % for 2 Angstrom pixels (up to 40 % for narrow lines), 17-100 % for a prism (R = 100), and 2-33 % in integrated line flux.

Other codes. BAGPIPES resamples its model spectrum onto the observed pixels with SpectRes, a flux-conserving bin integral (bagpipes/models/model_galaxy.py, spectres.spectres); with a resolution curve it first resamples onto a grid oversampled by 4 per resolution FWHM, disperses there, and integrates onto the pixels last. Prospector smooths the model on its own grid and then interpolates at the pixel wavelengths (sedpy.smoothing.smoothspec with outwave, called from prospect/models/sedmodel.py), a point sample. SpectRes: Carnall (2017), arXiv:1705.05165.

Examples

>>> import jax.numpy as jnp
>>> from tengri import Spectroscopy
>>> wave = jnp.linspace(4000.0, 9000.0, 500)
>>> spec = Spectroscopy(wave_obs=wave, resolution=1000.0)
>>> spec.n_pixels
500
cache_key() → tuple[source]

Return a hashable cache key for this spectroscopy configuration.

Returns:

Cache key derived from configuration attributes.

Return type:

tuple

Notes

Covariance matrix shape is keyed by content only (grid size fixes the likelihood). Covariance values move the key since two same-shaped matrices with different values must not share a compiled kernel.

cal_prior: str = 'gaussian'
cal_scale_prior: tuple[float, float] | None = None
cal_scale_window: tuple[float, float] | None = None
calibration_coeffs(params) → Array | None[source]

Extract calibration coefficients from parameter dict.

Returns:

Chebyshev polynomial coefficients [c_1, c_2, ..., c_N], extracted from params["cal_c1"], …, params["cal_cN"]. Returns None when calibration_order == 0.

Return type:

ndarray, shape (calibration_order,), or None

Notes

Keys are constructed with the same f-string shape as get_calibration_params() to prevent drift.

calibration_order: int = 0
calibration_segments: object | None = None
property calibration_wave_range

Wavelength range anchoring the calibration polynomial to [-1, 1].

Returns:

(wave_min, wave_max) [Angstrom] of the configured wave_obs.

Return type:

tuple of scalar

Notes

JIT-compatible: yes. The bounds are returned as JAX scalars, never Python floats: Spectroscopy is a pytree, so wave_obs is a tracer inside predict_observables_jit and float() on it would raise ConcretizationTypeError. They are only ever consumed arithmetically (by calibration_polynomial()), so tracers are fine.

The polynomial is normalized to the configured instrument grid, not to whatever grid a caller passes, so a given cal_cN keeps the same meaning when the model is evaluated on a custom wave_obs.

property chol_data: Array | None

Bands of the lower Cholesky factor of a banded covariance, or None.

Returns:

data[k, i] = L[i, i - k] [data units], or None when the covariance is absent or dense and not banded.

Return type:

ndarray, shape (p + 1, n_pix) or None

property chol_offsets: tuple[int, ...] | None

Diagonal offsets (0, -1, ..., -p) of chol_data, or None.

static constant_r(wave_obs: Array, R: float, *, wave_unit: str = 'AA', **kwargs) → Spectroscopy[source]

Constant-resolution spectrograph.

Parameters:
  • wave_obs (ndarray, shape (n_pix,)) – Observed-frame wavelength grid [Angstrom], or in wave_unit.

  • R (float) – Spectral resolution R = lambda / delta_lambda (constant across all wavelengths, dimensionless).

  • wave_unit (str, optional) – Unit of wave_obs: "AA" (default), "nm", "um", "micron" or "angstrom", case-insensitive. Converted to Angstrom before the resolution law is evaluated.

  • **kwargs – Additional keyword arguments passed to Spectroscopy.

Returns:

Configured spectrograph with constant wavelength-independent resolution.

Return type:

Spectroscopy

Notes

Convenient factory for instruments with wavelength-independent spectral resolution, such as low-resolution JWST NIRSpec PRISM approximations or ideal spectrographs.

property cov_inv: Array | None

Inverse covariance matrix, or None.

Returns:

Inverse covariance matrix, shape (n_pix, n_pix), or None if diagonal noise is assumed.

Return type:

ndarray or None

Notes

Read-only. A dense, non-banded covariance is inverted at construction. A banded covariance is inverted here on each call; the likelihoods use the banded factor and never read it.

covariance: Array | BandedMatrix | None = None
classmethod desi_like(wave_obs: Array, resolution: float = 2500.0, *, wave_unit: str = 'AA', **kwargs) → Spectroscopy[source]

DESI-like spectroscopic configuration with full line fitting.

Pre-configured with:

  • ~40-line optical catalog (FastSpecFit parity)

  • Marginalized emission lines with CLOUDY priors

  • Doublet constraints enabled

  • Calibration polynomial order 3

Parameters:
  • wave_obs (ndarray, shape (n_pix,)) – Observed-frame wavelength grid [Angstrom], or in wave_unit.

  • resolution (float, optional) – Spectral resolution R = lambda / delta_lambda (dimensionless). Default: 2500 (DESI standard).

  • wave_unit (str, optional) – Unit of wave_obs: "AA" (default), "nm", "um", "micron" or "angstrom", case-insensitive. Converted to Angstrom before the resolution law is evaluated.

  • **kwargs – Additional keyword arguments passed to Spectroscopy.

Returns:

Fully configured spectroscopy for DESI-like emission-line fitting with all standard settings pre-applied.

Return type:

Spectroscopy

Notes

This configuration mirrors DESI’s optical spectroscopy capabilities, including marginalized emission line amplitudes with CLOUDY-based priors and atomic physics constraints. Suitable for large spectroscopic surveys of emission-line galaxies.

property effective_catalog: object

Return the catalog, falling back to default_13() if not set.

Returns:

The active line catalog (either explicitly configured or default).

Return type:

LineList

Notes

Provides convenient fallback logic: if eline_catalog is None, automatically returns the default 13-line catalog.

eline_broad: bool = False
eline_broad_fwhm_min_kms: float = 500.0
eline_catalog: object | None = None
eline_fix_doublets: bool = True
eline_kinematics: Mapping[str, Mapping] | tuple[tuple[str, tuple[str, ...], bool], ...] | None = None

{group: {"lines": [...], "add": bool}}; stored as a hashable tuple.

eline_mode: str = 'off'
eline_prior_sigma: float = 100.0
eline_prior_type: str = 'flat'
eline_prior_width_dex: float = 0.3
classmethod from_fits(fits_path: str, *, wave_col: str = 'WAVELENGTH', flux_col: str = 'FLUX', err_col: str = 'FLUX_ERROR', wave_unit_aa: float = 1.0, flux_unit_cgs: float = 1.0, ext: int | str = 1, resolution: float | Array | None = None, **kwargs) → tuple[Spectroscopy, Array, Array][source]

Load from a generic FITS binary table spectrum.

Parameters:
  • fits_path (str) – Path to the FITS file.

  • wave_col (str) – Column name for wavelength. Default: "WAVELENGTH".

  • flux_col (str) – Column name for flux. Default: "FLUX".

  • err_col (str) – Column name for flux error. Default: "FLUX_ERROR".

  • wave_unit_aa (float) – Multiplicative factor to convert wavelength column to Angstrom. E.g., 1e4 for µm input. Default: 1.0 (already Å). This is a scale factor read from the file’s header, not a unit name; to state a unit name for a raw array, pass wave_unit= to the Spectroscopy constructor instead.

  • flux_unit_cgs (float) – Multiplicative factor to convert flux column to erg/s/cm²/Hz. E.g., 1e-29 for µJy. Default: 1.0 (already CGS).

  • ext (int or str) – FITS extension. Default: 1.

  • resolution (float, ndarray, or None) – Spectral resolution. Default: None. Additional keyword arguments passed to Spectroscopy.

Returns:

(spec_config, flux_obs, flux_err) in Angstrom and CGS.

Return type:

tuple[Spectroscopy, ndarray, ndarray]

Notes

Requires astropy. Generic reader for any FITS binary table spectrum. For JWST x1d files, prefer from_jwst_x1d which handles unit conversion and resolution auto-detection.

classmethod from_jwst_x1d(fits_path: str, *, ext: int | str = 1, resolution: float | Array | None = None, **kwargs) → tuple[Spectroscopy, Array, Array][source]

Load from a JWST x1d/x1dints FITS spectrum.

Reads WAVELENGTH (µm), FLUX (µJy), and FLUX_ERROR (µJy) from the specified extension and converts to tengri internal units (Angstrom, erg/s/cm²/Hz).

Parameters:
  • fits_path (str) – Path to the x1d FITS file.

  • ext (int or str) – FITS extension containing the spectrum table. Default: 1.

  • resolution (float, ndarray, or None) – Spectral resolution override. If None, auto-selects based on the FILTER or GRATING header keyword. Default: None. Additional keyword arguments passed to Spectroscopy.

Returns:

(spec_config, flux_obs, flux_err) where flux values are in erg/s/cm²/Hz and wavelengths in Angstrom.

Return type:

tuple[Spectroscopy, ndarray, ndarray]

Notes

Requires astropy. NaN pixels are masked by setting their error to infinity.

Unit conversions:

  • Wavelength: µm → Å (×10⁴)

  • Flux: µJy → erg/s/cm²/Hz (×10⁻²⁹)

get_calibration_params() → dict[str, Distribution][source]

Return Parameters entries for calibration polynomial.

Returns:

Mapping of calibration coefficient names (cal_c1, …, cal_cN) to Gaussian(0, 0.1) priors, plus cal_log_q (the log of the mean multiplier, a Gaussian from cal_scale_prior) when that is set. Empty dict if calibration_order == 0 and cal_scale_prior is None.

Return type:

dict[str, Distribution]

Notes

Called by Observation.get_all_params() to register observation-level parameters with the inference engine. Each coefficient has a weak Gaussian prior centered at 0 in log space (unity in linear space).

property has_banded_covariance: bool

Whether the covariance is held as a banded Cholesky factor.

property has_calibration: bool

Whether a calibration polynomial is configured.

Returns:

True if calibration order is > 0.

Return type:

bool

Notes

Read-only property; determines whether calibration coefficients are registered as free parameters.

property has_covariance: bool

Whether a full covariance matrix is configured.

Returns:

True if covariance matrix is present.

Return type:

bool

Notes

Read-only property; determined at initialization.

property has_eline_fitting: bool

True if emission lines are being fit (marginalized or fitted mode).

Returns:

True if eline_mode is “marginalized” or “fitted”.

Return type:

bool

Notes

Read-only property; determines whether emission line amplitudes are treated as free parameters or analytically marginalized.

property has_lsf: bool

Whether LSF convolution is configured.

Returns:

True if resolution profile is specified.

Return type:

bool

Notes

Read-only property; determines whether LSF convolution is applied in the forward model.

property has_resolution_matrix: bool

Whether a banded instrument resolution matrix is configured (#1163).

Returns:

True if a BandedMatrix is set, in which case it replaces the Gaussian apply_lsf in projection (the DESI/PFS spectro-perfectionism convention; Bolton & Schlegel 2010).

Return type:

bool

Notes

Read-only property; determined at initialization.

lsf_n_bins: int = 16
property n_cal_segments: int

Number of calibration segments; 0 without calibration_segments.

property n_pixels: int

Number of spectral pixels.

Returns:

Number of wavelength grid points.

Return type:

int

Notes

Read-only property; computed from the length of wave_obs.

nebular_lines: bool = True
static nirspec_g140m(wave_obs: Array, *, wave_unit: str = 'AA', **kwargs) → Spectroscopy[source]

JWST NIRSpec G140M: roughly constant R ~ 1000.

Parameters:
  • wave_obs (ndarray, shape (n_pix,)) – Observed-frame wavelength grid [Angstrom], or in wave_unit.

  • wave_unit (str, optional) – Unit of wave_obs: "AA" (default), "nm", "um", "micron" or "angstrom", case-insensitive. Converted to Angstrom before the resolution law is evaluated.

  • **kwargs – Additional keyword arguments passed to Spectroscopy.

Returns:

Configured NIRSpec G140M spectroscopy with approximately constant resolution R~1000.

Return type:

Spectroscopy

Notes

Applies wavelength-dependent resolution for NIRSpec’s medium-resolution G140M mode. Resolution is approximately constant at R~1000 across the wavelength range.

static nirspec_prism(wave_obs: Array, *, wave_unit: str = 'AA', **kwargs) → Spectroscopy[source]

JWST NIRSpec PRISM: variable R ~ 30-330 (Jakobsen+2022).

Parameters:
  • wave_obs (ndarray, shape (n_pix,)) – Observed-frame wavelength grid [Angstrom], or in wave_unit.

  • wave_unit (str, optional) – Unit of wave_obs: "AA" (default), "nm", "um", "micron" or "angstrom", case-insensitive. Converted to Angstrom before the resolution law is evaluated.

  • **kwargs – Additional keyword arguments passed to Spectroscopy.

Returns:

Configured NIRSpec PRISM spectroscopy with wavelength-dependent resolution.

Return type:

Spectroscopy

Notes

Applies wavelength-dependent resolution appropriate for NIRSpec’s PRISM mode. Resolution varies from R~30 in the red to R~330 in the blue (Jakobsen et al. 2022).

resample: str = 'auto'
resolution: float | Array | None = None
resolution_matrix: object | None = None
resolve_conserving(wave_rest_model, z_ref: float = 0.0, wave_obs=None) → bool[source]

Resolve the resample mode to a flux-conserving flag (#1166, #2530).

"point" maps to False and "conserving" to True. "auto" returns True when, anywhere in the overlap of the pixels and the model, a pixel is wider than the model-grid interval it falls in: there a point sample skips model structure that the pixel integral keeps. Where every pixel is at least as fine as the model the two modes agree to the interpolation error of the model itself, so the decision is made per pixel, not from a median spacing that a grid with a coarse and a fine region would hide. Every path that turns a model into pixels calls this one function, so they cannot disagree.

The decision is evaluated in the model’s rest frame: the observed pixels are divided by 1 + z_ref. It is a pure-Python decision made once before tracing, so the forward branch stays static.

Parameters:
  • wave_rest_model (array_like, shape (n_wave,)) – Rest-frame model wavelength grid [Angstrom], increasing.

  • z_ref (float, optional) – Redshift at which observed pixels are mapped to the rest frame. Pass the fixed redshift, or the lowest redshift of the prior when redshift is free (the coarsest rest-frame pixels). Default 0.0.

  • wave_obs (array_like, shape (n_pix,), optional) – Pixel grid actually being evaluated, when it is not the configured one. A traced grid cannot be inspected and the configured grid is used instead. Default None (the configured grid).

Returns:

Whether to use the flux-conserving resample.

Return type:

bool

Raises:

ValueError – If resample="conserving" on a pixel grid that is not strictly increasing (overlapping camera seams); the bin integral needs bin edges that increase. "auto" point-samples such a grid.

property segment_ids: ndarray | None

Per-pixel calibration segment id, or None without calibration_segments.

Returns:

Id of the camera segment of every pixel, in range(n_cal_segments).

Return type:

ndarray of int, shape (n_pix,), or None

Notes

calibration_segments takes the per-segment pixel counts (for example wave_obs_segment_sizes) or one integer id per pixel. Build-time NumPy property, not JIT-compatible.

sigma_lib_kms: float = 70.0
summary() → str[source]

Return a one-line summary of the spectroscopy configuration.

Returns:

Comma-separated summary (e.g., “500 pixels, R=2500, eline=marginalized”). Includes pixel count, resolution, calibration order, emission-line mode, and covariance info.

Return type:

str

Notes

Used for logging and diagnostics. Provides a compact, human-readable representation of the instrument configuration. Intended for display to users, not for programmatic parsing.

wave_obs: Array
wave_obs_segment_sizes: tuple[int, ...] | None = None
wave_unit: dataclasses.InitVar[str] = 'AA'

Unit of wave_obs at construction [AA | angstrom | nm | um | micron]. Init-only: wave_obs is converted to Angstrom here and stored in Angstrom.

Line list

class tengri.LineList(names: tuple[str, ...], wavelengths: Array, species: tuple[str, ...], doublets: tuple[DoubletConstraint, ...], is_balmer: tuple[bool, ...], is_broad_candidate: tuple[bool, ...], is_strong: tuple[bool, ...], plot_group: tuple[str, ...], kinematic_group: tuple[str, ...] = ())[source]

Bases: object

Immutable registry of emission lines for spectroscopic fitting.

Parameters:
  • names (tuple[str, ...]) – Line identifiers (e.g. "Halpha", "OIII_5007").

  • wavelengths (jnp.ndarray) – Rest-frame vacuum wavelengths in Angstrom, shape (n_lines,).

  • species (tuple[str, ...]) – Chemical species codes matching CLOUDY convention (e.g. "H1", "O3", "N2").

  • doublets (tuple[DoubletConstraint, ...]) – Doublet flux-ratio constraints between paired lines.

  • is_balmer (tuple[bool, ...]) – True for hydrogen Balmer/Lyman series lines.

  • is_broad_candidate (tuple[bool, ...]) – True for lines that can carry a broad AGN component.

  • is_strong (tuple[bool, ...]) – True for lines reliably detected in DESI spectra. Matches the isstrong column in FastSpecFit emlines.ecsv [tengri.LineList-1].

  • plot_group (tuple[str, ...]) – QA plot group label. Lines sharing a group are displayed together in diagnostic panels. Matches the plotgroup column in FastSpecFit emlines.ecsv [tengri.LineList-1] (e.g. "halpha_nii_6548_48", "oiii_doublet").

Returns:

Immutable line catalog instance.

Return type:

LineList

Variables:
  • names (tuple[str, ...]) – Line identifiers.

  • wavelengths (ndarray, shape (n_lines,)) – Rest-frame vacuum wavelengths [Angstrom].

  • species (tuple[str, ...]) – CLOUDY species codes.

  • doublets (tuple[DoubletConstraint, ...]) – Doublet constraints.

  • is_balmer (tuple[bool, ...]) – Balmer/Lyman series flags.

  • is_broad_candidate (tuple[bool, ...]) – Broad component candidate flags.

  • is_strong (tuple[bool, ...]) – Strong line detection flags (DESI context).

  • plot_group (tuple[str, ...]) – QA plot group labels.

Notes

Immutable container: A frozen dataclass. All fields are read-only.

Wavelength convention: All wavelengths are vacuum (not air) and rest-frame (not observed-frame).

References

[tengri.LineList-1] (1,2)

Moustakas, J., Scholte, D., Dey, B., Khederlarian, A., 2023, “FastSpecFit: Fast spectral synthesis and emission-line fitting of DESI spectra”, Astrophysics Source Code Library, record ascl:2308.005. https://ui.adsabs.harvard.edu/abs/2023ascl.soft08005M

Examples

Build the default DESI-like catalog and select BPT lines:

cat = LineList.default_optical()
bpt = cat.select(names=["Halpha", "Hbeta", "OIII_5007", "NII_6584"])
C = bpt.build_constraint_matrix()  # (n_lines, n_independent)

Inspect strong-line detections:

strong_names = [n for n, s in zip(cat.names, cat.is_strong) if s]
# ['Lya', 'NV_1240', 'CIV_1549', ...]

Find lines in the Halpha+NII panel:

panel = [n for n, g in zip(cat.names, cat.plot_group) if g == "halpha_nii_6548_48"]
# ['NII_6548', 'Halpha', 'NII_6584']

Use a custom wavelength subset from a line-finding step:

detected = cat.select(wavelengths=[6564.61, 4862.68, 5008.24])
build_constraint_matrix() → Array[source]

Build the (n_lines, n_independent) constraint matrix C.

The constraint matrix maps from independent amplitudes to all line amplitudes: flux = C @ a_independent.

Returns:

Linear constraint matrix. Each row represents one emission line; each column represents one independent amplitude parameter. For constrained secondary lines, the row encodes the constraint relationship; for primary lines, the row has a unit entry.

Return type:

ndarray, shape (n_lines, n_independent)

Notes

Not JIT-compatible (uses NumPy array mutation and slicing).

For each doublet constraint with flux_secondary = flux_primary / ratio, the corresponding column is removed and the secondary line’s row encodes the constraint via an off-diagonal entry 1 / ratio in the primary column. This ensures that fitting n_independent amplitudes automatically enforces all doublet ratio constraints via matrix multiplication: a_full = C @ a_independent.

cache_key() → tuple[source]

Return a hashable cache key for this line catalog.

Returns:

Cache key derived from all catalog fields.

Return type:

tuple

Notes

All fields are included by content as they define the catalog structure and amplitude relationships.

classmethod default_13() → LineList[source]

Backward-compatible 13-line catalog (legacy default).

Uses the same wavelengths as DEFAULT_LINE_WAVELENGTHS in eline_marginalization.py. Insertion order is preserved for index-based lookups.

Returns:

13-line catalog with doublet constraints where applicable.

Return type:

LineList

Notes

Not JIT-compatible (uses Python class method). Kept for backward compatibility with eline_marginalization.py.

Includes Lyman alpha, Balmer series, key optical lines, and commonly detected forbidden lines. Suitable for quick analyses where a compact line set is preferred over the full optical catalog.

classmethod default_optical() → LineList[source]

FastSpecFit-equivalent ~50-line catalog for optical/NIR spectroscopy.

Returns:

Catalog of ~50 lines sorted by wavelength [Angstrom] with doublet constraints auto-detected.

Return type:

LineList

Notes

Not JIT-compatible (uses Python sorting and class method).

Includes UV lines (1200–3000 Å), optical (3700–6800 Å), and near-infrared lines (7000–10000 Å). Line properties and doublet constraints follow the FastSpecFit standard (Moustakas et al. 2023).

classmethod default_uv() → LineList[source]

Rest-frame ultraviolet catalog with doublets and multiplets resolved.

Returns:

Lines between 1215 and 1910 Angstrom, each component a separate entry.

Return type:

LineList

Notes

For spectra with R of about 1000 or more (JWST/NIRSpec gratings at z > 5, HST/COS and STIS locally), where N V, Si IV, N IV], C IV, O III], the N III] multiplet, Si III] and C III] are resolved. No ratio is tied: the C III], N IV], N III] and Si III] ratios are electron-density diagnostics, and the resonant doublets depart from 2:1 when optically thick. The default optical catalog keeps the blended entries (CIV_1549, CIII_1908).

doublets: tuple[DoubletConstraint, ...]
classmethod from_cloudy_grid(filepath: str) → LineList[source]

Load all lines from a CLOUDY HDF5 grid file.

Reads lines/names and lines/wavelength datasets, parses species from CLOUDY naming conventions, and auto-detects doublets by species + wavelength proximity (< 20 Angstrom).

Parameters:

filepath (str) – Path to the CLOUDY HDF5 grid file containing lines/names and lines/wavelength datasets.

Returns:

Catalog populated from the CLOUDY grid, sorted by wavelength [Angstrom]. Doublet constraints are auto-detected by species and proximity.

Return type:

LineList

Raises:
  • ImportError – If h5py is not installed.

  • OSError – If the file cannot be opened or read.

  • KeyError – If required datasets (lines/names, lines/wavelength) are missing.

Notes

Not JIT-compatible (uses Python file I/O and h5py).

Parses CLOUDY species names (e.g., "H  1", "O  3") into compact codes ("H1", "O3"). Doublet detection requires same species and wavelength separation < 20 Å.

classmethod from_names(names: Sequence[str]) → LineList[source]

Construct a LineList from a list of line names.

Uses the default optical catalog and selects only the requested line names. Raises ValueError if any name is unknown.

Parameters:

names (sequence of str) – Line identifiers to select (e.g., ["Halpha", "OIII_5007"]).

Returns:

A new LineList containing only the requested lines, in wavelength order.

Return type:

LineList

Raises:

ValueError – If any name in names is not found in the default optical catalog.

Notes

Not JIT-compatible (uses Python class methods and filtering).

This is the recommended way to construct a LineList from line names for schema declarations:

obs = Observation(photometry=..., lines=LineList.from_names(["Halpha", "OIII_5007"]))

Examples

Select a few lines for a BPT diagram:

ll = LineList.from_names(["Halpha", "Hbeta", "OIII_5007", "NII_6584"])
assert ll.n_lines == 4
property group_index: ndarray

Index into kinematic_groups of each line, shape (n_lines,).

property independent_wavelengths: Array

Wavelengths of the independent (non-constrained) amplitude parameters.

After applying doublet constraints, the design matrix has n_independent columns, one per independent amplitude. This property returns the wavelength of each independent parameter’s primary line, in column order matching build_constraint_matrix().

Returns:

Rest-frame vacuum wavelengths in Angstrom for independent amplitude columns.

Return type:

ndarray, shape (n_independent,)

Notes

The returned wavelengths correspond to the columns of the constraint matrix returned by build_constraint_matrix(). Column order is the same as the order of non-constrained lines in the original catalog.

is_balmer: tuple[bool, ...]
is_broad_candidate: tuple[bool, ...]
is_strong: tuple[bool, ...]
kinematic_group: tuple[str, ...] = ()

Kinematic group of each line; () puts every line in the default group "".

property kinematic_groups: tuple[str, ...]

Distinct kinematic group names, in order of first appearance.

property line_groups: tuple[str, ...]

Kinematic group name of each line; "" is the default group.

property n_independent: int

Number of independent amplitude parameters after doublet constraints.

Returns:

Number of independent parameters (total lines minus doublet secondaries).

Return type:

int

Notes

Computed as n_lines - len(doublets), since each doublet constraint removes one degree of freedom.

property n_lines: int

Total number of lines in the catalog.

Returns:

Number of emission lines.

Return type:

int

Notes

Computed from the length of the names tuple. Constant for the lifetime of the object (immutable).

names: tuple[str, ...]
plot_group: tuple[str, ...]
select(wave_min: float = 0.0, wave_max: float = inf, species: Sequence[str] | None = None, names: Sequence[str] | None = None, wavelengths: Sequence[float] | None = None) → LineList[source]

Return a filtered copy of the catalog.

Parameters:
  • wave_min (float, optional) – Minimum rest-frame wavelength [Angstrom] (inclusive). Default: 0.

  • wave_max (float, optional) – Maximum rest-frame wavelength [Angstrom] (inclusive). Default: infinity.

  • species (sequence of str, optional) – If given, retain only lines whose species code is in this list. Default: None (no filtering).

  • names (sequence of str, optional) – If given, retain only lines whose name exactly matches one in this list. Default: None (no filtering).

  • wavelengths (sequence of float, optional) – If given, match each wavelength to the nearest line in the catalog within 5 Angstrom tolerance. Default: None (no filtering).

Returns:

New catalog containing only lines satisfying all given criteria (AND logic). Doublet constraints are rebuilt with updated indices; constraints where either member is filtered out are dropped.

Return type:

LineList

Raises:

ValueError – If any name in names is not found in the catalog, or if any wavelength in wavelengths cannot be matched within 5 Angstrom.

Notes

Not JIT-compatible (uses Python control flow and set operations).

All filtering criteria are combined via AND logic. If all criteria filter out all lines, returns an empty LineList.

Examples

Select BPT diagram lines by name:

cat = LineList.default_optical()
bpt = cat.select(names=["Halpha", "Hbeta", "OIII_5007", "NII_6584"])

Select by observed wavelengths (e.g. from a line-finding algorithm):

bpt = cat.select(wavelengths=[6564.61, 4862.68, 5008.24, 6585.28])

Select only optical window:

optical = cat.select(wave_min=3700.0, wave_max=7000.0)

Select hydrogen lines only:

hydrogen = cat.select(species=["H1"])
species: tuple[str, ...]
wavelengths: Array
with_kinematics(groups: Mapping[str, Mapping]) → LineList[source]

Return a copy with lines assigned to named kinematic groups.

Every line of one group shares a velocity offset and an intrinsic width (the parameters eline_delta_v_kms_<group> and eline_sigma_kms_<group>). Lines named in no group stay in the default group, whose parameters are eline_delta_v_kms and eline_sigma_kms.

Parameters:

groups (mapping of str to mapping) – {group: {"lines": [names], "add": bool}}. With "add": False (the default) the named lines move to the group. With "add": True each named line gains a second component, a new catalog entry <line>__<group> at the same wavelength with its own amplitude, which is how a broad component under a narrow line is written.

Returns:

New catalog. Added components follow the original lines.

Return type:

LineList

Raises:

ValueError – On a group name that is not lowercase letters, digits and underscores, an unknown line, a line moved to two groups, or a fixed-ratio doublet split across two groups.

Notes

Not JIT-compatible (build-time Python). A fixed-ratio doublet stays tied inside its group, and an added component of both members is tied by the same ratio. The group owns the kinematics and the line owns the amplitude, the tying scheme of pPXF’s kinematic components, FastSpecFit and PyQSOFit.

Examples

cat = LineList.default_uv().with_kinematics(
    {
        "lya": {"lines": ["Lya"]},
        "niv_broad": {"lines": ["NIV_1486"], "add": True},
    }
)

Spectral indices

A SpectralIndexDef defines one index; CompositeIndexDef combines atomic ones; and SpectralIndexData carries the observed values to fit against.

class tengri.SpectralIndexDef(name: str, index_type: str, continuum: tuple[tuple[float, float], ...], feature: tuple[float, float] | None = None, units: str = 'AA', pseudo_continuum: str = 'linear')[source]

Bases: object

Definition of a single spectral index.

Parameters:
  • name (str) – Human-readable name (e.g. "Dn4000").

  • index_type (str) – "EW" (equivalent width), "break" (flux ratio), or "slope" (power-law spectral slope β over a window, e.g. the UV continuum slope, Calzetti+1994).

  • continuum (tuple of tuple) – Continuum/sideband windows as ((lo1, hi1), (lo2, hi2), ...). Rest-frame wavelengths in Angstrom. For EW indices: blue and red pseudo-continuum sidebands. For break indices: exactly two windows (numerator, denominator). For slope indices: unused (pass ()); the fit range is feature.

  • feature (tuple of float or None) – Feature window (lo, hi) in Angstrom. Required for EW indices (the absorption feature) and slope indices (the fit range), None for break indices.

  • units (str) – "AA" for Angstrom (default) or "mag" for magnitude.

  • pseudo_continuum ({"linear", "mean"}) – How an EW index builds its pseudo-continuum (ignored by break and slope indices). "linear" (default) is the Lick definition [tengri.SpectralIndexDef-1]: the straight line through the mean \(F_\lambda\) of the two sidebands placed at the sideband mid-wavelengths, with \(\mathrm{EW} = \int (1 - F_\lambda/F_{C\lambda})\,d\lambda\) over the feature window (magnitude indices: \(-2.5\log_{10}\) of the feature-window mean of \(F_\lambda/F_{C\lambda}\)), measured on \(F_\lambda\) obtained from the flux argument (\(F_\lambda \propto F_\nu/\lambda^2\)). "mean" is BAGPIPES’ arithmetic (bagpipes.input.spectral_indices.single_index) and not the Lick definition: a constant continuum equal to the mean of the sideband means, W (C - <F>)/C, on the flux array exactly as given (no frame conversion). It exists to compare with BAGPIPES. "linear" needs exactly two continuum windows.

References

[tengri.SpectralIndexDef-1]

Trager, S. C., Worthey, G., Faber, S. M., Burstein, D., Gonzalez, J. J., 1998, ApJS, 116, 1 (Sect. 2.2, Eqs. 1-3).

Examples

>>> from tengri import SpectralIndexDef
>>> dn4000 = SpectralIndexDef(
...     name="Dn4000",
...     index_type="break",
...     continuum=((3850.0, 3950.0), (4000.0, 4100.0)),
... )
>>> dn4000.wave_min, dn4000.wave_max
(3850.0, 4100.0)
>>> hda = SpectralIndexDef(
...     name="HdA",
...     index_type="EW",
...     continuum=((4041.6, 4079.75), (4128.5, 4161.0)),
...     feature=(4083.5, 4122.25),
... )
>>> hda.index_type
'EW'
continuum: tuple[tuple[float, float], ...]
feature: tuple[float, float] | None = None
index_type: str
name: str
pseudo_continuum: str = 'linear'
units: str = 'AA'
property wave_max: float

Maximum wavelength needed to measure this index.

Returns:

Maximum wavelength [Angstrom] across all continuum and feature windows defined in this index.

Return type:

float

Notes

Computed as the maximum of all window edges. Useful for determining the maximum wavelength coverage needed in the forward model spectrum.

property wave_min: float

Minimum wavelength needed to measure this index.

Returns:

Minimum wavelength [Angstrom] across all continuum and feature windows defined in this index.

Return type:

float

Notes

Computed as the minimum of all window edges. Useful for determining the minimum wavelength coverage needed in the forward model spectrum.

class tengri.CompositeIndexDef(name: str, components: tuple[SpectralIndexDef, ...], combiner: Callable[[...], Array], units: str = 'AA')[source]

Bases: object

A spectral index that is a function of atomic indices.

Composite indices break the age-metallicity degeneracy by combining multiple Lick measurements (Worthey & Ottaviani 1997; Thomas, Maraston & Bender 2003). Standard examples include [MgFe]' (sensitive to [Fe/H] but not [alpha/Fe]) and <Fe> (the mean of Fe5270 and Fe5335).

Parameters:
  • name (str) – Human-readable name, e.g. "[MgFe]'" or "<Fe>".

  • components (tuple of SpectralIndexDef) – The atomic indices this composite is built from.

  • combiner (Callable) – Function that takes one argument per atomic index (in the same order as components) and returns the composite value. Must be JAX-compatible (operate on jnp arrays) so the composite stays differentiable through measure_index_jax.

  • units (str) – Units of the composite value, for display only. Default "AA".

Examples

The Thomas+2003 [MgFe]’ index:

from tengri import STANDARD_INDICES, CompositeIndexDef

mgfe_prime = CompositeIndexDef(
    name="[MgFe]'",
    components=(
        STANDARD_INDICES["Mgb"],
        STANDARD_INDICES["Fe5270"],
        STANDARD_INDICES["Fe5335"],
    ),
    combiner=lambda mgb, fe1, fe2: jnp.sqrt(
        jnp.maximum(mgb * (0.72 * fe1 + 0.28 * fe2), 0.0)
    ),
)
combiner: Callable[[...], Array]
components: tuple[SpectralIndexDef, ...]
name: str
units: str = 'AA'
property wave_max: float
property wave_min: float
class tengri.SpectralIndexData(index_defs: tuple[SpectralIndexDef, ...], values: Array, errors: Array)[source]

Bases: object

Observed spectral index values for fitting.

Parameters:
  • index_defs (tuple of SpectralIndexDef) – Index definitions.

  • values (jnp.ndarray) – Observed index values, shape (n_indices,).

  • errors (jnp.ndarray) – 1-sigma uncertainties, shape (n_indices,).

Returns:

Spectral index data container with validation.

Return type:

SpectralIndexData

Variables:
  • index_defs (tuple[SpectralIndexDef, ...]) – Index definitions.

  • values (ndarray, shape (n_indices,)) – Observed index values [dimensionless].

  • errors (ndarray, shape (n_indices,)) – 1-sigma measurement uncertainties [dimensionless].

Notes

Velocity-dispersion convention (#3466): values are the indices as measured on the observed spectrum, at its own velocity dispersion. They are not corrected to \(\sigma = 0\). The model index that predict_spectral_indices() returns is measured on the rest-frame SED broadened by the model’s sigma_v_kms (the default, broaden=True), so the two are compared like with like. Pass broaden=False for the unbroadened, \(\sigma = 0\) model index, which is the right comparison only for data already corrected to \(\sigma = 0\). sigma_v_kms is free in an index-only fit when declared the way the spectrum path declares it, model.spec.merge_observation_params( sigma_v_kms=Uniform(0.0, 2000.0)).

Immutable container: All fields are read-only by convention. Construct once with validated data, do not modify.

Indexing and access: Use names property to get human-readable line identifiers, n_indices for count, and index_defs for the full definition metadata.

Examples

>>> import jax.numpy as jnp
>>> from tengri import SpectralIndexData
>>> sid = SpectralIndexData.from_names(
...     names=["Dn4000", "HdA"],
...     values=[1.35, 5.2],
...     errors=[0.05, 0.3],
... )
>>> sid.n_indices
2
>>> sid.names
('Dn4000', 'HdA')
cache_key() → tuple[source]

Return a hashable cache key for this spectral index data.

Returns:

Cache key derived from index definitions and array shapes.

Return type:

tuple

Notes

Index definitions are keyed by content as they define the likelihood function. Value and error arrays are keyed by shape only (array values don’t affect the program, only the per-galaxy data does).

chi2(model_values: Array) → Array[source]

Chi-squared statistic.

Parameters:

model_values (ndarray, shape (n_indices,)) – Model-predicted index values (same units as values).

Returns:

Sum of ((obs - model) / error)^2 [dimensionless].

Return type:

ndarray, shape ()

Notes

JIT-compatible: yes, uses only jnp primitives.

Gradient-safe: yes, differentiable w.r.t. model_values.

errors: Array
classmethod from_names(names: list[str], values: list[float], errors: list[float]) → SpectralIndexData[source]

Construct from standard index names.

Parameters:
  • names (list[str]) – Index names from STANDARD_INDICES (e.g. ["Dn4000", "HdA"]).

  • values (list[float]) – Observed index values. Units depend on index type: [Angstrom] for EW indices, [dimensionless] for break indices.

  • errors (list[float]) – 1-sigma uncertainties (same units as values).

Returns:

Spectral index data object with index definitions looked up from STANDARD_INDICES.

Return type:

SpectralIndexData

Raises:

ValueError – If any name is not in STANDARD_INDICES.

Notes

The wavelength coverage required to measure all indices can be obtained via wave_range() property.

index_defs: tuple[SpectralIndexDef, ...]
log_likelihood(model_values: Array) → Array[source]

Gaussian log-likelihood.

Parameters:

model_values (ndarray, shape (n_indices,)) – Model-predicted index values (same units as values).

Returns:

Total log-likelihood summed over all indices [dimensionless].

Return type:

ndarray, shape ()

Notes

JIT-compatible: yes, uses only jnp primitives.

Gradient-safe: yes, differentiable w.r.t. model_values.

Assumes Gaussian uncertainties on the observed indices.

property n_indices: int

Number of spectral indices.

Returns:

Number of indices in this dataset.

Return type:

int

Notes

Computed from the length of the index_defs tuple. Constant for the lifetime of the object (immutable).

property names: tuple[str, ...]

Tuple of spectral index names.

Returns:

Index names in the same order as index_defs, e.g. ("Dn4000", "HdA").

Return type:

tuple[str, …]

Notes

Names match the keys in STANDARD_INDICES.

Examples

>>> from tengri import SpectralIndexData
>>> sid = SpectralIndexData.from_names(["Dn4000", "HdA"], [1.3, 5.1], [0.05, 0.3])
>>> sid.names
('Dn4000', 'HdA')
summary() → str[source]

Return a human-readable summary of the spectral indices.

Returns:

Summary string (e.g., "2 indices (Dn4000, HdA)").

Return type:

str

Notes

Intended for logging and diagnostics, not for programmatic parsing.

values: Array
property wave_range: tuple[float, float]

Rest-frame wavelength range needed to measure all indices.

Returns:

Tuple (wave_min, wave_max) [Angstrom] covering all continuum and feature windows across all indices.

Return type:

tuple[float, float]

Notes

Useful for determining minimum wavelength coverage required in the forward model spectrum to compute all indices.

Two catalogs ship with tengri, keyed by index name, so most work needs no hand-built definition — look the name up rather than redefining passbands.

tengri.observation.spectral_indices.STANDARD_INDICES

Catalog of the 13 single-passband spectral indices tengri ships, keyed by index name. Three kinds are represented: break ratios (Dn4000, D4000), Lick-style equivalent widths (HdA, HdF, HgA, HgF, Hbeta, Mgb, Fe4383, Fe5270, Fe5335, Ca4227), and one continuum slope (uv_slope_beta). The Lick equivalent widths use the Lick pseudo-continuum (see SpectralIndexDef.pseudo_continuum). Values are SpectralIndexDef records carrying the passband definitions in rest-frame vacuum Angstrom: the Lick windows (_LICK_AIR_WINDOWS) and the 4000 A break windows (tengri.utils.break_windows) are published in air and converted once at import; the UV slope range (Calzetti+1994, 1250-2600 A, measured on space-based IUE spectra) is vacuum. Pass a key to tengri.measure.spectral_index() or tengri.measure_index_jax().

tengri.observation.spectral_indices.STANDARD_COMPOSITE_INDICES

Catalog of the four composite indices tengri ships, keyed by index name. Each combines two or three entries of STANDARD_INDICES into the standard abundance- and age-tracer combinations: [MgFe]' and <Fe> for metallicity, HdA+HgA and HdF+HgF for the Balmer age diagnostics. Values are CompositeIndexDef records.

tengri.measure.spectral_index() is the exploratory surface; measure_index_jax is the JIT/vmap-safe one used inside inference. Both take a rest-frame wavelength axis and a flux density per unit frequency (\(L_\nu\) or \(F_\nu\); pass an \(F_\lambda\) spectrum as flux_lambda * wave_rest**2).

Lick equivalent widths follow Trager et al. (1998, ApJS 116, 1, Eqs. 1-3): the flux is converted to \(F_\lambda\) inside the operator and the pseudo-continuum is the straight line through the mean \(F_\lambda\) of the two sidebands at the sideband mid-wavelengths. Break indices (Dn4000, D4000) are ratios of \(F_\nu\) window means. The pseudo_continuum="mean" option of SpectralIndexDef selects the constant mean-of-sidebands arithmetic of bagpipes.input.spectral_indices.single_index for comparison with BAGPIPES; it is not the Lick definition.

tengri.measure_index_jax(wave_rest: Array, flux: Array, index_def: SpectralIndexDef | CompositeIndexDef, edge_width: float = 0.0) → Array[source]

Measure a spectral index on a rest-frame spectrum.

Parameters:
  • wave_rest (ndarray, shape (n_pix,)) – Rest-frame wavelengths [Angstrom]. Must cover all windows defined in index_def.

  • flux (ndarray, shape (n_pix,)) – Flux density per unit frequency, \(L_\nu\) or \(F_\nu\) (any consistent units; only ratios matter, so no distance is needed). EW and magnitude indices convert it to \(F_\lambda \propto F_\nu/\lambda^2\) internally (Lick definition); break indices use it as given (ratio of \(F_\nu\) window means); a slope index fits it as \(F_\nu\). A spectrum in \(F_\lambda\) is passed as flux_lambda * wave_rest**2. An index defined with pseudo_continuum="mean" measures flux as given, in any frame.

  • index_def (SpectralIndexDef or CompositeIndexDef) – Atomic index (EW or break) or a composite that combines several atomic measurements via a user-provided function.

  • edge_width (float, default 0.0) – Window-edge softening [Å]. 0 (default) integrates over exactly the catalog bounds, the Worthey et al. (1994) and Balogh et al. (1999) definition. A positive value opts into sigmoid edges of that width, which make the measurement a smooth function of the pixel-to-window assignment (needed only if the rest-frame grid itself moves under the gradient, e.g. a free redshift) at the price of a 0.01-0.1 Å bias in a Lick EW.

Returns:

Measured index value (scalar). Units per index_def.units: [Angstrom] for EW; [dimensionless] for break and slope (beta) indices.

Return type:

ndarray, shape ()

Notes

JIT-compatible: yes.

Gradient-safe: yes, differentiable w.r.t. flux. Window edges are hard: a window mean is the exact integral of the piecewise-linear interpolant of the spectrum over \([\lambda_{\rm lo}, \lambda_{\rm hi}]\), with the partial pixel at each edge weighted by the overlap. That integral is linear in the flux, so the flux gradient is exact and needs no smoothing. The edges are catalog constants, not parameters, so no gradient is taken through them.

An EW index integrates \(1 - F_\lambda/F_{C\lambda}\) over the feature window (node weights \(w_p\), \(\sum_p w_p = W\) the window width): W (1 - <F/F_C>_w).

Filter convention

class tengri.FilterConvention(*values)[source]

Bases: StrEnum

Broadband filter-convolution convention (the bandpass weight).

The band-averaged flux density is

\[\langle F_\nu\rangle = \frac{\int F_\nu(\lambda)\,T(\lambda)\,w(\lambda)\,d\lambda} {\int T(\lambda)\,w(\lambda)\,d\lambda},\]

and the member selects the weight \(w(\lambda)\):

  • BESSELL: photon-counting, \(w = 1/\lambda\). The physically correct mean for photon-counting detectors (all optical/NIR CCDs) and how the AB system is realized by surveys. Matches DSPS, FSPS, sedpy, Prospector, Synthesizer, and BAGPIPES. This is the default.

  • ENERGY: energy-counting, \(w = 1/\lambda^2\) (i.e. flat in frequency, \(\int F_\nu T\,d\nu / \int T\,d\nu\)). Matches CIGALE for its energy-type filters (e.g. 2MASS, WISE, SPIRE); CIGALE’s photon-type filters (e.g. SDSS, JWST) follow BESSELL. Use it when reproducing those energy-type bands.

The two agree exactly for a flat-\(F_\nu\) source (the AB reference) and diverge by 5–40 mmag, band- and SED-slope-dependent, otherwise.

References

[tengri.FilterConvention-1]

Hogg, Baldry, Blanton & Eisenstein 2002, “The K correction”, arXiv:astro-ph/0210394, Eq. 5 (photon-counting AB definition).

[tengri.FilterConvention-2]

Fukugita et al. 1996, AJ 111, 1748, Eq. 7 (FSPS’s cited form).

[tengri.FilterConvention-3]

Hearin et al. 2023, “DSPS”, arXiv:2112.06830 (rest-frame mag, \(w = 1/\lambda\), \(T_Q\) = photon transmission probability).

[tengri.FilterConvention-4]

Boquien et al. 2019, A&A 622, A103 (CIGALE energy convention).

See also

list_filter_conventions

Names + descriptions of the supported conventions.

BESSELL = 'bessell'
ENERGY = 'energy'

Filter curve

class tengri.FilterCurve(wave: Array, trans: Array, name: str = '')[source]

Bases: object

Photometric filter transmission curve.

Represents a single broad-band photometric filter via its wavelength-dependent transmission profile. Used to convolve SEDs and compute observed flux densities.

Variables:
  • wave (array, shape (n_wave,)) – Wavelength grid [Ångstrom]. Should be at least 10 points spanning the transmission curve from near zero to near zero.

  • trans (array, shape (n_wave,)) – Transmission at each wavelength (dimensionless, 0.0–1.0). Typically peaked at 1.0 and falls to 0 at the filter edges.

  • name (str, optional) – Filter identifier (e.g., "sdss_r", "jwst_f200w", "hsc_i"). Used for diagnostic output and filter registry lookups. Default empty string.

Notes

Standard sources:

  • Optical/NIR: Spanish Virtual Observatory (SVO) Filter Profile Service

  • JWST: STScI filter definitions (via astropy.io.fits)

  • Custom: User-provided arrays

Filter conventions:

  • Transmission is not flux-normalized (raw instrumental response)

  • Wavelength grid should be uniform or fine enough to resolve structure

  • Outside [wave[0], wave[-1]], transmission is assumed zero

See also

load_filter_set

Load filter set from SVO database.

compute_flux_density

Convolve SED through this filter.

pad_filters

Stack variable-length filter arrays.

cache_key() → tuple[source]

Return a hashable cache key for this filter curve.

Returns:

Cache key derived from wave, trans, and name.

Return type:

tuple

Notes

All attributes are included by content.

name: str = ''
trans: Array
wave: Array

Noise model

class tengri.NoiseModel(calibration_floor: float | Distribution | Array = 0.0, student_t_dof: float | None = None)[source]

Bases: object

Noise model configuration.

Parameters:
  • calibration_floor (float, Distribution, or array) – Fractional calibration floor added in quadrature with observational noise: sigma_eff = sqrt(sigma_obs^2 + (f_cal * model)^2). A float value becomes Fixed(value); a Distribution (e.g. Uniform(0.01, 0.15)) makes it a free parameter during inference. An array (shape (n_filters,)) specifies a per-band fixed floor; arrays of Distributions are not supported. Default: 0.0 (no calibration floor).

  • student_t_dof (float or None) – Degrees of freedom for a Student-t likelihood (heavier tails for outlier robustness). None uses a standard Gaussian likelihood. With marginalized calibration or marginalized emission lines the nuisance coefficients cannot be integrated out in closed form under Student-t noise; the marginal is then a Laplace approximation at the iteratively reweighted least-squares mode (within 0.46 nat of numerical integration for independent noise and 0.03 nat for a pixel covariance in the cases measured, one or two coefficients and 3 to 30 degrees of freedom; see marginalize_linear_nuisance()). Default: None.

Returns:

Noise model instance with configuration validated.

Return type:

NoiseModel

Variables:
  • calibration_floor (float, Distribution, or array) – Fractional calibration uncertainty floor.

  • student_t_dof (float or None) – Student-t degrees of freedom (or None for Gaussian).

Notes

Immutable container: A frozen dataclass. Fields are read-only by convention.

A frozen dataclass encapsulating noise model configuration. Replaces the older pattern of manually creating noise_frac_cal and noise_dof parameters. Primarily used to register observation-level hyperparameters with the inference engine.

Examples

>>> from tengri import NoiseModel, Uniform
>>> nm = NoiseModel(calibration_floor=Uniform(0.01, 0.1))
>>> list(nm.get_params().keys())
['noise_frac_cal']
cache_key() → tuple[source]

Return a hashable cache key for this noise model.

Returns:

Cache key derived from calibration floor and Student-t degrees of freedom.

Return type:

tuple

Notes

Both fields are included by content as they define the likelihood function.

calibration_floor: float | Distribution | Array = 0.0
get_params() → dict[str, object][source]

Return Parameters entries for the noise model.

Returns:

Mapping of parameter names ("noise_frac_cal", "noise_dof") to Distribution objects. Empty dict if no noise parameters are needed. Per-band array floors are fixed and not added as parameters.

Return type:

dict[str, Distribution]

Notes

Called by Observation.get_all_params() to register noise model hyperparameters with the inference engine. Parameters are only included if they are non-trivial (calibration floor > 0 or Student-t dof is not None). Array calibration floors are fixed and not added as free parameters.

student_t_dof: float | None = None
summary() → str[source]

Return a one-line summary of the noise configuration.

Returns:

Single-line summary string with calibration floor and likelihood settings (e.g., "cal floor=0.05 (fixed), Student-t dof=10").

Return type:

str

Notes

Used for logging and diagnostics. Returns "Gaussian (default)" if no custom noise settings are configured.

validate_array_length(n_filters: int) → None[source]

Validate that array calibration_floor matches the number of filters.

Parameters:

n_filters (int) – Expected number of filters.

Raises:

ValueError – If calibration_floor is an array with length != n_filters.

VI config

class tengri.VIConfig(n_samples: int | Callable = 3, n_iterations: int = 10, use_vmap: bool = True, evi_linear_fraction: float = 0.5, draw_linear_kwargs: dict = <factory>, nonlinearly_update_kwargs: dict = <factory>, kl_kwargs: dict = <factory>)[source]

Bases: object

Configuration for geoVI/MGVI/EVI optimize_kl calls.

Parameters:
  • n_samples (int or callable) – Samples per KL iteration. mirror_samples=True (default in NIFTy) doubles this internally, so 3 → 6 effective samples.

  • n_iterations (int) – Number of KL minimization iterations.

  • use_vmap (bool) – Use jax.vmap for residual_map (faster, slightly more memory).

  • evi_linear_fraction (float) – Fraction of iterations using linear_resample before switching to nonlinear_resample in EVI mode.

  • draw_linear_kwargs (dict) – Kwargs for the CG solver that generates each sample.

  • nonlinearly_update_kwargs (dict) – Kwargs for the Newton-CG that inverts the coordinate transform.

  • kl_kwargs (dict) – Kwargs for the outer KL minimization.

Variables:
  • n_samples (int or callable) – Samples per KL iteration (doubled by NIFTy’s mirror_samples).

  • n_iterations (int) – Number of KL minimization iterations.

  • use_vmap (bool) – Whether to use jax.vmap for residual mapping.

  • evi_linear_fraction (float) – Fraction of iterations to use linear (MGVI) before nonlinear (geoVI).

  • draw_linear_kwargs (dict) – Conjugate gradient solver configuration for sampling.

  • nonlinearly_update_kwargs (dict) – Newton-CG configuration for coordinate transform inversion.

  • kl_kwargs (dict) – Outer KL minimization configuration.

Notes

Frozen dataclass configuring the variational inference backend. Key fields: method selects the VI algorithm. 'vi' (NIFTy geoVI) and 'vi_linear' (NIFTy MGVI) are the working paths.

The pure-JAX native_vi_nonlinear / native_vi_linear backends are registered tier="broken" (#1287), they segfault on DPL/dense_basis photometry mocks, and 'vi_native' was never a registered name at all; it raises KeyError. The “~19x faster” figure once quoted here was withdrawn: it compared MGVI against geoVI, not native against NIFTy.

Examples

>>> from tengri import VIConfig
>>> cfg = VIConfig(n_samples=4, n_iterations=50)
>>> cfg.n_samples
4
draw_linear_kwargs: dict
evi_linear_fraction: float = 0.5
kl_kwargs: dict
n_iterations: int = 10
n_samples: int | Callable = 3
nonlinearly_update_kwargs: dict
use_vmap: bool = True

Exceptions

Every exception tengri raises derives from TengriError, so except TengriError catches all of them. Each also inherits the built-in that matches its failure mode — ParameterError is a ValueError, TengriIOError an OSError — so existing except ValueError handlers keep working.

exception tengri.TengriError[source]

Bases: Exception

Base exception for all Tengri errors.

Parameters:

message (str) – Human-readable error description.

exception tengri.ParameterError[source]

Bases: TengriError, ValueError

Invalid parameter names, values, or conflicts.

Parameters:

message (str) – Human-readable error description.

exception tengri.ConfigError[source]

Bases: TengriError, ValueError

Invalid Config construction or missing fields.

Parameters:

message (str) – Human-readable error description.

exception tengri.BackendError[source]

Bases: TengriError, RuntimeError

Backend initialization or computation failure.

Parameters:

message (str) – Human-readable error description.

exception tengri.InferenceError[source]

Bases: TengriError, RuntimeError

Sampler/optimizer failures (convergence, NaN, etc.).

Parameters:

message (str) – Human-readable error description.

exception tengri.DeadFitError(message: str, *, warmup_divergence_frac: float = nan, sampling_divergence_frac: float = nan, step_size: float = nan)[source]

Bases: InferenceError

MCMC fit divergence detected; sampling halted (#2088, #2093).

Raised at two points in the MCMC pipeline:

  1. Pre-hoc (warmup-time, #2088): The final window of warmup ends with essentially every transition divergent (DEAD_WARMUP_DIVERGENCE_FRAC threshold, 0.9). A 4-chain NUTS fit whose every one of 2400 transitions diverged spent 227 s in warmup and another 237 s sampling before DeadFitWarning could name the failure. The warmup’s own divergence record already held the verdict, so window-adaptation backends (NUTS, HMC, dynamic HMC) now read the final window of that record and refuse to sample. The adaptation is not cached, so the next call re-tunes.

  2. Post-hoc (sampling-time, #2093): Sampling completed but every kept draw diverged (DEAD_SAMPLING_DIVERGENCE_FRAC threshold, 0.9). A fit that survived warmup but sampled a frozen posterior is logged explicitly instead of silently: the cost was paid, but the result is uninformative.

Raises rather than warns: there is nothing to return. A sampler that rejects every proposal produces a frozen posterior, and the measured cause is the data, not the tuning (fluxes 1000x too faint from a wrong AB zero point pushed the stellar mass to its prior edge, where the bounded transform runs to infinity).

Variables:
  • warmup_divergence_frac (float) – Divergent fraction over the final warmup window (pre-hoc trigger). NaN if triggered post-hoc.

  • sampling_divergence_frac (float) – Divergent fraction over all post-burnin draws (post-hoc trigger). NaN if triggered pre-hoc.

  • step_size (float) – The adapted step size at the end of warmup (pre-hoc) or sampling (post-hoc).

exception tengri.TengriIOError[source]

Bases: TengriError, OSError

File I/O, missing data files, format mismatch.

Parameters:

message (str) – Human-readable error description.