Distributions¶
Prior distributions for model parameters. Each distribution provides
sample, log_prob, and transform methods compatible with JAX
tracing.
Uniform¶
- class tengri.Uniform(lo: float, hi: float, description: str = '', *, units: str = '', default: float | None = None)[source]¶
Bases:
DistributionUniform prior on [lo, hi].
A flat probability density on the interval [lo, hi]. Commonly used for bounded astrophysical quantities with little prior knowledge. Reparameterizes via the Gaussian CDF to ensure differentiability and automatic bound satisfaction.
- Parameters:
- Variables:
- Raises:
ValueError – If lo >= hi.
Notes
JIT-compatible: yes, all operations use
jnpprimitives.Standardization: Maps ξ ~ N(0,1) to θ via the Gaussian CDF:
\[\theta = lo + (hi - lo) \cdot \Phi(\xi)\]where Φ(ξ) = 0.5 * (1 + erf(ξ / sqrt(2))) is the standard normal CDF. At ξ = 0 (prior center), Φ(0) = 0.5, so θ = (lo + hi) / 2. This ensures an N(0,1) latent yields a genuine uniform prior on [lo, hi], not a midpoint-peaked one. Automatic bound satisfaction and smooth gradients.
Examples
>>> import jax.random >>> from tengri import Uniform >>> prior = Uniform(0, 1) >>> key = jax.random.PRNGKey(0) >>> sample = prior.sample(key) >>> print(f"Sample: {sample:.4f}") # Will be in [0, 1) >>> log_prob = prior.log_prob(0.5) >>> print(f"log p(0.5): {log_prob:.4f}") # ≈ 0.0 (log(1) = 0)
- property hi: float¶
Upper bound of the uniform distribution.
- Returns:
Upper bound value.
- Return type:
- property lo: float¶
Lower bound of the uniform distribution.
- Returns:
Lower bound value.
- Return type:
- sample(key: Array) Array[source]¶
Draw one sample uniformly from [lo, hi].
- Parameters:
key (jax.Array) – JAX PRNG key for random sampling.
- Returns:
A single sample uniformly distributed in [lo, hi].
- Return type:
ndarray
- standardize(theta: Array) Array[source]¶
Uniform(lo, hi) → ξ via inverse Gaussian CDF.
Inverts the unstandardize map: given θ ∈ (lo, hi), returns ξ such that θ = lo + (hi-lo) * Φ(ξ). Uses the inverse error function erfinv.
- unstandardize(xi: Array) Array[source]¶
ξ ~ N(0,1) → Uniform(lo, hi) via Gaussian CDF.
Uses the standard normal CDF Φ(ξ) = 0.5 * (1 + erf(ξ / sqrt(2))) to map N(0,1) latent variables to uniform on (lo, hi). At ξ=0, Φ(0) = 0.5, so θ = midpoint of [lo, hi]. This ensures an N(0,1) latent yields a genuine uniform prior, not a midpoint-peaked one.
Gaussian¶
- class tengri.Gaussian(mu: float, sigma: float, lo: float = -inf, hi: float = inf, description: str = '', *, units: str = '', default: float | None = None)[source]¶
Bases:
DistributionGaussian (normal) prior, optionally clipped to [lo, hi].
A bell-curve probability density centered at μ with standard deviation σ. Useful when prior information suggests a most-probable value with uncertainty. Optional bounds allow truncation to physical ranges.
- Parameters:
- Variables:
- Raises:
ValueError – If sigma <= 0 or lo >= hi.
Notes
JIT-compatible: yes, all operations use
jnpprimitives.Standardization: Unbounded case maps ξ ~ N(0,1) to θ = μ + σ·ξ. With finite bounds, uses the truncated-normal inverse CDF:
\[\theta = \mu + \sigma \cdot \Phi^{-1}\left[\Phi(\alpha) + \Phi(\xi)\,(\Phi(\beta) - \Phi(\alpha))\right]\]with α = (lo−μ)/σ, β = (hi−μ)/σ; the exact inverse-CDF pushforward (Knollmüller & Enßlin 2019, arXiv:1901.11033, Eqs. 18–25). Clipping would instead censor: point-masses at the bounds and zero gradient outside them.
Normalization: When lo, hi are finite, the density is normalized over [lo, hi] (
log_probincludes the −log[Φ(β)−Φ(α)] mass term), not over the full real line. Use this for physically bounded quantities.Examples
>>> import jax.random >>> from tengri import Gaussian >>> prior = Gaussian(mu=-0.3, sigma=0.2) # metallicity >>> key = jax.random.PRNGKey(0) >>> sample = prior.sample(key) >>> print(f"Sample: {sample:.3f}") # Typically near -0.3 >>> log_prob = prior.log_prob(-0.3) >>> print(f"log p(μ): {log_prob:.4f}") # Maximum at mean
- property hi: float¶
Upper truncation bound.
- Returns:
Upper truncation bound (+inf if unbounded).
- Return type:
- property lo: float¶
Lower truncation bound.
- Returns:
Lower truncation bound (-inf if unbounded).
- Return type:
- sample(key: Array) Array[source]¶
Draw a random sample from the Gaussian distribution.
- Parameters:
key (jax.Array) – JAX PRNG key for random sampling.
- Returns:
A single sample from N(mu, sigma²) truncated to [lo, hi].
- Return type:
ndarray
- property sigma: float¶
Standard deviation of the Gaussian distribution.
- Returns:
Standard deviation value.
- Return type:
- unstandardize(xi: Array) Array[source]¶
ξ ~ N(0,1) → N(μ,σ²) exactly truncated to [lo, hi].
Unbounded case is the identity-affine map θ = μ + σξ. With finite bounds, uses the truncated-normal inverse CDF θ = μ + σ·Φ⁻¹(Φ(α) + Φ(ξ)·(Φ(β) − Φ(α))): a smooth bijection onto (lo, hi), unlike clipping, which piles point-masses at the bounds and zeroes the gradient outside them.
Log uniform¶
- class tengri.LogUniform(lo: float, hi: float, description: str = '', *, units: str = '', default: float | None = None)[source]¶
Bases:
DistributionUniform in log10 space on [lo, hi].
A prior that places equal probability in logarithmic intervals, resulting in power-law density in linear space. Useful for quantities with logarithmic uncertainties, such as star formation rates, timescales, and luminosities.
- Parameters:
lo (float) – Lower bound. Must be strictly positive.
hi (float) – Upper bound. Must be greater than lo.
description (str, optional) – Human-readable summary of the quantity, surfaced by
describe_parameterandspec.summary().units (str, optional) – Physical units, e.g.
"erg/s". Empty for dimensionless quantities.
- Variables:
- Raises:
ValueError – If lo <= 0 or lo >= hi.
Notes
JIT-compatible: yes; all operations use
jnpprimitives.The probability density in linear space is:
\[p(x) = \frac{1}{x \cdot \ln(10) \cdot \log_{10}(hi / lo)}\]where x ∈ [lo, hi]. Samples drawn from this distribution are equally spaced in log10 space: log10(x) ~ U(log10(lo), log10(hi)).
Standardization: Maps ξ ~ N(0,1) to θ via the Gaussian CDF in log space (the exact inverse-CDF pushforward required by the standardized parameterization; Knollmüller & Enßlin 2019 [tengri.LogUniform-1], Eqs. 18–25):
\[\theta = \exp\left[\ln(lo) + (\ln(hi) - \ln(lo)) \cdot \Phi(\xi)\right]\]where Φ(ξ) = 0.5 * (1 + erf(ξ / sqrt(2))) is the standard normal CDF. This ensures an N(0,1) latent yields a genuine log-uniform prior on [lo, hi] (matching
log_probandsample) not a midpoint-peaked one. (A sigmoid map here would silently substitute a logit-normal prior in log space, biasing weakly-constrained scale parameters toward the geometric midpoint and compressing the tails.)References
[tengri.LogUniform-1]Knollmüller, J. & Enßlin, T. A., “Metric Gaussian Variational Inference”, arXiv:1901.11033.
Examples
>>> import jax.random >>> from tengri import LogUniform >>> prior = LogUniform(1e-2, 1e2) # ~4 orders of magnitude >>> key = jax.random.PRNGKey(0) >>> sample = prior.sample(key) >>> print(f"Sample: {sample:.3e}") >>> log_prob = prior.log_prob(1.0) # Center of log space >>> print(f"log p(1.0): {log_prob:.4f}")
- property hi: float¶
Upper bound of the log-uniform distribution.
- Returns:
Upper bound value.
- Return type:
- property lo: float¶
Lower bound of the log-uniform distribution.
- Returns:
Lower bound value.
- Return type:
- log_prob(x: Array) Array[source]¶
Return log probability: -log(x * log(hi/lo)) inside bounds, -inf outside.
- sample(key: Array) Array[source]¶
Draw one sample log-uniformly from [lo, hi].
- Parameters:
key (jax.Array) – JAX PRNG key for random sampling.
- Returns:
A single sample log-uniformly distributed in [lo, hi].
- Return type:
ndarray
- standardize(theta: Array) Array[source]¶
LogUniform(lo, hi) → ξ via inverse Gaussian CDF in log space.
Inverts the unstandardize map: given θ ∈ (lo, hi), returns ξ such that θ = exp(ln lo + (ln hi − ln lo) · Φ(ξ)).
- unstandardize(xi: Array) Array[source]¶
ξ ~ N(0,1) → LogUniform(lo, hi) via Gaussian CDF in log space.
Uses the standard normal CDF Φ(ξ) = 0.5 * (1 + erf(ξ / sqrt(2))) so that an N(0,1) latent yields a genuine log-uniform prior; the exact inverse-CDF pushforward θ = F⁻¹(Φ(ξ)) required for the ½ξᵀξ prior term in the standardized information Hamiltonian.
Log normal¶
- class tengri.LogNormal(mu: float = 0.0, sigma: float = 1.0, lo: float = 0.0, hi: float = inf, description: str = '', *, units: str = '', default: float | None = None)[source]¶
Bases:
DistributionLog-normal prior: log(θ) ~ N(μ, σ²).
A prior suitable for positive-definite quantities with multiplicative uncertainty, such as timescales, amplitudes, and scale factors. The log of the parameter is normally distributed.
- Parameters:
mu (float, optional) – Mean of log(θ). Default: 0.0.
sigma (float, optional) – Standard deviation of log(θ). Must be positive. Default: 1.0.
lo (float, optional) – Lower truncation bound. Default: 0.0 (ensures θ > 0).
hi (float, optional) – Upper truncation bound. Default: +∞ (no upper truncation).
description (str, optional) – Human-readable summary of the quantity, surfaced by
describe_parameterandspec.summary().units (str, optional) – Physical units, e.g.
"erg/s". Empty for dimensionless quantities.
- Variables:
- Raises:
ValueError – If sigma <= 0.
Notes
JIT-compatible: yes, all operations use
jnpprimitives.The probability density in linear space is:
\[p(\theta) = \frac{1}{\theta \sigma \sqrt{2\pi}} \exp\left( -\frac{(\ln \theta - \mu)^2}{2\sigma^2} \right)\]for θ ∈ [lo, hi]. When truncated, the density is renormalized over the interval.
Standardization: Maps ξ ~ N(0,1) to θ via:
\[\theta = \text{clip}(\exp(\mu + \sigma \cdot \xi), lo, hi)\]Examples
>>> import jax.random >>> from tengri import LogNormal >>> # PSD timescale: log(tau_yr) centered at 8, width 0.5 dex >>> prior = LogNormal(mu=8, sigma=0.5) >>> key = jax.random.PRNGKey(0) >>> sample = prior.sample(key) >>> print(f"Sample (yr): {sample:.3e}") >>> log_prob = prior.log_prob(1e8) >>> print(f"log p(1e8): {log_prob:.4f}")
- log_prob(x: Array) Array[source]¶
Evaluate log probability density, returning -inf outside bounds.
Normalized over [lo, hi] (the constants matter for nested-sampling evidence, which compares priors across models).
- property mu: float¶
Mean of log(theta).
- Returns:
Mean of the logarithm of the parameter.
- Return type:
- sample(key: Array) Array[source]¶
Draw a random sample from the log-normal distribution.
- Parameters:
key (jax.Array) – JAX PRNG key for random sampling.
- Returns:
A single sample from LogNormal(mu, sigma²) truncated to [lo, hi].
- Return type:
ndarray
- property sigma: float¶
Standard deviation of log(theta).
- Returns:
Standard deviation of the logarithm of the parameter.
- Return type:
Student t¶
- class tengri.StudentT(mu: float = 0.0, sigma: float = 1.0, df: float = 3.0, lo: float = -inf, hi: float = inf, description: str = '', *, units: str = '', default: float | None = None)[source]¶
Bases:
DistributionStudent’s t prior with heavier tails than Gaussian.
A robust prior with longer tails, useful for parameters that may exhibit outlier-like behavior. Commonly used in BAGPIPES-style SED fitting for down-weighting extreme values while remaining flexible.
- Parameters:
mu (float, optional) – Location (center) of the distribution. Default: 0.0.
sigma (float, optional) – Scale parameter. Must be positive. Default: 1.0.
df (float, optional) –
Degrees of freedom. Controls tail weight:
df → ∞ gives Gaussian (heaviest concentration at center)
df = 3 gives a moderately heavy-tailed prior
df = 1 gives Cauchy (extremely heavy tails)
Default: 3.0.
lo (float, optional) – Lower truncation bound. Default: -∞ (no lower truncation).
hi (float, optional) – Upper truncation bound. Default: +∞ (no upper truncation).
description (str, optional) – Human-readable summary of the quantity, surfaced by
describe_parameterandspec.summary().units (str, optional) – Physical units, e.g.
"erg/s". Empty for dimensionless quantities.
- Variables:
Notes
JIT/grad/vmap-safe: yes, including the gradient at the Φ(ξ)=½ midpoint (ξ=0): see Standardization below.
The probability density follows a Student’s t distribution with the standard normalization. For finite df, it has heavier tails than a Gaussian.
Standardization: Exact quantile pushforward θ = μ + σ·F⁻¹_t,df(Φ(ξ)) (Knollmüller & Enßlin 2019, arXiv:1901.11033, Eqs. 18–25). Closed forms for df = 1 (Cauchy: tan(π(p−½))) and df = 2 ((2p−1)/√(2p(1−p))); other df use a monotone quantile table built at construction from the exact Student-t CDF (
jnp.interp, the NIFTy interpolation-operator pattern) as the seed for two Newton iterations on the exact CDF (_student_t_quantile()), reaching that CDF’s own accuracy floor (measured <=1.9e-10 absolute against scipystdtritfor|ξ| <= 4.5). The gradient is supplied analytically viajax.custom_jvp(dz/dp = 1/f_t(z), the inverse-function-theorem derivative) rather than by differentiating the Newton loop or the incomplete beta function through which the CDF is computed: the Jacobian a sampler needs, dθ/dξ = σ·φ(ξ)/f_t(z), is therefore exact and finite everywhere, including at ξ=0 wherebetainc’s own derivative is singular. Finite truncation bounds are applied in CDF space, giving a smooth bijection onto (lo, hi);standardizeinverts through the same exact CDF and the inverse-error-function normal quantile (erfinv), matching every other bounded prior family in this module.Heavy tails are preserved exactly; the previous variance-matched Gaussian approximation silently discarded them, which matters for the Leja et al. (2019) [tengri.StudentT-1] continuity-SFH log-SFR-ratio priors (StudentT(0, 0.3, df=2)) whose tails control burst flexibility.
References
[tengri.StudentT-1]Leja, J., et al. 2019, ApJ, 876, 3, “How to Measure Galaxy Star Formation Histories. II.”, arXiv:1811.03637, doi:10.3847/1538-4357/ab133c
Examples
>>> import jax.random >>> from tengri import StudentT >>> prior = StudentT(mu=0, sigma=1, df=3) # Robust prior >>> key = jax.random.PRNGKey(0) >>> sample = prior.sample(key) >>> print(f"Sample: {sample:.4f}")
- sample(key: Array) Array[source]¶
Draw a random sample from the Student’s t distribution.
- Parameters:
key (jax.Array) – JAX PRNG key for random sampling.
- Returns:
A single sample from Student’s t distribution truncated to [lo, hi].
- Return type:
ndarray
- standardize(theta: Array) Array[source]¶
Physical value → ξ (inverse of the exact quantile pushforward).
ξ = Φ⁻¹((F_t(z; df) − F_t(lo)) / (F_t(hi) − F_t(lo))), where z = (θ−μ)/σ. Φ⁻¹ is evaluated via the inverse error function (
erfinv), matching every other bounded prior family in this module (Uniform, Gaussian, LogUniform, LogNormal, Laplace all use this identical tail expression for Φ⁻¹, notndtri). Closed-form CDFs for df ∈ {1, 2}; exact CDF via_student_t_cdf()(jax.custom_jvp, analytic tangent f_t(z)) for other df.
- unstandardize(xi: Array) Array[source]¶
ξ ~ N(0,1) → t-distributed via the exact quantile pushforward.
θ = μ + σ·F⁻¹_t,df(p) with p = Φ(ξ) mapped through the truncation bounds in CDF space. Closed-form quantiles for df ∈ {1, 2} (df = 2 is the Leja+2019 / Tacchella+2022 continuity-SFH ratio prior); other df use
_student_t_quantile()(table guess + Newton refinement, exact analytic gradient).
Fixed¶
- class tengri.Fixed(value: float | str, description: str = '', *, units: str = '')[source]¶
Bases:
DistributionFixed (non-free) parameter with a constant value.
Represents a parameter that is not sampled or inferred. Used for holding model settings constant during fitting, or for categorical parameters that don’t vary. Fixed parameters contribute zero to the likelihood.
- Parameters:
value (float, int, or str) – The fixed value. Can be numeric (for quantitative parameters) or string (for categorical choices, e.g. “solar” for shock abundance).
- Returns:
Fixed instance with the given value.
- Return type:
- Variables:
Notes
JIT-compatible: yes;
unstandardize()returns the constant value regardless of the latent variable ξ.Inference: Fixed parameters are excluded from the inference set. They do not appear in the posterior and do not contribute to the loss or gradients.
Examples
>>> from tengri import Fixed >>> # Numerical fixed value >>> redshift = Fixed(0.1) >>> print(redshift.sample(None)) 0.1 >>> # Categorical fixed value >>> shock_abundance = Fixed("solar") >>> print(shock_abundance.sample(None)) solar
- property bounds: tuple[float, float] | tuple[None, None]¶
Return (value, value) for numeric, or (None, None) for string.
- Returns:
For numeric values: (value, value); for string values: (None, None).
- Return type:
- Raises:
ValueError – If this is an unresolved
Fixed(DEFAULT)token.
- property default: float | str¶
Return the fixed value; for
Fixed, value and default coincide.- Returns:
The fixed value.
- Return type:
- Raises:
ValueError – If this is an unresolved
Fixed(DEFAULT)token.
- property is_fixed: bool¶
Return True; this is a fixed (non-free) parameter.
- Returns:
Always True for Fixed distributions.
- Return type:
- log_prob(x: Array) Array[source]¶
Return 0.0 (fixed parameters have zero log-likelihood contribution).
- sample(key: Array) Array | str[source]¶
Return the fixed value (ignores random key).
- Parameters:
key (jax.Array) – JAX PRNG key (ignored for fixed parameters).
- Returns:
The constant fixed value.
- Return type:
- Raises:
ValueError – If this is an unresolved
Fixed(DEFAULT)token.
- unstandardize(xi: Array) Array | str[source]¶
Fixed: always returns the fixed value (ignores ξ).
- Parameters:
xi (float or array_like) – Standardized latent value (ignored for fixed parameters).
- Returns:
The constant fixed value.
- Return type:
- Raises:
ValueError – If this is an unresolved
Fixed(DEFAULT)token.
Laplace¶
- class tengri.Laplace(mu: float = 0.0, b: float = 1.0, lo: float = -inf, hi: float = inf, description: str = '', *, units: str = '', default: float | None = None)[source]¶
Bases:
DistributionLaplace (double-exponential) prior: a sparsity/robustness prior.
Heavier-tailed than a Gaussian and peaked at the location, the Laplace prior is the continuous analog of an L1 penalty (LASSO): it pulls weakly constrained parameters toward
muwhile tolerating occasional large excursions. Useful for coefficients expected to be near a default with a few genuine departures (e.g. per-band calibration offsets, sparse additive components).- Parameters:
mu (float) – Location (median and mode).
b (float) – Scale (diversity). Must be positive; variance is
2 b^2.lo (float, optional) – Lower truncation bound. Default:
-inf.hi (float, optional) – Upper truncation bound. Default:
+inf.description (str, optional) – Human-readable summary of the quantity, surfaced by
describe_parameterandspec.summary().units (str, optional) – Physical units, e.g.
"erg/s". Empty for dimensionless quantities.
- Variables:
Notes
JIT-compatible: yes; all operations use
jnpprimitives.The density is
\[\begin{split}p(x) = \\frac{1}{2b}\\exp\\!\\left(-\\frac{|x-\\mu|}{b}\\right).\end{split}\]Standardization: exact inverse-CDF pushforward \(\\theta = \\mu - b\\,\\mathrm{sgn}(p-\\tfrac12)\\, \\ln(1-2|p-\\tfrac12|)\) with \(p = \\Phi(\\xi)\) mapped through the truncation bounds in CDF space (Knollmüller & Enßlin 2019 [tengri.Laplace-1], Eqs. 18-25). The quantile is closed-form, so no interpolation table is needed.
Examples
>>> import jax.random >>> from tengri import Laplace >>> prior = Laplace(mu=0.0, b=0.1) # sparse calibration offset >>> sample = prior.sample(jax.random.PRNGKey(0))
References
[tengri.Laplace-1]Knollmüller, J. & Enßlin, T. A., “Metric Gaussian Variational Inference”, arXiv:1901.11033.
- log_prob(x: Array) Array[source]¶
Return the normalized (truncated) Laplace log-density, -inf outside.
- sample(key: Array) Array[source]¶
Draw one sample from the (truncated) Laplace via inverse-CDF.
- Parameters:
key (jax.Array) – JAX PRNG key for random sampling.
- Returns:
A single sample from Laplace(mu, b) truncated to [lo, hi].
- Return type:
ndarray
Sentinels¶
FREE and DEFAULT are not distributions. FREE is a singleton marker
used in the nested-dict grammar of tengri.SEDModel.build() to say “take
the registry’s default prior” for a parameter. DEFAULT is legal only as
the argument of tengri.Fixed, e.g. Fixed(DEFAULT), and says
“take the registry’s default value” instead.
Note the deliberate spelling difference from tengri.Fixed above:
Fixed(0.05) pins a parameter to the value you give it, whereas
Fixed(DEFAULT) pins it to the value the registry already carries.
They are different objects and are not interchangeable.
- tengri.parameters.sentinels.FREE
Sentinel marking a parameter to use the registry’s default prior.
Place it inside a group dict passed to
tengri.SEDModel.build(), either against one parameter or against the'all_params'wildcard, to defer the choice of prior to the registry:from tengri import SEDModel, FREE, Fixed, DEFAULT, Uniform model = SEDModel.build( ssp_data=ssp, observation=obs, sfh={"type": "dpl", "all_params": FREE, "beta": Uniform(1.0, 3.0)}, dust={"type": "two_component", "all_params": Fixed(DEFAULT)}, )
Here the double-power-law SFH parameters become free on their registry default priors, with
betafree on the explicit prior given instead.Identity is preserved across pickle, copy, and deepcopy operations.
Notes
'all_params': FREEfrees only the parameters a group declares with a default prior. Groups whose parameters default totengri.Fixedvalues (radio and shock) are unaffected by the wildcard; give those an explicit prior instead (e.g.shock={"frac": Uniform(0.0, 1.0)}).
- tengri.parameters.sentinels.DEFAULT
Sentinel marking the registry default as the value of a
Fixed(...)pin.Only legal as the argument of
tengri.Fixed, e.g.Fixed(DEFAULT), inside a group dict passed totengri.SEDModel.build()/tengri.parameters.parse_groups():from tengri import SEDModel, Fixed, DEFAULT model = SEDModel.build( ssp_data=ssp, observation=obs, met={"type": "delta", "logzsol": Fixed(DEFAULT)}, )
Fixed(0.3)pins the parameter at your own value,0.3;Fixed(DEFAULT)pins it at the registry default instead – the same value the'all_params'wildcard set toFixed(DEFAULT)would have used for that parameter. It resolves through the identical canonical-default resolver, never a second path.Bare
DEFAULT(not wrapped inFixed(...)) is not a legal value anywhere in a group dict; it raisestengri.config.exceptions.ParameterErrorpointing at theFixed(DEFAULT)spelling.Identity is preserved across pickle, copy, and deepcopy operations.