Utilities¶
Grid construction and helper functions used throughout the pipeline.
The Gaussian-process generators (compute_field_gp,
generate_gp_fourier, generate_gp_batch, gp_from_xi) are
documented in Physics models, alongside the PSD parameterizations they
consume.
make_log_age_grid¶
- tengri.make_log_age_grid(n_grid: int = 256, log_age_min: float = 6.0, log_age_max: float = 10.14) Array[source]¶
Create uniform grid in log10(age/yr).
Default range: 1 Myr to ~13.8 Gyr (approximately the age of the universe).
- Parameters:
n_grid (int, optional) – Number of grid points (should be even for FFT efficiency). Default: 256.
log_age_min (float, optional) – Minimum log10(age/yr) [dimensionless log years]. Default: 6.0 (1 Myr).
log_age_max (float, optional) – Maximum log10(age/yr) [dimensionless log years]. Default: 10.14 (~13.8 Gyr).
- Returns:
Uniform grid in log10(age/yr) [dimensionless log values].
- Return type:
ndarray, shape (n_grid,)
Notes
JIT-compatible: yes, uses
jnp.linspace.This grid is the internal representation for age in GP-based SFH models. The log-space parametrization provides better resolution at young ages and maps naturally to the logarithmic timescales of stellar evolution.
This is the single definition.
components.stellar.sfh.gp_sfhre-exports it under the same name; the forward model and the inference standardization consume it from opposite sides of that boundary, so a second copy could desync the two without any test failing (#1402).Examples
>>> from tengri import make_log_age_grid >>> grid = make_log_age_grid(n_grid=64) >>> grid.shape (64,) >>> float(grid[0]), float(grid[-1]) (6.0, 10.14)
Noise utilities¶
- tengri.compute_effective_noise(noise_obs: Array, model_flux: Array, f_cal: float | Array) Array[source]¶
Compute effective noise with calibration floor.
σ_eff = sqrt(σ²_obs + (f_cal · model)²)
- Parameters:
noise_obs (array, shape (n_bands,)) – Observed 1-sigma uncertainties [flux units].
model_flux (array, shape (n_bands,)) – Model-predicted fluxes [flux units] (absolute value used for calibration term).
f_cal (float or array, shape (n_bands,)) – Fractional calibration uncertainty [dimensionless]. A scalar applies the same floor to all bands. An array applies a per-band floor; shape must match
noise_obsandmodel_flux. Typical range: 0.01–0.15.
- Returns:
Effective noise standard deviation [same units as inputs].
- Return type:
array, shape (n_bands,)
Notes
JIT-compatible: yes, uses only jnp primitives.
The calibration term
f_cal * |model|adds a flux-dependent floor to the noise budget, preventing zero-noise solutions when measurement uncertainties are very small. Per-band floors allow calibration uncertainty to vary across filters, e.g., due to detector or photometry pipeline differences.Examples
>>> import jax.numpy as jnp >>> from tengri import compute_effective_noise >>> noise = jnp.array([0.1, 0.2, 0.15]) >>> model = jnp.array([1.0, 2.0, 1.5]) >>> sigma_eff = compute_effective_noise(noise, model, f_cal=0.05) >>> sigma_eff.shape (3,)
Per-band floor example:
>>> f_cal_per_band = jnp.array([0.02, 0.10, 0.05]) >>> sigma_eff = compute_effective_noise(noise, model, f_cal=f_cal_per_band) >>> sigma_eff.shape (3,)
- tengri.compute_std_inv(noise_obs: Array, model_flux: Array, f_cal: float | Array) Array[source]¶
Compute inverse effective noise (precision).
τ = 1/σ_eff. This is the second output expected by NIFTy’s
VariableCovarianceGaussianlikelihood.- Parameters:
noise_obs (array, shape (n_bands,)) – Observed 1-sigma uncertainties [flux units].
model_flux (array, shape (n_bands,)) – Model-predicted fluxes [flux units].
f_cal (float or scalar array) – Fractional calibration uncertainty [dimensionless].
- Returns:
Inverse noise standard deviation τ = 1/σ_eff [1/flux_units].
- Return type:
array, shape (n_bands,)
Notes
JIT-compatible: yes, delegates to
compute_effective_noise()which is pure JAX.Used in variable-covariance likelihoods where the noise is a traced parameter. See
variable_noise_hamiltonian()for integration into the likelihood energy function.Examples
>>> import jax.numpy as jnp >>> from tengri import compute_std_inv >>> noise = jnp.array([0.1, 0.2, 0.15]) >>> model = jnp.array([1.0, 2.0, 1.5]) >>> tau = compute_std_inv(noise, model, f_cal=0.05) >>> tau.shape (3,)
- tengri.has_noise_model(spec) bool[source]¶
Check if any noise parameter is free (not Fixed at 0).
- Parameters:
spec (Parameters) – Parameter specification.
- Returns:
True if the noise model is active (any noise parameter is free or Fixed to nonzero value).
- Return type:
Notes
Not JIT-compatible (uses Python control flow and class introspection).
This function checks if any parameter whose name starts with
"noise_"is in the free parameter list, or ifnoise_frac_calis explicitly fixed to a nonzero value.Examples
>>> from tengri import Parameters, Uniform, has_noise_model >>> spec = Parameters(dust_tau_bc=Uniform(0.1, 4.0)) >>> has_noise_model(spec) False >>> spec2 = Parameters(dust_tau_bc=Uniform(0.1, 4.0), noise_frac_cal=Uniform(0.01, 0.2)) >>> has_noise_model(spec2) True
Bundled data and caches¶
tengri persists compiled JAX kernels and precomputed photometry tables
between sessions, and resolves bundled data files by walking parent
directories for a data/ folder.
- tengri.data_path(filename: str) Path[source]¶
Locate a bundled data file in any directory tengri reads data from.
Searches
data_dirs():$TENGRI_DATA_DIRfirst if set, then each ancestor of the working directory with adata/subdirectory, then~/tengri/data. The ancestor walk matters because sphinx-gallerychdir``s into each script's directory before exec, so a hand-coded ``"data/foo.h5"would otherwise resolve underexamples/<section>/.- Parameters:
filename (str) – Basename of the data file, e.g.
"bosa_templates.h5".- Returns:
Path to the file.
- Return type:
- Raises:
FileNotFoundError – If
filenameexists in none ofdata_dirs(). The message names the directories searched.
Examples
>>> from tengri import data_path >>> templates = data_path("bosa_templates.h5") >>> import h5py >>> h5py.File(templates).keys()
Batching¶
- tengri.vmap_chunked(fn, chunk_size: int = 16, *, shared=None)[source]¶
Map
fnover a batch in memory-bounded chunks.Equivalent to
jax.vmap(fn)in its result, but evaluates the batchchunk_sizedraws at a time so peak memory scales with the chunk rather than with the batch. Each chunk runs as one compiledjit(vmap(fn))kernel.If
fncannot be jitted (some nebular backends are not traceable) the call degrades to an eager per-draw loop rather than raising, and warns once so the ~7x slowdown is never silent. The jittability probe runs once per returned callable, not once per draw.No state is kept between calls: each call to
vmap_chunked()compiles its own kernel. To reuse a compiled program across calls, hold on to the returned callable (an owner caches it, keyed on its compile signature), not the function.Only genuine tracing failures count as “not jittable”. A typo’d key, a shape mismatch, or any other real bug propagates rather than being quietly reclassified and routed around (#1128).
- Parameters:
fn (callable) – A function of a single parameter pytree (e.g.
params -> dict). It is mapped over the leading axis of every leaf of the batch. Withsharedgiven it is(item, shared) -> result.chunk_size (int, default 16) – Draws per compiled call. Larger is faster and hungrier. Values larger than the batch are harmless (one chunk). Galaxy-batch entry points use
GALAXY_CHUNK_SIZEinstead.shared (pytree, optional) – Arguments shared by every item (grids, templates, a wavelength grid). They are broadcast to every item and passed into the compiled chunk as arguments, not closed over, so they are not frozen as constants.
- Returns:
batch -> results, wherebatchis a pytree whose leaves share a leading draw axis of lengthn, and each result leaf has leading axisn.- Return type:
callable
- Warns:
UserWarning – Once per callable, when
fnturns out not to be traceable and the evaluation falls back to the eager per-draw loop.- Raises:
ValueError – If
chunk_sizeisNone(useGALAXY_CHUNK_SIZEorlen(batch)), is not an int, or is not positive; or the batch has no leaves.Exception – Whatever
fnraises, if the failure is not a tracing failure; a real bug is never swallowed by the jittability probe.
Notes
JIT-compatible: the returned callable is not itself meant to be jitted; it drives compilation internally and does Python-level slicing. Use it around a jittable
fn, not inside anotherjit.The ragged final chunk (when
nis not a multiple ofchunk_size) triggers one extra, cheap compile for its distinct shape.Not bit-neutral. XLA compiles a different kernel per batch shape, so changing
chunk_sizecan move the last bit (~1 ULP). Pin it if you need bit-for-bit reproducibility.Examples
>>> from tengri import vmap_chunked >>> masses = vmap_chunked( ... lambda p: model.predict_properties(p, names=("stellar_mass",)), ... chunk_size=32, ... )(posterior.samples) >>> masses["stellar_mass"].shape (4000,)
Parameter introspection¶
Read-only walker over every declared free parameter — per-component
_params.py modules plus the shared parameters/_shared.py declarations.
See docs/adr/0008-parameter-registry-introspection.md for the
design rationale.
list_parameters¶
- tengri.list_parameters(prefix: str | None = None)[source]¶
List every free parameter in the registry, optionally filtered.
- Parameters:
prefix (str, optional) – If given, only return names starting with this prefix (e.g.
"dust_","agn_"). Useful for surveying a physics domain.- Returns:
One row per parameter, sorted by name, with keys
name,description,units,ownerandgroup. Renders as a table in a notebook.This used to return
list[str], the onlylist_*that did (#1285). Use.names()for the old shape: and note the bare names were throwing away the description and units the registry stores.- Return type:
_RegistryTable
Examples
>>> import tengri >>> tengri.list_parameters(prefix="radio_").names()[:3] ['radio_T_e', 'radio_alpha_agn', 'radio_alpha_ff']
describe_parameter¶
- tengri.describe_parameter(name: str) ParameterRecord[source]¶
Return the
ParameterRecordforname.- Raises:
KeyError – If
nameis not in the registry. The message lists the Levenshtein-closest known parameter as a “Did you mean: …” hint, matching the style used bytengri.forward.orchestrator.validate_pipeline().
Examples
>>> import tengri >>> rec = tengri.describe_parameter("dust_tau_v") >>> rec.owner 'tengri.components.dust._params'
recipe_parameters¶
- tengri.recipe_parameters(recipe_dict: dict, free_only: bool = True) list[ParameterRecord][source]¶
Introspect a recipe dict and return the parameters it activates.
Takes a nested-dict recipe (output of e.g.
tengri.recipes.star_forming_photometry()) and returns a sorted list ofParameterRecordobjects for each parameter that the recipe would activate: WITHOUT requiring SSP data or building anSEDModel.- Parameters:
recipe_dict (dict) –
A recipe dictionary matching the format of
tengri.recipes. Example:{ "sfh": {"type": "dpl", "all_params": FREE}, "dust": {"type": "two_component", "law": "calzetti", "all_params": FREE}, "neb": {"type": "cue", "all_params": Fixed(DEFAULT)}, "redshift": Uniform(0.01, 6.0), }
free_only (bool, optional) – If True (default), return only the free parameters (entries with non-fixed priors). If False, return all parameters the recipe activates (including fixed ones). Default is True.
- Returns:
A sorted list of
ParameterRecordobjects corresponding to the parameters that the recipe activates. Sorted by parameter name.- Return type:
- Raises:
ValueError – If the recipe dict is invalid (e.g., unknown group, unknown type, invalid parameter name).
Notes
Does not require SSP data. Unlike
build(), which needs SSP data to build the full model, this function only translates the recipe structure to aParametersobject and introspects its parameter names; the heaviest operation is a pure-Python dict traversal.Resolves sentinels/tokens.
FREEis expanded to its registry default prior, andFixed(DEFAULT)is expanded to its registry default value; iffree_only=True, fixed entries are filtered out.Examples
List all free parameters activated by a recipe:
>>> from tengri import recipes, recipe_parameters >>> recipe = recipes.star_forming_photometry() >>> params = recipe_parameters(recipe) >>> len(params) 14 >>> params[0].name 'agn_a_spin'
Or include fixed parameters:
>>> all_params = recipe_parameters(recipe, free_only=False) >>> len(all_params) > len(params) True
See also
recipesCurated recipe functions.
describe_parameterLook up a single parameter by name.
ParameterRecord¶
- class tengri.ParameterRecord(name: str, prior: object, description: str, units: str, owner: str, group: str, free_prior: object = None, internal_name: str | None = None, scale: float = 1.0, offset: float = 0.0)[source]¶
Bases:
NamedTupleWhere a free parameter lives: name, prior, description, units, owner module, owner tuple.
Physical constants¶
Fundamental physical constants in CGS units.
- tengri.units.C_AA¶
Convert a string or number to a floating-point number, if possible.
- tengri.units.LOG10_ZSUN¶
Convert a string or number to a floating-point number, if possible.