Cross-component contract¶
Tengri’s forward model is built from a list of SEDComponent
adapters. Each component declares — at construction time, in pure
metadata — the named cross-component quantities it publishes into
PipelineState.derived and the keys it requires from upstream
producers. The orchestrator validates this contract once at
tengri.forward.build_components() time, before any JIT trace,
catching renames, units drift, missing publishers, duplicate
publishers, and out-of-order dependencies.
See docs/dev/component_architecture.md for a tutorial; this page is
the API reference for the types involved.
Derived-data types¶
DerivedKey¶
- class tengri.DerivedKey(name: str, units: str, description: str = '')[source]¶
Bases:
NamedTupleOne cross-component datum published into
ForwardState.derived.Returned in a tuple from
SEDComponent.outputs()andSEDComponent.inputs(). Consumed once at pipeline construction bytengri.forward.orchestrator.validate_pipeline()to ensure every required key has an upstream producer with matching units, and (when needed) to derive a topological ordering over components.Mirrors
ParamDeclarationline-for-line so future readers see the same shape on both sides of the cross-component contract.Fields¶
- namestr
Stable key written to / read from
ForwardState.derived. Compared by string equality, so renames are caught at construction.- unitsstr
Free-form units tag, e.g.
"erg/s","Msun/yr","dex","erg/s/Hz","yr","photons/s". The validator compares publisher and consumer units strings for equality; the_CANONICAL_UNITStable intengri.forward.orchestratorpins the expected string for every well-known key. Use""for unitless quantities (e.g. transmission factors, mass weights, attenuation factors).- descriptionstr
One-line human-readable description shown in error messages and by future introspection helpers. Optional.
Notes
No numeric unit conversion is attempted by the validator: the contract refuses to silently paper over a unit disagreement, but it will not convert
"Lsun"to"erg/s"for the consumer. Each component is responsible for converting at its own boundary.The strings are deliberately not
astropy.unitsquantities; that path is JIT-incompatible and would cost a 5–100× performance hit on the hot pipeline. Stringly-typed-with-a-canonical-table is enough to catch the realistic failure modes (L_SUN vs L_SUN_CUE confusion,"Lsun"vs"erg/s"cross-talk).
DerivedState¶
- class tengri.protocols.DerivedState(log_mstar: Array | None = None, log_mstar_formed: Array | None = None, log_mstar_surviving: Array | None = None, sfr: Array | None = None, sfr_10myr: Array | None = None, sfr_100myr: Array | None = None, L_age: Array | None = None, log_L_age: Array | None = None, lnu_age: Array | None = None, lnu_interval: Array | None = None, joint_weights: Array | None = None, met_exact_joint: Array | None = None, met_exact_z: Array | None = None, met_exact_lgmet: Array | None = None, log_stellar_mass_scale: Array | None = None, stellar_alpha_bracket_index: Array | None = None, stellar_alpha_bracket_fraction: Array | None = None, ssp_ages_yr: Array | None = None, age_weights: Array | None = None, age_weights_surviving: Array | None = None, nion: Array | None = None, log_nion: Array | None = None, log_L_lyc_age: Array | None = None, lnu_age_ion: Array | None = None, ssp_wave_ion: Array | None = None, sfh_grid_lbt_yr: Array | None = None, sfh_timing_gyr: dict[str, ~typing.Any] | None=None, sfr_history: Array | None = None, log_metallicity_history: Array | None = None, stellar_phot_lnu_precomp: Array | None = None, stellar_phot_moment_precomp: Array | None = None, stellar_phot_lnu_per_age_precomp: Array | None = None, stellar_phot_moment_per_age_precomp: Array | None = None, stellar_phot_lnu_precomp_lyc: Array | None = None, stellar_phot_lnu_per_age_precomp_lyc: Array | None = None, stellar_phot_lnu_precomp_nolyc: Array | None = None, stellar_phot_lnu_per_age_precomp_nolyc: Array | None = None, stellar_phot_lnu_per_age_subband_precomp: Array | None = None, stellar_subband_waves_rest_precomp: Array | None = None, stellar_subband_waves_rest_igm_precomp: Array | None = None, stellar_subband_lyc_factor_precomp: Array | None = None, stellar_phot_lnu_per_age_subband_igm_precomp: Array | None = None, stellar_restband_lnu_precomp: Array | None = None, nebular_restband_lnu_precomp: Array | None = None, shock_restband_lnu_precomp: Array | None = None, agn_restband_lnu_precomp: Array | None = None, radio_restband_lnu_precomp: Array | None = None, xray_restband_lnu_precomp: Array | None = None, dust_emission_restband_lnu_precomp: Array | None = None, stellar_restband_lnu_per_age_subband_precomp: Array | None = None, stellar_restband_subband_waves_precomp: Array | None = None, filter_restband_eff_waves: Array | None = None, dust_restband_attenuation_precomp: Array | None = None, dust_bc_restband_attenuation_precomp: Array | None = None, dust_diff_restband_attenuation_precomp: Array | None = None, dust_restband_attenuation_subband_precomp: Array | None = None, dust_bc_restband_attenuation_subband_precomp: Array | None = None, dust_diff_restband_attenuation_subband_precomp: Array | None = None, L_ir: Array | None = None, L_absorbed: Array | None = None, log_L_ir: Array | None = None, log_L_absorbed: Array | None = None, log_L_lyc_dust: Array | None = None, log_L_lyc: Array | None = None, dust_attenuation_factor: Array | None = None, dust_diff_transmission: Array | None = None, sed_dust_attenuated: Array | None = None, sed_dust_ir: Array | None = None, L_ir_emission: Array | None = None, log_L_ir_emergent: Array | None = None, dust_umean: Array | None = None, dust_attenuation_precomp: Array | None = None, dust_attenuation_slope_precomp: Array | None = None, dust_bc_attenuation_precomp: Array | None = None, dust_bc_attenuation_slope_precomp: Array | None = None, dust_diff_attenuation_precomp: Array | None = None, dust_diff_attenuation_slope_precomp: Array | None = None, dust_hole_attenuation_precomp: Array | None = None, dust_ionizing_flag_precomp: Array | None = None, dust_bc_attenuation_subband_precomp: Array | None = None, dust_diff_attenuation_subband_precomp: Array | None = None, dust_hole_attenuation_subband_precomp: Array | None = None, dust_ionizing_flag_subband_precomp: Array | None = None, dust_attenuation_subband_precomp: Array | None = None, dust_bc_attenuation_subband_igm_precomp: Array | None = None, dust_diff_attenuation_subband_igm_precomp: Array | None = None, dust_attenuation_subband_igm_precomp: Array | None = None, dust_bc_log_attenuation_slope_precomp: Array | None = None, dust_diff_log_attenuation_slope_precomp: Array | None = None, dust_young_indicator: Array | None = None, dust_young_lyc_gate_subband_precomp: Array | None = None, dust_spec_neb_transmission_precomp: Array | None = None, age_boundary_younger_fraction: Array | None = None, filter_eff_waves: Array | None = None, phot_filter_waves_padded: Array | None = None, phot_filter_trans_padded: Array | None = None, phot_band_spec: Any | None = None, spec_eff_waves: Array | None = None, spec_sigma_v_kms: Array | None = None, L_agn_bol: Array | None = None, log_L_agn_bol: Array | None = None, agn_torus_frac_effective: Array | None = None, agn_ir_frac_saturated: Array | None = None, log_agn_ir_frac_window_host: Array | None = None, log_L_agn_direct_los: Array | None = None, log_L_agn_disc: Array | None = None, log_L_agn_disc_los: Array | None = None, log_L_agn_torus: Array | None = None, log_L_agn_torus_los: Array | None = None, log_L_agn_polar_dust: Array | None = None, log_L_agn_polar_dust_los: Array | None = None, log_L_agn_absorbed: Array | None = None, log_L_agn_bol_ionizing: Array | None = None, agn_adaf_mdot: Array | None = None, log_L_agn_adaf_accretion: Array | None = None, L_agn_bol_lsun: Array | None = None, L_agn_direct_los_lsun: Array | None = None, L_agn_disc_lsun: Array | None = None, L_agn_disc_los_lsun: Array | None = None, L_agn_torus_lsun: Array | None = None, L_agn_torus_los_lsun: Array | None = None, L_agn_polar_dust_lsun: Array | None = None, L_agn_polar_dust_los_lsun: Array | None = None, L_agn_absorbed_lsun: Array | None = None, L_agn_bol_ionizing_lsun: Array | None = None, L_agn_adaf_accretion_lsun: Array | None = None, L_2500_intrinsic: Array | None = None, L_4400_intrinsic: Array | None = None, log_L_12um: Array | None = None, log_L_6um: Array | None = None, agn_cos_inc: Array | None = None, sed_agn: Array | None = None, sed_agn_disc: Array | None = None, sed_agn_torus: Array | None = None, sed_agn_lines: Array | None = None, sed_agn_lines_attenuated: Array | None = None, sed_agn_polar: Array | None = None, sed_grahsp: Array | None = None, agn_phot_lnu_precomp: Array | None = None, sed_nebular: Array | None = None, nebular_line_frac: Array | None = None, sed_shock: Array | None = None, line_waves: Array | None = None, line_lums: Array | None = None, log_line_lums: Array | None = None, log_line_lums_attenuated: Array | None = None, lyc_transmission: Array | None = None, lyc_fdust: Array | None = None, lyc_fesc: Array | None = None, nebular_phot_lnu_precomp: Array | None = None, nebular_phot_lnu_lines_precomp: Array | None = None, nebular_phot_lnu_cont_precomp: Array | None = None, nebular_line_phot_waves_rest: Array | None = None, nebular_phot_lnu_attenuated_precomp: Array | None = None, nebular_restband_lnu_attenuated_precomp: Array | None = None, nebular_phot_lnu_subband_precomp: Array | None = None, nebular_subband_waves_rest_precomp: Array | None = None, nebular_phot_lnu_subband_screened_precomp: Array | None = None, nebular_restband_lnu_subband_precomp: Array | None = None, nebular_restband_subband_waves_precomp: Array | None = None, nebular_eb_absorbed_per_qh_grid_precomp: Array | None = None, shock_phot_lnu_precomp: Array | None = None, dust_emission_phot_lnu_precomp: Array | None = None, radio_phot_lnu_precomp: Array | None = None, xray_phot_lnu_precomp: Array | None = None, shock_phot_lnu_attenuated_precomp: Array | None = None, agn_phot_lnu_attenuated_precomp: Array | None = None, sed_nebular_attenuated_precomp: Array | None = None, sed_shock_attenuated_precomp: Array | None = None, sed_agn_attenuated_precomp: Array | None = None, stellar_spec_lnu_precomp: Array | None = None, nebular_spec_lnu_precomp: Array | None = None, dust_spec_lnu_precomp: Array | None = None, dust_emission_spec_lnu_precomp: Array | None = None, radio_spec_lnu_precomp: Array | None = None, xray_spec_lnu_precomp: Array | None = None, agn_spec_lnu_precomp: Array | None = None, igm_spec_transmission_precomp: Array | None = None, stellar_spec_lnu_per_age_precomp: Array | None = None, dust_spec_transmission_precomp: Array | None = None, dust_spec_bc_transmission_precomp: Array | None = None, dust_spec_diff_transmission_precomp: Array | None = None, sed_radio: Array | None = None, radio_L_ir_input: Array | None = None, radio_log_L_ir_input: Array | None = None, sed_xray: Array | None = None, log_L_x_xrb_2_10: Array | None = None, log_L_x_agn_2_10: Array | None = None, log_L_x_hmxb_2_10: Array | None = None, log_L_x_lmxb_2_10: Array | None = None, log_L_x_hotgas_0p5_2: Array | None = None, log_L_x_agn_total: Array | None = None, log_Lnu_2keV_30deg: Array | None = None, igm_transmission: Array | None = None, foreground_transmission: Array | None = None, igm_phot_factor: Array | None = None, igm_spec_factor: Array | None = None, igm_rest_transmission_precomp: Array | None = None, igm_reach_filters_precomp: Array | None = None, shock_log_lhalpha: Array | None = None, neb_log_no: Array | None = None, spatial_profile_2d: Array | None = None, spatial_grid_xy_kpc: Any = None, _extras: dict[str, ~typing.Any]=<factory>)[source]¶
Bases:
objectTyped container for cross-component derived data.
Fields mirror
tengri.forward.orchestrator._CANONICAL_UNITSone-for-one; every canonical derived key has a field with the same name.Nonemeans “not populated by any upstream component”.Mutation via
with_()(the same patterntengri.protocols.ForwardStateuses); never assign in place because the dataclass is frozen.Dict compatibility¶
All of these work, returning
True/ the value / iterating non-None fields exactly as a plaindictwould:"L_ir" in bundle bundle["L_ir"] bundle.get("L_ir", 0.0) bundle.keys() bundle.items() bundle.values() list(bundle) len(bundle)
JAX pytree¶
Registered with
jax.tree_util.register_dataclass()so the bundle can ride throughjax.lax.scan/jax.tree_mapalong with the rest ofForwardState. Every field is a data field: JAX traces each one.Nonedefaults are static at trace time; switching which fields are populated invalidates the JIT cache, which is acceptable because a giventengri.SEDModelpins its component list at construction and never reshuffles.- L_ir_emission: Array | None = None¶
Bolometric IR luminosity from dust emission component [erg/s]. Published by dust-emission components that close the energy balance.
- age_weights_surviving: Array | None = None¶
age_weightstimes each node’s mass-remaining fraction, summed over metallicity. Sums to10**log_mstar. Fragos+2013’s LMXB age is the mass-weighted age of the population’s current stars, so the X-ray component weights by this.- Type:
Surviving mass per SSP age bin [Msun], shape (n_age,)
- dust_attenuation_subband_precomp: Array | None = None¶
Single-screen counterpart, shape
(n_age, n_filter, n_subbands).
- dust_diff_transmission: Array | None = None¶
T(λ) on the full state.wave grid, evaluated by the dust attenuator. Published by all dust-attenuation models for use by dust-emission components when diffuse_screen=True.
- Type:
Full-grid diffuse dust transmission (dimensionless)
- dust_hole_attenuation_precomp: Array | None = None¶
T_hole(λ_eff) (absent -> the pre-#2529 ‘screened’ formula above is used unchanged) and the pivot’s ionizing flag, shape
(n_filter,)each. Seeobservation.predict_via_precomp’s combine andDustSEDComponent.apply’s publish.- Type:
#2529 hole geometry at the filter pivot
- dust_hole_attenuation_subband_precomp: Array | None = None¶
#2529 hole geometry, exact-node equivalent of the two fields above, shape
(n_filter, n_subbands)each.
- dust_restband_attenuation_precomp: Array | None = None¶
at its pivot, and at its quadrature nodes. Separate from the observed-band screens because the two bands sample different rest wavelengths.
- Type:
The dust screen evaluated on the rest band
- dust_umean: Array | None = None¶
Mean starlight intensity <U> of a Draine & Li dust model [dimensionless]:
U_min [(1 - gamma) + gamma R](CIGALEdust.umean). Published bydraine_li2007anddraine_li2014.
- classmethod field_names() tuple[str, ...][source]¶
Tuple of every typed-field name (excludes
_extras).
- filter_restband_eff_waves: Array | None = None¶
the filter’s own pivot, since the projection is at z=0 [Angstrom]. Contrast
filter_eff_waves= pivot/(1+z), the rest wavelength the OBSERVED band samples.- Type:
The wavelength the rest band samples
- classmethod from_dict(d: dict[str, Any], *, allow_extras: bool = False) DerivedState[source]¶
Build a bundle from a plain dict.
Strict by default: when
allow_extras=False, keys outside the typed set raiseTypeErrorwith a Levenshtein-2 “Did you mean: …” hint. Production write paths (ForwardState.__post_init__(),ForwardState.with_()) rely on this strictness to catch typos at trace time.Pass
allow_extras=Trueto spill unknown keys into_extras(still readable via mapping syntax). Used by the legacy-compat tests; not used by production code.
- lnu_age_ion: Array | None = None¶
Per-age, per-Msun ionizing-wavelength L_nu slice [erg/s/Hz/Msun], shape (n_age, n_ion_bins): the UNREDUCED cube
log_L_lyc_age(andlog_nion) are peak-factored integrals of. Paired withssp_wave_ion(the matching wavelength axis). Published so a weighted per-age LyC credit can be computed via the cheap combine-then-integrate identity in thelog_L_lyc_agedocstring above, instead of reducinglog_L_lyc_ageper age.
- lnu_interval: Array | None = None¶
Per-age-interval L_nu [erg/s/Hz], shape (n_interval, n_wave):
sum_a F_j(a) lnu_age(a)for the stellar component’sage_boundaries_yr(F_jfromage_boundary_younger_fraction). Published only when an attenuator asks for its grouped age mixture (StellarSEDComponentConfig.publish_interval_spectra).
- log_L_absorbed: Array | None = None¶
the ABSORBED stellar+nebular energy budget, independent of
dust_eta_balanceand of a declareddust_log_L_iroverride – unlikelog_L_ir(the re-emitted budget), this key never moves. Split out of thelog_L_irpublisher (#1837/#2187-series): three readers (AGN torus coupling,pred.l_dust_absorbedviacomponent_factory.pyandstellar/component.py) want ABSORBED energy specifically and were readinglog_L_iras a stand-in, which is only correct when eta == 1 and no override is declared.- Type:
log10(L_absorbed / (erg/s)) [dex]
- log_L_age: Array | None = None¶
float32-safe companion to
L_age(#1534).L_ageis ~1e42-1e46 erg/s and reads asinfin pure float32;-infhere means a bin genuinely emits nothing,+infthat the input was corrupt (#1527).
- log_L_ir: Array | None = None¶
the float32-safe form of
L_ir, which is ~1e43 and therefore outside the float32 range entirely (#1206).- Type:
log10(L_ir / (erg/s)) [dex]
- log_L_ir_emergent: Array | None = None¶
the IR luminosity escaping the diffuse dust screen after single-pass attenuation (diffuse_screen=True only). When diffuse_screen is off, this key is absent (not published).
- Type:
log10(L_ir_emergent / (erg/s)) [dex]
- log_L_lyc: Array | None = None¶
the RAW (pre-fesc, pre-fdust) Lyman-continuum luminosity of the whole stellar population (#2539 item 3). Published alongside
lyc_fdustso a dust component can creditf_dust * L_LyCintolog_L_absorbedvia the smooth (log1p-based) combine inenergy_balance.log10_add_fdust_creditinstead oflog10_add``ing the already-``fdust-multipliedlog_L_lyc_dust(whose own gradient is deliberately clamped to zero atf_dust == 0, which would zero the combined gradient too even thoughL_absorbedis linear infdust). Published only when a stellar SED is present.- Type:
log10(L_LyC / (erg/s)) [dex]
- log_L_lyc_age: Array | None = None¶
Per-age ionizing luminosity [erg/s], shape (n_age,). Computed from the ionizing-wavelength slice (λ < LYMAN_LIMIT_AA × 2) via the same Q_H pathway. Published for nebular and dust components to compute LyC credits without materializing the full stellar SED (FeaturePrecomp guards G1/G2). Combined via
log10_age_sum_lycto yield whole- populationlog_L_lycand per-age variants.A per-age weighted credit (e.g. the young/birth-cloud-only share two_component’s
lyc_reprocessed_by='young'needs) should NOT reduce THIS array withlog10_age_sum_lyc(log_L_lyc_age, weights=...): that pays for peak-factoring and the edge-aware quadrature once PER AGE, which a #1748/#1770-class FLOP guard (G1/G2) measured as the dominant cost of the WavePrecomp fit path (~5x the cost of the alternative below, bit-identical to float64 round-off, sinceedge_trapezoid()is linear in its input for fixed wave/edge). Weight-and-sumlnu_age_ionFIRST (a cheap O(n_age x n_ion) linear combine) and calllog10_lyc_luminosity()ONCE on the resulting single slice instead; this field stays published, correct, and available for direct per-age inspection (e.g. diagnostics, tests), and is simply pruned as dead code by XLA when nothing reads it this way.
- log_L_lyc_dust: Array | None = None¶
the Lyman-continuum energy absorbed by dust inside HII regions (the absolute f_dust share,
lyc_shares(neb_fesc, neb_fdust_frac)[1], #2436), not credited to nebular emission but to dust heating. Added tolog_L_absorbedby dust components (#2539). Published only when f_dust > 0.- Type:
log10(L_LyC_dust / (erg/s)) [dex]
- log_line_lums: Array | None = None¶
float32-safe companion to
line_lums(#1534); ~1e41 erg/s isinfin pure float32. Same sentinel convention aslog_L_age.
- log_line_lums_attenuated: Array | None = None¶
log_line_lumsafter the dust screen, published by whichever dust component ran, with the same law/params/clip it applies to the nebular continuum (#1867).Nonewhen no dust component ran, and consumers then fall back to the intrinsiclog_line_lums: the correct answer in that case.A typed field rather than an
_extrasentry deliberately: both public line surfaces (pred.lines.*andpredict_properties) resolve through it, and #1867 was exactly a reddened catalog going somewhere nothing read. A typed field is greppable and checkable; an untyped extra would reproduce the failure mode.
- log_stellar_mass_scale: Array | None = None¶
log10(total_mass x L_sun) [dex]. The linear erg/s scale is ~1e43 for a 1e10 Msun galaxy and overflows float32 for any galaxy above ~9e4 Msun, so only the log form is published (#1206, #3149).
- lyc_fdust: Array | None = None¶
Absolute HII-region dust-absorption share (#2539 item 2),
lyc_shares(neb_fesc, neb_fdust_frac)[1](#2436), thelyc_transmissionanalog for the dust-absorption fraction: a dust component’sparameter_prefix(dust_) meansslice_params_for_component(ADR-0006) never hands it aneb_-prefixed key, sotwo_componentreads this cross-component value instead ofparams["neb_fdust_frac"](which would silently see only the 0.0 default) to compute its own young-weighted HII-region dust credit.
- lyc_fesc: Array | None = None¶
Raw
neb_fescvalue (#2539 item 1), thelyc_fdustanalog for the escape fraction: published sotwo_component’s WavePrecomp energy-balance LUT branch can pass the runtime fesc intolut_l_absorbed_stellar_log10’s exact affine (A_0 + fesc*A_1) combine, the same cross-component reasonlyc_fdustexists (a dust component’sparameter_prefixnever sees aneb_-prefixed key).
- met_exact_joint: Array | None = None¶
(n_met, n_age) on a declared scatter, (1, n_age) age marginal when undeclared; with the galaxy’s log Z (scalar or per age) and the SSP metallicity nodes it is read over.
- Type:
Metallicity-read joint for the exact contractions (#3434, phase 2)
- nebular_line_frac: Array | None = None¶
Line share of
sed_nebular,lines / (continuum + lines)on the rest grid (0 where the nebular SED is 0), shape (n_wave,). Published by the Cue component when built withpublish_line_fraction=True; read bySpectroscopy(nebular_lines=False)to drop the lines from the spectrum.
- ssp_wave_ion: Array | None = None¶
Wavelength axis of
lnu_age_ion[Angstrom], shape (n_ion_bins,):ssp.ssp_wave[:n_ion_bins](the ionizing-side prefix of the ascending SSP grid, unprojected – i.e. before any panchromatic extension ofstate.wave).
- stellar_alpha_bracket_index: Array | None = None¶
Lower [alpha/Fe] node index
iaand fractionfaof the model’smet_alpha_feon a 4D grid, shape () each, or (n_age,) each underalpha_fe_evolving(one bracket per SSP age): the bracket the stellar component collapses its own cube at. Published only on a grid with an [alpha/Fe] axis; the dust energy-balance LUT collapses its alpha axis at the same bracket.Noneon a 3D grid.
- stellar_phot_lnu_per_age_subband_igm_precomp: Array | None = None¶
The same sub-band tensor with the IGM transmission folded in at the quadrature nodes, shape
(n_age, n_filter, n_subbands)[erg/s/Hz] (#1135). Published only when a mean-IGM model is precomputable: patchy reionization and DLAs read free parameters, soTis not a function of(λ, z)alone and those configs keep the live per-call path.igm_phot_factorband-averagesTalone, unweighted by the spectrum, forming⟨S⟩·⟨T⟩where the flux needs⟨S·T⟩. Across GALEX FUV at z≈0.8 the transmission runs from ~1 to ~0 inside the bandpass and that covariance term reaches −9.5 %. FoldingTinto the sub-band weights captures it in the same contraction as the dust screen.Folded at BUILD time, into the
(n_met, n_age, n_filter, n_subbands)SSP node tensor: where the nodes actually live. The node is a metallicity-weighted average whose weights move with the freemet_logzsol, so a table keyed on(z, age, filter, k)alone would be valid at one metallicity only (the node shifts by up to 68 % of a sub-band width across the SSP grid;Tthere by up to 1.3 % in GALEX FUV). Folding before the met contraction handles that exactly, and for free: the runtime einsum is the same shape and cost as the IGM-free one.The IGM-free twin above is retained, not replaced:
phot_rest_fnuis projected at z=0 and carries no IGM by contract.
- stellar_restband_lnu_per_age_subband_precomp: Array | None = None¶
Per-age sub-band quadrature over the rest band, shape (n_age, n_filter, K), and its nodes [Angstrom]: the #1122 machinery applied to the rest-frame projection, so the dust screen is EVALUATED across the band rather than extrapolated from its pivot.
- stellar_subband_waves_rest_igm_precomp: Array | None = None¶
the centroid of the light the IGM lets through [Angstrom], shape (n_age, n_filter, n_subbands). The dust screen on
stellar_phot_lnu_per_age_subband_igm_precompis evaluated here. Published only with the exact IGM fold.- Type:
The same node for the IGM-folded tensor
- to_dict() dict[str, Any][source]¶
Return a plain dict; the inverse of
from_dict().Non-None typed fields are included;
_extrasis merged in. Useful for serialization, debugging, and gradual migration.
- with_(**overrides: Any) DerivedState[source]¶
Return a copy with selected fields replaced.
Unknown keys raise
TypeError(the dataclass-frozen default) with a Levenshtein-2Did you mean: ...hint if the typo is close to a known field.
ComponentIOError¶
- exception tengri.protocols.ComponentIOError[source]¶
Bases:
ValueErrorRaised when one component’s declared inputs/outputs disagree with the chain.
Checked once at
tengri.SEDModelconstruction bytengri.forward.orchestrator.validate_pipeline(), before any JIT compile. The error message always names the offending component class and the offending derived key, with a “Did you mean: …” hint when a missing producer looks like a typo. Seevalidate_pipeline()for the full list of checks.
Orchestrator helpers¶
These run once at build_components() time. They are not on the
hot JIT-traced path and are intended for advanced users who construct
their own component lists or write new physics modules.
validate_pipeline¶
- tengri.forward.orchestrator.validate_pipeline(components: Iterable[SEDComponent]) None[source]¶
Check that every component’s inputs are produced by upstream components.
Runs at
tengri.SEDModelconstruction time, once per model. Zero hot-path / JIT cost, all checks are pure-Python over the metadata returned bySEDComponent.outputs()andSEDComponent.inputs().The five checks¶
Duplicate output. Two components publish the same key, unless they are listed in
_ALTERNATE_PUBLISHERSas alternate implementations of the same role (e.g. one-component vs two-component dust).Missing producer. A key declared in
inputs()has no upstreamoutputs(). The error message includes aDid you mean: ...suggestion when a published key is within edit distance 2; this is what catches the silent-rename hazard (L_ir→L_dust_totalproduces a suggestion).Out-of-order producer. A required key is published by a component that appears after the consumer in the pipeline list.
Unit mismatch (publisher vs consumer). Consumer’s
DerivedKey.unitsdiffers from publisher’s. The validator refuses to silently paper over a unit disagreement; conversion is the publisher’s or consumer’s responsibility, at their own boundary, made explicit.Canonical-units mismatch. Either side declares a units string that differs from
_CANONICAL_UNITSfor that key (where the table has an entry). Catches the case where a new component independently invents a units convention, the contract pins the project-wide answer.
- param components:
Ordered list of pipeline components, in the order they will run.
- type components:
iterable of SEDComponent
- raises ComponentIOError:
On any of the five failure modes. The message names the offending component class, the offending key, the offending units strings, and (where applicable) a
Did you mean: ...suggestion.
topological_sort¶
- tengri.forward.orchestrator.topological_sort(components: Iterable[SEDComponent]) list[SEDComponent][source]¶
Stable topological sort over the output/input dependency graph.
Produces an ordering where every component appears strictly after every other component whose
outputs()it consumes viainputs()oroptional_inputs(). Among components with no ordering constraint, the input order is preserved (stable sort).This is the inverse of
validate_pipeline()’s “out-of-order publisher” check, instead of refusing pipelines whose hand-coded order violates declared dependencies, it derives the order from the declarations. See ADR-0006.- Parameters:
components (iterable of SEDComponent) – The unordered (or arbitrarily-ordered) component list. Typically passed straight from
tengri.forward.build_components()which appends in domain-grouped order; the sort tightens that into the dependency-respecting order before downstream consumers observe it.- Returns:
Topologically ordered. For the canonical pipeline (stellar, nebular, shock, dust, AGN, radio, X-ray, IGM), this reproduces the hand-coded order byte-for-byte, the snapshot test in
tests.integration.test_derived_contract_snapshotsis the regression guarantee.- Return type:
list of SEDComponent
- Raises:
ComponentIOError – If the dependency graph contains a cycle. The error message names every component still pending when the algorithm stalls typically the cycle’s participants.
Notes
Algorithm. Kahn’s algorithm with stable tie-breaking: at each step, the lowest-input-index component whose dependencies are all already emitted is picked next. With deterministic-order producer resolution (first publisher wins on duplicates, see
_ALTERNATE_PUBLISHERS), the sort is fully deterministic.Why both ``inputs`` and ``optional_inputs``. A hard requirement establishes ordering by definition. An optional requirement also establishes ordering when the publisher is present: the consumer reads from
state.derivedwith a fallback, so it can only read meaningful data if the publisher has already written. The validator enforces strict-before for both flavors (ADR-0004 Phase B); the sort must too, elsevalidate_pipeline()would reject sort output.Zero JIT cost. Runs once at
build_components()time.
merge_declared_parameters¶
- tengri.forward.orchestrator.merge_declared_parameters(components: Iterable[SEDComponent]) dict[str, Any][source]¶
Flatten
declared_parameters()from each component into one prior dict.Each
SEDComponentowns a list ofParamDeclarationentries (name + prior + description). This helper validates that:Every declared name starts with the owning component’s
SEDComponent.parameter_prefixor is inBARE_NAME_ALLOWLIST.No two components declare the same parameter name (a collision would make the orchestrator’s prefix-slicing ambiguous).
The output maps each parameter name to its prior, suitable for spreading into
tengri.Parametersonce the component-driven builder intengri.parameters.parameterslands.- Parameters:
components (iterable of SEDComponent) – Adapters whose declarations should be merged.
- Returns:
Parameter name -> prior. Order is preserved by component order and within-component declaration order.
- Return type:
dict mapping str -> Distribution
- Raises:
ValueError – If a name violates the prefix rule or two components declare the same name.
run_components¶
- tengri.forward.orchestrator.run_components(components: Iterable[SEDComponent], state: ForwardState, params: Mapping[str, Array], ssp_data: Any | None = None, template_data: Any | None = None, ztable_data: Any | None = None) ForwardState[source]¶
Thread
statethroughcomponentsin order.- Parameters:
components (iterable of SEDComponent) – Ordered list. Each component reads what it needs from
stateand returns a newForwardState.state (ForwardState) – Initial pipeline state. Typically carries just
waveand any seed values (e.g.sed_observedalready populated).params (mapping) – Full parameter dict. Each component sees only its prefix-matched slice plus the bare-name allowlist.
ssp_data (Any | None, optional) – SSP stellar population synthesis grid. When provided, is passed to each component’s
apply()method as a JIT runtime parameter. Components that do not need it should ignore the argument. DefaultNonemeans components rely on their internalself.ssp_data.template_data (Any | None, optional) – Nebular backend grids and weights. When provided, is passed to each component’s
apply()method as a JIT runtime parameter. Components that do not need it should ignore the argument. DefaultNonemeans components rely on their internal template data.ztable_data (Any | None, optional) – Precomputed photometric redshift table for stellar component. When provided, is passed to each component’s
apply()method as a JIT runtime parameter instead of closure capture, preventing XLA from materializing it as a constant. DefaultNonemeans components rely on their internal z-table.
- Returns:
Final state after all components have applied.
- Return type:
ForwardState
- Raises:
ComponentIOError – If, after every component has applied, the final
state.derived._extrasis non-empty, i.e. some component’sapply()slipped data through theDerivedState’s opt-in spillover instead of usingstate.derived.with_(X=value)(ADR-0007 Phase 3). The snapshot test (tests.integration.test_derived_contract_snapshots) catches this for the 3 snapshotted recipes; the runtime check here broadens the guard to every hand-rolled component list. Bypass with the env varTENGRI_ALLOW_DERIVED_EXTRAS=1, useful during in-flight migrations or when external user code explicitly attaches non-canonical keys viaDerivedState.from_dict(..., allow_extras=True). Not for production code.
Extending the pipeline¶
Subclassing SEDModelComponent is the recommended way to add
a physics block: it registers the component for SEDModel.build dispatch
and discovers its parameters in one step (ADR-0011). register_component
is the narrower seam for a class that cannot take that base — it wires up
parameter discovery only.
- tengri.register_component(cls: type) type[source]¶
Register an SEDComponent class for parameter auto-discovery.
Decorate a contributor’s
SEDComponent-conforming class to have itsdeclared_parameters()consulted at param-map-build time, so any new free parameters become available totengri.Parameterswithout editingtengri.parameters.translate.- Parameters:
cls (type) – A class conforming to the
SEDComponentprotocol. It must exposename,parameter_prefix, and adeclared_parameters()method returning the parameter declarations the component contributes.- Returns:
The same class, unchanged, so the decorator is transparent.
- Return type:
Notes
Registration is idempotent: the class is appended once and re-decorating an already-registered class is a no-op. This function is the parameter-discovery seam only. Subclassing
tengri.SEDModelComponentregisters a component forSEDModel.builddispatch as well and is the recommended path for new physics blocks (ADR-0011); reach for this decorator when a class cannot take that base.Examples
>>> from tengri import register_component >>> @register_component ... class MyAGNSEDComponent: ... name = "my_agn" ... parameter_prefix = "my_agn_" ... ... def declared_parameters(self): ... return [ParamDeclaration("my_agn_param", ...)]
parse_groups is the translator underneath the nested-dict grammar,
turning the group dicts accepted by tengri.SEDModel.build() into a
Parameters spec. Call it directly to inspect what a set of
group dicts resolves to without building a model.
- tengri.parse_groups(**kwargs) Parameters[source]¶
Translate nested-dict model specification to Parameters.
- Parameters:
**kwargs (keyword arguments) – Model configuration. Keys are group names (sfh, dust_attenuation, dust_emission, neb, igm, radio, xray, agn) or top-level settings (redshift, apply_igm, n_grid).
_allow_empty_wildcard (bool, optional) – Private. When True, an
all_params: FREEthat frees nothing is permitted instead of raisingParameterError. Reserved for introspection callers (recipe_parameters()) that readall_paramsand do not care whether a parameter is free. Never set this when building a model to fit.ssp_data (SSPData, optional) – The SSP the model is built against. When
neb={'type': 'cloudy'}names no explicitgrid, itssourceisochrone tag ("mist"/"prsc"/"pdva"/"bpss") is preferred when auto-resolving the packagedcloudy_grid_<tag>.h5(#2426). Passed automatically bybuild().
- Returns:
A fully initialized Parameters object ready for inference.
- Return type:
- Raises:
ValueError – If an unknown group key, unknown type value, or unknown parameter name is provided. Also raised if both deprecated ‘lines’ and new ‘nlr’/’blr’ sub-blocks are provided under ‘agn’.
Notes
JIT-compatible: no; this is a pure Python translator.
AGN blocks: The new composable AGN grammar supports independent
nlr(narrow-line region) andblr(broad-line region) sub-blocks under theagngroup. The deprecatedlinessub-block is expanded to an (nlr, blr) pair with aDeprecationWarning.Examples
>>> from tengri.parameters import parse_groups, FREE >>> params = parse_groups( ... sfh={"type": "dpl", "all_params": FREE}, ... redshift=0.1, ... ) >>> assert "sfh_dpl_alpha" in params.free_params