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_sfh re-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_obs and model_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 VariableCovarianceGaussian likelihood.

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:

bool

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 if noise_frac_cal is 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

Correlated noise

Spectroscopic residuals are rarely white. These build a full covariance as white noise plus a Gaussian-process kernel, for use with a NoiseModel that models correlated errors.

tengri.gp_noise_covariance(wavelength: Array, noise_obs: Array, gp_amplitude: float | Array, gp_length_scale: float | Array, kernel: str = 'exp_squared') → Array[source]

Compute noise covariance as white noise + GP kernel.

Combines observational uncertainties (white noise diagonal) with a Gaussian process kernel to model correlated spectral noise.

Parameters:
  • wavelength (array, shape (n_wave,)) – Wavelengths [Angstrom].

  • noise_obs (array, shape (n_wave,)) – Observed 1-sigma uncertainties [same units as flux].

  • gp_amplitude (float or scalar array) – GP kernel amplitude. Dimensionless scaling of kernel.

  • gp_length_scale (float or scalar array) – GP kernel length scale [Angstrom].

  • kernel (str, optional) – Kernel type: “exp_squared” (default) or “matern32”.

Returns:

N – Covariance matrix \(N = \text{diag}(\sigma_{\text{obs}}^2) + K_{\text{gp}}\).

Return type:

ndarray, shape (n_wave, n_wave)

Notes

The returned matrix combines white noise variance on the diagonal with off-diagonal correlations from the chosen GP kernel. This is suitable for spectral fitting likelihoods that support full covariance matrices.

Examples

>>> import jax.numpy as jnp
>>> from tengri import gp_noise_covariance
>>> wave = jnp.linspace(4000.0, 8000.0, 50)
>>> noise = jnp.ones(50) * 0.1
>>> N = gp_noise_covariance(
...     wave, noise, gp_amplitude=0.5, gp_length_scale=300.0, kernel="exp_squared"
... )
>>> N.shape
(50, 50)
tengri.exp_squared_kernel(x: Array, amplitude: float | Array, length_scale: float | Array, x2: Array | None = None) → Array[source]

Squared exponential (RBF) covariance kernel.

Computes the squared exponential kernel matrix for Gaussian process modeling of correlated spectral noise.

Parameters:
  • x (array, shape (n,)) – Coordinate values [Angstrom] (or any real-valued coordinate).

  • amplitude (float or scalar array) – Kernel amplitude \(\sigma\). Controls overall variance.

  • length_scale (float or scalar array) – Kernel length scale \(\ell\). Controls correlation length.

  • x2 (array, shape (m,), optional) – Second set of coordinates for cross-covariance. If None, computes auto-covariance (x vs x).

Returns:

K – Covariance matrix. If x2 is None, returns symmetric (n, n) auto-covariance; otherwise returns (n, m) cross-covariance.

Return type:

ndarray, shape (n, n) or (n, m)

Notes

\[K(x, x') = \sigma^2 \exp\!\left(-\frac{(x - x')^2}{2 \ell^2}\right)\]

where \(\sigma\) is the amplitude and \(\ell\) is the length scale.

JIT-compatible and differentiable w.r.t. all float inputs.

Examples

>>> import jax.numpy as jnp
>>> from tengri import exp_squared_kernel
>>> x = jnp.linspace(4000.0, 8000.0, 20)
>>> K = exp_squared_kernel(x, amplitude=1.0, length_scale=500.0)
>>> K.shape
(20, 20)
>>> float(K[0, 0])  # diagonal entry equals amplitude^2
1.0
tengri.matern32_kernel(x: Array, amplitude: float | Array, length_scale: float | Array, x2: Array | None = None) → Array[source]

Matérn 3/2 covariance kernel.

Once-differentiable GP kernel, smoother than the exponential kernel, rougher than squared-exponential. A good default for correlated spectral noise where the autocorrelation length is finite but the residuals are not infinitely smooth.

Parameters:
  • x (array, shape (n,)) – Coordinate values [Angstrom] (or any real coordinate).

  • amplitude (float or scalar array) – Kernel amplitude \(\sigma\).

  • length_scale (float or scalar array) – Correlation length \(\ell\).

  • x2 (array, shape (m,), optional) – Second set of coordinates for cross-covariance. Defaults to x (auto-covariance).

Returns:

K

Return type:

ndarray, shape (n, n) or (n, m)

Notes

\[K(x, x') = \sigma^2 \left(1 + \frac{\sqrt{3}\,r}{\ell}\right) \exp\!\left(-\frac{\sqrt{3}\,r}{\ell}\right), \quad r = |x - x'|\]

JIT-compatible. \(r\) is softened to \(\sqrt{r^2 + 10^{-20}}\) so the gradient is defined at the diagonal.

Examples

>>> x = jnp.linspace(4000.0, 8000.0, 20)
>>> K = matern32_kernel(x, amplitude=1.0, length_scale=500.0)
>>> K.shape
(20, 20)

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_DIR first if set, then each ancestor of the working directory with a data/ subdirectory, then ~/tengri/data. The ancestor walk matters because sphinx-gallery chdir``s into each script's directory before exec, so a hand-coded ``"data/foo.h5" would otherwise resolve under examples/<section>/.

Parameters:

filename (str) – Basename of the data file, e.g. "bosa_templates.h5".

Returns:

Path to the file.

Return type:

pathlib.Path

Raises:

FileNotFoundError – If filename exists in none of data_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()
tengri.clear_cache(cache_dir: str | PathLike[str] | None = None) → int[source]

Remove all entries from the persistent cache directory.

The directory itself is preserved (the cache stays enabled). Use after pip install -U jax to evict stale-key artifacts, or periodically for general housekeeping.

Parameters:

cache_dir (str or PathLike or None) – Directory to clear. Defaults to the currently enabled cache, falling back to _default_cache_dir().

Returns:

Bytes reclaimed. Reported because the cache is otherwise invisible: it reached 141 GB before anyone looked (#1507).

Return type:

int

Batching

tengri.vmap_chunked(fn, chunk_size: int = 16, *, shared=None)[source]

Map fn over a batch in memory-bounded chunks.

Equivalent to jax.vmap(fn) in its result, but evaluates the batch chunk_size draws at a time so peak memory scales with the chunk rather than with the batch. Each chunk runs as one compiled jit(vmap(fn)) kernel.

If fn cannot 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. With shared given 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_SIZE instead.

  • 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, where batch is a pytree whose leaves share a leading draw axis of length n, and each result leaf has leading axis n.

Return type:

callable

Warns:

UserWarning – Once per callable, when fn turns out not to be traceable and the evaluation falls back to the eager per-draw loop.

Raises:
  • ValueError – If chunk_size is None (use GALAXY_CHUNK_SIZE or len(batch)), is not an int, or is not positive; or the batch has no leaves.

  • Exception – Whatever fn raises, 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 another jit.

The ragged final chunk (when n is not a multiple of chunk_size) triggers one extra, cheap compile for its distinct shape.

Not bit-neutral. XLA compiles a different kernel per batch shape, so changing chunk_size can 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, owner and group. Renders as a table in a notebook.

This used to return list[str], the only list_* 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 ParameterRecord for name.

Raises:

KeyError – If name is not in the registry. The message lists the Levenshtein-closest known parameter as a “Did you mean: …” hint, matching the style used by tengri.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 of ParameterRecord objects for each parameter that the recipe would activate: WITHOUT requiring SSP data or building an SEDModel.

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 ParameterRecord objects corresponding to the parameters that the recipe activates. Sorted by parameter name.

Return type:

list of ParameterRecord

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 a Parameters object and introspects its parameter names; the heaviest operation is a pure-Python dict traversal.

Resolves sentinels/tokens. FREE is expanded to its registry default prior, and Fixed(DEFAULT) is expanded to its registry default value; if free_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

recipes

Curated recipe functions.

describe_parameter

Look 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: NamedTuple

Where a free parameter lives: name, prior, description, units, owner module, owner tuple.

description: str

Alias for field number 2

free_prior: object

Alias for field number 6

group: str

Alias for field number 5

internal_name: str | None

Alias for field number 7

name: str

Alias for field number 0

offset: float

Alias for field number 9

owner: str

Alias for field number 4

prior: object

Alias for field number 1

scale: float

Alias for field number 8

units: str

Alias for field number 3

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.