Skip to content

Inference

The latent space, likelihoods and the posterior shared by every backend. See Priors and inference for the workflow.

spectracles.inference.LatentSpace

The map from standard-normal latents ξ to a model's parameter values.

Parameters:

Name Type Description Default
model ShareModule

An unlocked ShareModule. Every free parameter must have a prior, and must be a plain Parameter (not a ConstrainedParameter).

required

Attributes:

Name Type Description
model

The model the latent space was built from. Fixed parameters and Known values keep the values they have here.

paths list[str]

The latent keys, i.e. the unique free parameter paths, in tree order.

priors dict[str, Prior]

Dict from path to Prior.

shapes dict[str, ShapeDtypeStruct]

Dict from path to jax.ShapeDtypeStruct of the latent.

size property

Total number of latent dimensions.

to_params(ξ)

The free parameters' values at ξ: prior.transform(ξ[path]) for each path.

Accepts one draw of the latents, draws stacked along a leading axis (the values are then stacked the same way), or a NIFTy Vector or Samples object. Keys are the latent paths; fixed parameters and Known values are not included. Works under jit/grad/vmap.

to_model(x, space='latent')

The model with every free parameter set from one draw.

Shared parameters are written once, at their parent path. Fixed parameters and Known values keep their values. Works under jit/grad/vmap.

Parameters:

Name Type Description Default
x Any

One draw, as a dict keyed by parameter path: latents ξ by default, or parameter values with space="params" (e.g. the output of to_params, or draws(samples).mean()).

required
space Literal['latent', 'params']

"latent" (default) or "params": the space x is in.

'latent'

from_model(model, fallback='zero')

The latents ξ that reproduce model's current free parameter values.

Needs each prior's inverse transform. For priors without one, and for values outside a prior's support (e.g. 0 for a LogNormal, which gives a non-finite latent), fallback decides: "zero" sets ξ = 0 (the prior median) and warns, listing those parameters; "raise" raises.

sample_prior_latent(key, n=None)

Draw latents from the prior, i.e. independent standard normals.

With n, returns n draws stacked along a leading axis of each array.

sample_prior_params(key, n=None)

Draw the free parameters' values from their priors.

With n, returns n draws stacked along a leading axis of each array.

sample_prior_model(key, n=None)

A model with parameters drawn from their priors; with n, a list of n models.

fix(values, space='params')

A new latent space with these parameters fixed at the given values.

The fixed parameters are no longer inferred: they drop out of paths, and every model this latent space makes holds them at these values. This latent space is unchanged, so the original free parameters stay available. A shared parameter can be named by any of its paths.

Parameters:

Name Type Description Default
values dict[str, Any]

Dict from parameter path to its value; a single number is broadcast to the parameter's shape.

required
space Literal['latent', 'params']

"params" (default) for parameter values, or "latent" for latents ξ (transformed by each parameter's prior).

'params'

zeros()

Latents at zero (every parameter at its prior median).

map_samples(fn, samples, space='latent')

Evaluate fn(model) at every sample, stacked along the samples' leading axes.

For any quantity derived from the model (a field on a grid, the predictions, a line ratio), this gives its value at each posterior sample; its posterior mean and spread are then the mean and std over the leading axis. Several leading axes, e.g. (chain, draw), are kept.

Parameters:

Name Type Description Default
fn Callable[[ShareModule], Any]

Takes a model and returns an array (or a pytree of arrays). Must be JAX-traceable: it runs under jax.vmap. The model it gets has shared values filled in (as by for_evaluation), so any part of it can be called.

required
samples Any

Stacked samples, as for posterior_summary.

required
space Literal['latent', 'params']

"latent" (default) or "params", as for posterior_summary.

'latent'

Returns:

Type Description
Draws

Draws of fn's output: .mean(), .std(), .quantile(q) etc.

Draws

summarise over the samples; .values holds the stacked outputs.

draws(samples, to='params', space='latent')

Samples as draws of the parameter values (default), the latents, or the model.

space says what the samples are; to says what you get out. For "params" and "latent", returns Draws: .mean(), .std(), .quantile(q) etc. give {path: summary}, and draws[path] is one parameter's draws. For "model", returns ModelDraws: call it, or any part of it, to get Draws of that part's output, e.g. draws(samples, to="model").field(grid).mean().

Parameters:

Name Type Description Default
samples Any

Stacked samples, as for posterior_summary.

required
to Literal['params', 'latent', 'model']

What to return draws of: "params" (default), "latent" or "model".

'params'
space Literal['latent', 'params']

The space samples are in: "latent" (default) or "params".

'latent'

posterior_summary(samples, space='latent', print_table=True, true_latents=None, true_params=None)

Summarise samples as parameter values (mean and std).

Parameters:

Name Type Description Default
samples Any

Samples with a leading sample axis: by default latents (a NIFTy Samples object, or a dict from path to stacked latents, as inference returns them).

required
space Literal['latent', 'params']

"latent" (default) or "params". Use "params" for samples that are already parameter values, e.g. from to_params or sample_prior_params; with the default they would be transformed a second time.

'latent'
print_table bool

Print a table like get_parameter_summary.

True
true_latents Any

Optionally, the true latents (one draw), e.g. for simulated data. Adds the truth and z = (mean - truth) / std.

None
true_params Any

The same, given as parameter values. Give at most one of true_latents and true_params. Entries for fixed parameters (e.g. ones fixed with fix) are ignored.

None

Returns:

Type Description
dict[str, Any]

Dict from path to {"mean": array, "std": array} of the parameter

dict[str, Any]

values, with "truth" and "z" added when a truth is given.

spectracles.inference.Likelihood

Bases: Module

Base class for likelihoods: the observed data and how a prediction is scored.

A subclass provides n_used (the number of data points used), compress (a prediction with the data's shape to the used data points, flat), log_likelihood (of a prediction, in pure JAX) and to_nifty (the equivalent NIFTy.re likelihood, taking the compressed prediction).

n_used abstractmethod property

Number of data points used.

compress(pred) abstractmethod

The used data points of a prediction with the data's shape, as a flat array.

log_likelihood(pred) abstractmethod

Log-likelihood of a prediction with the data's shape.

to_nifty() abstractmethod

The equivalent NIFTy.re likelihood, taking the compressed prediction.

spectracles.inference.GaussianLikelihood

Bases: Likelihood

Independent Gaussian noise with known inverse variance, and a mask.

Masked data points are removed when the likelihood is built, so their values and inverse variances (often NaN) never enter a value or a gradient. Data points with a non-finite value or inverse variance, or an inverse variance <= 0, are masked too.

Parameters:

Name Type Description Default
data ArrayLike

Observed data, any shape.

required
ivar ArrayLike

Inverse variance, same shape as data.

required
mask ArrayLike | None

Boolean, True where a data point is used. Defaults to all data points.

None

n_used property

Number of data points used.

compress(pred)

The used data points of a prediction with the data's shape, as a flat array.

log_likelihood(pred)

Gaussian log-likelihood of a prediction, with full normalisation.

normalised_residual(pred)

(data - pred) / σ on the used data points.

to_nifty()

The equivalent NIFTy.re likelihood: jft.Gaussian on the used data points.

Its input is the compressed prediction (see compress).

spectracles.inference.Posterior

A latent space, a forward model and a likelihood.

Parameters:

Name Type Description Default
latent LatentSpace

The model's latent space.

required
forward Callable[[ShareModule], Array]

Maps a model to a prediction with the data's shape, e.g. lambda m: jax.vmap(m, in_axes=(0, None))(λ, spatial_data).

required
likelihood Likelihood

The likelihood of the data given the prediction.

required

All methods taking ξ are pure JAX (jit, grad, vmap).

predict(ξ)

The forward model's prediction at ξ, with the data's shape.

log_prior(ξ)

The prior in latent space: -½|ξ|² (without the normalisation constant).

log_density(ξ)

The unnormalised log-posterior: log-likelihood - ½|ξ|².

fix(values, space='params')

A new posterior with these parameters fixed: LatentSpace.fix.

It has the same forward model and likelihood; this posterior is unchanged.

to_model(x, space='latent')

The model at one draw, given as latents or parameter values: LatentSpace.to_model.

map_samples(fn, samples, space='latent')

Evaluate fn(model) at every sample: LatentSpace.map_samples.

draws(samples, to='params', space='latent')

Samples as draws of the parameter values, latents or model: LatentSpace.draws.

summary(samples, space='latent', print_table=True, true_latents=None, true_params=None)

Summarise samples as parameter values: LatentSpace.posterior_summary.

value_and_grad(ξ)

log_density and its gradient with respect to ξ.

spectracles.inference.Draws

Draws of a quantity, stacked along leading sample axes, with summaries over them.

The quantity can be an array (e.g. a field on a grid) or a dict of arrays (e.g. parameter values keyed by path). The summaries reduce over the sample axes only, so draws.mean() has the quantity's own shape (or is a dict of them). Draws from several chains, stacked as (chain, draw, ...), reduce over both axes; axis= picks a subset, e.g. draws.mean(axis=1) for the mean of each chain. reduce(fn) applies any other statistic.

Parameters:

Name Type Description Default
values Any

The stacked draws: an array, or a dict of arrays.

required
n_sample_axes int

How many leading axes index the draws (default 1).

1

Attributes:

Name Type Description
values

The stacked draws, as given.

sample_shape property

The shape of the sample axes, e.g. (n_draws,) or (n_chains, n_draws).

n_draws property

The total number of draws (over all sample axes).

reduce(fn, axis=None)

Any statistic over the draws: fn(x, axis=axes) for each array.

fn reduces over the given axes, as numpy-style reductions do, e.g. draws.reduce(jnp.var) or draws.reduce(lambda x, axis: jnp.mean(x > 0, axis=axis)).

Parameters:

Name Type Description Default
fn Any

Called as fn(x, axis=axes), with axes a tuple of sample axes.

required
axis int | tuple[int, ...] | None

The sample axes to reduce over: all of them (default), or an index or tuple of indices into sample_shape, e.g. axis=1 on (chain, draw) draws gives one value per chain.

None

mean(axis=None)

The mean over the draws (over axis of the sample axes, if given).

std(axis=None)

The standard deviation over the draws (over axis, if given).

median(axis=None)

The median over the draws (over axis, if given).

quantile(q, axis=None)

Quantile(s) q (in [0, 1]) over the draws; several q add a leading axis.

__getitem__(key)

The draws of one entry, when the quantity is a dict (e.g. one parameter).

keys()

The keys, when the quantity is a dict.

spectracles.inference.ModelDraws

The model at every sample: call it, or any part of it, to get Draws.

models(data) evaluates the whole model at every sample; models.field(data) or models.line.flux(data) evaluates that component. Attribute paths are checked against the model straight away. Components are evaluated with shared values filled in (as by for_evaluation), so parts that hold shared parameters can be called. For parameter values, use posterior.draws(samples) instead.

Obtained with LatentSpace.draws(samples, to="model") (or the same on a Posterior); not constructed directly.

__call__(*args, **kwargs)

Call this part of the model at every sample, with these arguments.