Skip to content

Nonlinear inversion

The end-to-end coupled inversion over the emission rate (Gaussian or lognormal), whichever blocks the transport backend declares (the source position and wind of the Tier I plume, the geometry of the column plume), the background and per-instrument biases, through each instrument's averaging kernel or a JAX radiance operator. plumax builds the forward, the prior and the quality masks; vardax solves it (ThreeDVar with L-BFGS in the whitened control) and gives the Laplace posterior (LaplaceCovariance). A column-plume solve retrieves the line density \(q = Q / U\), and CoupledResult.with_wind applies the wind after it. Needs the assim extra. Tier IV.

inversion

Nonlinear end-to-end coupled inversion on vardax (implementation in plumax.coupled._src.inversion).

CoupledPrior dataclass

CoupledPrior(mean: Mapping[str, Float[Array, '*shape']], covariance: Float[Array, ' param'] | Float[Array, 'param param'])

Gaussian prior N(μ_θ, Σ_θ) on the stacked control, by named block.

The prior accepts any block name; :class:CoupledProblem checks the names and shapes against what its transport backend declares.

Attributes:

Name Type Description
mean Mapping[str, Float[Array, '*shape']]

Prior mean μ_θ of each block. Exactly one emission block (for the Tier I plume emission_rate or log_emission_rate, a scalar or one value per emission parameter), the backend's own blocks (for the Tier I plume location (x, y) [m] and wind (speed [m/s], direction [deg from North])), background (scalar) and biases (one per instrument).

covariance Float[Array, ' param'] | Float[Array, 'param param']

Σ_θ over the flattened control, in :attr:layout order: a vector of variances (diagonal) or a dense matrix.

Raises:

Type Description
ValueError

On a covariance that does not match the control.

size property

size: int

Length D_θ of the flattened control.

layout property

layout: tuple[tuple[str, int], ...]

(block, length) pairs in the flattened order (sorted by name).

log_emission property

log_emission: bool

Whether the emission is lognormal (controlled through log Q).

from_std classmethod

from_std(mean: Mapping[str, Float[Array, '*shape'] | float], std: Mapping[str, Float[Array, '*shape'] | float]) -> CoupledPrior

A diagonal prior from per-block means and standard deviations.

Σ_θ = diag(σ²), each block's σ broadcast to the block's shape.

Parameters:

Name Type Description Default
mean Mapping[str, Float[Array, '*shape'] | float]

Prior mean μ_θ of each block.

required
std Mapping[str, Float[Array, '*shape'] | float]

Prior standard deviation σ of each block, same keys.

required

Returns:

Type Description
CoupledPrior

The prior.

Raises:

Type Description
ControlBlockError

If the keys differ, a deviation does not broadcast to its block's shape, or a deviation is not positive.

Source code in src/plumax/coupled/_src/inversion.py
@classmethod
def from_std(
    cls,
    mean: Mapping[str, Float[Array, "*shape"] | float],
    std: Mapping[str, Float[Array, "*shape"] | float],
) -> CoupledPrior:
    """A diagonal prior from per-block means and standard deviations.

    Σ_θ = diag(σ²), each block's σ broadcast to the block's shape.

    Args:
        mean: Prior mean μ_θ of each block.
        std: Prior standard deviation σ of each block, same keys.

    Returns:
        The prior.

    Raises:
        ControlBlockError: If the keys differ, a deviation does not broadcast
            to its block's shape, or a deviation is not positive.
    """
    # a (n, n) entry is a dense covariance to from_blocks, never a deviation
    for name in sorted(set(mean) & set(std)):
        shape = np.shape(mean[name])
        if not _broadcasts(np.shape(std[name]), shape):
            raise ControlBlockError(
                f"CoupledPrior.from_std: `{name}` has mean shape {shape}, so "
                f"its standard deviation must broadcast to it; got "
                f"{np.shape(std[name])}. Pass a covariance to from_blocks."
            )
    # the all-deviations case of from_blocks
    return cls.from_blocks(mean, std)

from_blocks classmethod

from_blocks(mean: Mapping[str, Float[Array, '*shape'] | float], covariance: Mapping[str, Float[Array, '*block'] | float]) -> CoupledPrior

A block-diagonal prior, Σ_θ = blockdiag(Σ₁, …, Σ_B).

A block's entry is a standard deviation σ (a scalar, or one per element of the block), giving Σ_b = diag(σ²), or a dense (n, n) covariance for a block of n elements, such as a gauss_plume.CentrelinePrior matrix. With only standard deviations the prior is diagonal and equals :meth:from_std.

Algorithm
  1. Order the blocks as :attr:layout does (by name).
  2. Turn each standard deviation into a diagonal block.
  3. Place the blocks on the diagonal of Σ_θ.

Parameters:

Name Type Description Default
mean Mapping[str, Float[Array, '*shape'] | float]

Prior mean μ_θ of each block.

required
covariance Mapping[str, Float[Array, '*block'] | float]

For each block, a standard deviation (scalar or one per element) or a dense covariance block.

required

Returns:

Type Description
CoupledPrior

The prior.

Raises:

Type Description
ControlBlockError

If the keys differ, a dense block does not match its mean, or a standard deviation is not positive.

Examples:

A scalar block and a dense block of two:

>>> import jax.numpy as jnp
>>> prior = CoupledPrior.from_blocks(
...     mean={"background": 0.0, "centreline": jnp.zeros(2)},
...     covariance={
...         "background": 1e-4,
...         "centreline": jnp.array([[4.0, 1.0], [1.0, 9.0]]),
...     },
... )
>>> prior.covariance.shape
(3, 3)
>>> bool(jnp.allclose(prior.covariance[0, 0], 1e-8))
True
Source code in src/plumax/coupled/_src/inversion.py
@classmethod
def from_blocks(
    cls,
    mean: Mapping[str, Float[Array, "*shape"] | float],
    covariance: Mapping[str, Float[Array, "*block"] | float],
) -> CoupledPrior:
    """A block-diagonal prior, Σ_θ = blockdiag(Σ₁, …, Σ_B).

    A block's entry is a standard deviation σ (a scalar, or one per
    element of the block), giving Σ_b = diag(σ²), or a dense ``(n, n)``
    covariance for a block of n elements, such as a
    ``gauss_plume.CentrelinePrior`` matrix. With only standard deviations
    the prior is diagonal and equals :meth:`from_std`.

    Algorithm:
        1. Order the blocks as :attr:`layout` does (by name).
        2. Turn each standard deviation into a diagonal block.
        3. Place the blocks on the diagonal of Σ_θ.

    Args:
        mean: Prior mean μ_θ of each block.
        covariance: For each block, a standard deviation (scalar or one
            per element) or a dense covariance block.

    Returns:
        The prior.

    Raises:
        ControlBlockError: If the keys differ, a dense block does not
            match its mean, or a standard deviation is not positive.

    Examples:
        A scalar block and a dense block of two:

        >>> import jax.numpy as jnp
        >>> prior = CoupledPrior.from_blocks(
        ...     mean={"background": 0.0, "centreline": jnp.zeros(2)},
        ...     covariance={
        ...         "background": 1e-4,
        ...         "centreline": jnp.array([[4.0, 1.0], [1.0, 9.0]]),
        ...     },
        ... )
        >>> prior.covariance.shape
        (3, 3)
        >>> bool(jnp.allclose(prior.covariance[0, 0], 1e-8))
        True
    """
    if set(mean) != set(covariance):
        raise ControlBlockError(
            "CoupledPrior.from_blocks: `mean` and `covariance` keys differ: "
            f"{sorted(mean)} against {sorted(covariance)}."
        )
    means = {name: jnp.asarray(value, dtype=float) for name, value in mean.items()}
    blocks, dense = [], False
    for name in sorted(means):
        shape = means[name].shape
        size = int(np.prod(shape, dtype=int))
        entry = jnp.asarray(covariance[name], dtype=float)
        if _broadcasts(entry.shape, shape):
            # σ per element
            broadcast_std = jnp.broadcast_to(entry, shape)
            std = einx.id("... -> (...)", broadcast_std)
            require_positive(
                f"std[{name}]",
                std,
                caller="CoupledPrior.from_blocks",
                error=ControlBlockError,
            )
            # Σ_b = diag(σ²)
            blocks.append(jnp.square(std))
        elif entry.shape == (size, size):
            # Σ_b dense
            blocks.append(entry)
            dense = True
        else:
            raise ControlBlockError(
                f"CoupledPrior.from_blocks: `{name}` has mean shape {shape}, so "
                f"its covariance must be a standard deviation broadcastable to "
                f"{shape} or a ({size}, {size}) matrix; got {entry.shape}."
            )
    if not dense:
        # Σ_θ = diag(σ²)
        return cls(mean=means, covariance=jnp.concatenate(blocks))
    matrices = [jnp.diag(block) if block.ndim == 1 else block for block in blocks]
    # Σ_θ = blockdiag(Σ₁, …, Σ_B)
    full = jax.scipy.linalg.block_diag(*matrices)
    return cls(mean=means, covariance=full)

flatten

flatten() -> tuple[Float[Array, ' param'], Callable[[jax.Array], dict[str, jax.Array]]]

μ_θ as one vector, and the map from such a vector back to blocks.

Source code in src/plumax/coupled/_src/inversion.py
def flatten(
    self,
) -> tuple[Float[Array, " param"], Callable[[jax.Array], dict[str, jax.Array]]]:
    """μ_θ as one vector, and the map from such a vector back to blocks."""
    means = {
        name: jnp.asarray(value, dtype=float) for name, value in self.mean.items()
    }
    return ravel_pytree(means)

cholesky

cholesky() -> Float[Array, 'param param']

L with Σ_θ = L Lᵀ (√σ² on the diagonal for a diagonal prior).

Source code in src/plumax/coupled/_src/inversion.py
def cholesky(self) -> Float[Array, "param param"]:
    """L with Σ_θ = L Lᵀ (√σ² on the diagonal for a diagonal prior)."""
    covariance = jnp.asarray(self.covariance, dtype=float)
    if covariance.ndim == 1:
        # L = diag(σ)
        return jnp.diag(jnp.sqrt(covariance))
    return gaussx_linalg.safe_cholesky(
        lx.MatrixLinearOperator(covariance, PSD_TAGS)
    )

covariance_operator

covariance_operator() -> lx.AbstractLinearOperator

Σ_θ as an operator on the flat (D_θ,) control.

Source code in src/plumax/coupled/_src/inversion.py
def covariance_operator(self) -> lx.AbstractLinearOperator:
    """Σ_θ as an operator on the flat ``(D_θ,)`` control."""
    covariance = jnp.asarray(self.covariance, dtype=float)
    if covariance.ndim == 1:
        return lx.DiagonalLinearOperator(covariance)
    return lx.MatrixLinearOperator(covariance, PSD_TAGS)

CoupledProblem dataclass

CoupledProblem(forward: CoupledForward, prior: CoupledPrior, observations: Mapping[str, Float[Array, '*shape']], radiance_ops: Mapping[str, RadianceOperator] = dict(), radiance_variance: Mapping[str, Float[Array, '*shape'] | float] = dict())

The coupled forward, its prior and every instrument's observations.

Column instruments are observed through their averaging kernel (the CoupledForward responses); an instrument named in radiance_ops is observed through that operator instead, applied to its column (bias included). Masks and variance inflation come from each instrument (coupled.quality.apply_quality).

Attributes:

Name Type Description
forward CoupledForward

The coupled forward. A backend that is an AbstractControlledSource (the Tier I PlumeSource, the column plume) recomputes its response at each control that holds one of its declared blocks; other backends keep their precomputed responses.

prior CoupledPrior

Prior on the control.

observations Mapping[str, Float[Array, '*shape']]

Observations by instrument name: (n_obs,) columns, or (n_obs, n_channels) radiances.

radiance_ops Mapping[str, RadianceOperator]

JAX radiance operators by instrument name.

radiance_variance Mapping[str, Float[Array, '*shape'] | float]

Radiance error variance by instrument name, a scalar or (n_obs, n_channels).

Raises:

Type Description
ControlBlockError

If the prior names a block the backend does not declare, holds other than one emission block, or gives a block the wrong shape.

ValueError

On missing or extra observations or a radiance operator without a variance.

emission_block property

emission_block: str

The emission block the prior holds, one of the backend's.

responses

responses(control: Mapping[str, Array]) -> list[jax.Array]

Unit-emission response of each instrument at this control.

Source code in src/plumax/coupled/_src/inversion.py
def responses(self, control: Mapping[str, jax.Array]) -> list[jax.Array]:
    """Unit-emission response of each instrument at this control."""
    source = self.forward.source
    if not isinstance(source, AbstractControlledSource):
        return list(self.forward.responses)
    if not any(name in control for name in source.control_blocks):
        return list(self.forward.responses)
    return [
        source.response_at(instrument, control)
        for instrument in self.forward.instruments
    ]

predict

predict(control: Mapping[str, Array]) -> dict[str, jax.Array]

h_i(θ) for every instrument, by name.

Parameters:

Name Type Description Default
control Mapping[str, Array]

The control, by block (as :meth:CoupledPrior.flatten unflattens it).

required

Returns:

Type Description
dict[str, Array]

Columns (n_obs,), or radiances (n_obs, n_channels).

Source code in src/plumax/coupled/_src/inversion.py
def predict(self, control: Mapping[str, jax.Array]) -> dict[str, jax.Array]:
    """h_i(θ) for every instrument, by name.

    Args:
        control: The control, by block (as :meth:`CoupledPrior.flatten`
            unflattens it).

    Returns:
        Columns ``(n_obs,)``, or radiances ``(n_obs, n_channels)``.
    """
    block = self.emission_block
    if block.startswith("log_"):
        # A line-search trial far from the data can overflow exp, and
        # lineax raises on the non-finite residual; capping log Q at 50
        # (Q ≈ 5e21 kg/s) keeps the trial cost finite, so the search
        # backtracks instead.
        log_emission = jnp.minimum(control[block], _LOG_EMISSION_CAP)
        # Q = exp(log Q)
        emission = jnp.exp(log_emission)
    else:
        emission = control[block]
    background = control.get(
        "background", jnp.asarray(self.forward.source.background, dtype=float)
    )
    num_instruments = len(self.forward.instruments)
    biases = control.get("biases", jnp.zeros(num_instruments))
    predictions = {}
    for index, (instrument, response) in enumerate(
        zip(self.forward.instruments, self.responses(control), strict=True)
    ):
        # c_i = Q r_i + c_bg + bias_i
        column = _scale_response(response, emission) + background + biases[index]
        operator = self.radiance_ops.get(instrument.name)
        predictions[instrument.name] = (
            column if operator is None else operator.predict(column)
        )
    return predictions

predict_stacked

predict_stacked(control: Mapping[str, Array]) -> jax.Array

Every instrument's prediction, flattened and stacked, shape (D_y,).

Source code in src/plumax/coupled/_src/inversion.py
def predict_stacked(self, control: Mapping[str, jax.Array]) -> jax.Array:
    """Every instrument's prediction, flattened and stacked, shape ``(D_y,)``."""
    predictions = self.predict(control)
    flat_predictions = [
        einx.id("... -> (...)", predictions[instrument.name])
        for instrument in self.forward.instruments
    ]
    return jnp.concatenate(flat_predictions)

stacked_observations

stacked_observations() -> StackedObservations

Observations, masks and Σ_ε stacked like :meth:predict_stacked.

A radiance pixel's mask and variance inflation apply to all its channels. Masked values are zero, so a sum over the stacked residuals (fit_diagnostics) needs no mask.

Source code in src/plumax/coupled/_src/inversion.py
def stacked_observations(self) -> StackedObservations:
    """Observations, masks and Σ_ε stacked like :meth:`predict_stacked`.

    A radiance pixel's mask and variance inflation apply to all its
    channels. Masked values are zero, so a sum over the stacked residuals
    (``fit_diagnostics``) needs no mask.
    """
    observations, masks, variances = [], [], []
    for instrument in self.forward.instruments:
        observation = jnp.asarray(self.observations[instrument.name], dtype=float)
        mask = instrument.observation_mask()
        if instrument.name in self.radiance_ops:
            num_channels = observation.shape[-1]
            variance = jnp.broadcast_to(
                jnp.asarray(self.radiance_variance[instrument.name], dtype=float),
                observation.shape,
            )
            if instrument.variance_inflation is not None:
                inflation = jnp.asarray(instrument.variance_inflation, dtype=float)
                variance = einx.multiply(
                    "obs channel, obs -> obs channel", variance, inflation
                )
            mask = einx.id("obs -> obs channel", mask, channel=num_channels)
        else:
            variance = instrument.observation_variance()
        observations.append(observation)
        masks.append(mask)
        variances.append(variance)
    # the shape check and the masked-pixel zero live in stack_observations
    return stack_observations(
        self.forward.instruments, observations, masks=masks, variances=variances
    )

CoupledResult dataclass

CoupledResult(map_estimate: dict[str, Array], std: dict[str, Array] | None, mean: Array, covariance: Array | None, emission_rate: Array, emission_std: Array, converged: bool, n_steps: int, cost: float, per_instrument_residuals: dict[str, Array], pixels_used: dict[str, int], prior: CoupledPrior | None = None, line_density: Array | None = None, line_density_std: Array | None = None, wind: tuple[float, float] | None = None, emission_block: str | None = None)

MAP and Laplace posterior of the coupled inversion.

emission_rate and emission_std are the posterior mean and standard deviation of Q (population.PerEventPosterior): for a lognormal Q the lognormal moments of the Laplace marginal on log Q, E[Q] = exp(μ + σ²/2) and sd[Q] = E[Q] √(exp(σ²) − 1).

A column-plume solve retrieves the line density q = Q / U instead, with the same moments in line_density and line_density_std; its emission_rate and emission_std are NaN until :meth:with_wind supplies the wind.

Attributes:

Name Type Description
map_estimate dict[str, Array]

MAP θ* by block (log_emission_rate stays in logs).

std dict[str, Array] | None

Laplace posterior standard deviation by block (None without the posterior).

mean Array

MAP θ* flattened, in CoupledPrior.layout order.

covariance Array | None

Laplace covariance Σ_θ|y, None without the posterior.

emission_rate Array

Posterior mean of Q.

emission_std Array

Posterior standard deviation of Q (NaN without the posterior).

converged bool

optimistix's success flag for the L-BFGS solve.

n_steps int

Iterations taken.

cost float

𝒥 at the MAP, in the whitened control.

per_instrument_residuals dict[str, Array]

y_i − h_i(θ*) by instrument, NaN where masked.

pixels_used dict[str, int]

Pixels each instrument contributed at full weight.

prior CoupledPrior | None

The prior the solve used (None when built by hand).

line_density Array | None

Posterior mean of q [kg m⁻¹]; None for a backend that retrieves Q.

line_density_std Array | None

Posterior standard deviation of q (NaN without the posterior).

wind tuple[float, float] | None

(U, s_U) [m s⁻¹] that :meth:with_wind applied, or None.

emission_block str | None

The emission block the solve fitted, as its backend declared it; None for a result built by hand, whose block is then read from the names in map_estimate and prior. A name that starts with log_ is lognormal in the payload.

For a scalar Q it also carries the Tier V per-event payload (population.PerEventPosterior): draws of Q from the Laplace marginal of its block, N(Q, σ²) or log Q ~ N(log Q, σ²) for a lognormal Q, and the log-density of that block's prior marginal, both exact for the Gaussian laws on θ. For a line density these need the wind: log Q ~ N(μ_q + μ_U, σ_q² + σ_U²) for the lognormal wind of :meth:with_wind.

with_wind

with_wind(*, speed: float, speed_std: float) -> CoupledResult

The same result with the emission rate filled in, Q = q U.

For a lognormal wind independent of the fit, with σ_U² = log(1 + s_U² / U²) and μ_U = log U − σ_U² / 2, a lognormal line density gives log Q ~ N(μ_q + μ_U, σ_q² + σ_U²). The moments are those of the product of independent q and U, which equal that law's:

E[Q] = E[q] U,
Var[Q] = sd[q]² s_U² + sd[q]² U² + E[q]² s_U².

Parameters:

Name Type Description Default
speed float

Mean wind speed U [m s⁻¹].

required
speed_std float

Its standard deviation s_U [m s⁻¹].

required

Returns:

Type Description
CoupledResult

The result with emission_rate, emission_std and wind

CoupledResult

set.

Raises:

Type Description
ParameterError

If speed is not positive or speed_std is negative.

PayloadError

If the result holds no line density.

Examples:

With no spread in the wind, Q is q times the speed:

>>> import jax.numpy as jnp
>>> result = CoupledResult(
...     map_estimate={"log_line_density": jnp.log(0.1)},
...     std={"log_line_density": jnp.asarray(0.15)},
...     mean=jnp.log(0.1)[None],
...     covariance=None,
...     emission_rate=jnp.asarray(jnp.nan),
...     emission_std=jnp.asarray(jnp.nan),
...     converged=True,
...     n_steps=1,
...     cost=0.0,
...     per_instrument_residuals={},
...     pixels_used={},
...     line_density=jnp.asarray(0.1),
...     line_density_std=jnp.asarray(0.015),
... )
>>> rate = result.with_wind(speed=3.5, speed_std=0.0)
>>> bool(jnp.allclose(rate.emission_rate, 0.35))
True
Source code in src/plumax/coupled/_src/inversion.py
def with_wind(self, *, speed: float, speed_std: float) -> CoupledResult:
    """The same result with the emission rate filled in, Q = q U.

    For a lognormal wind independent of the fit, with
    σ_U² = log(1 + s_U² / U²) and μ_U = log U − σ_U² / 2, a lognormal line
    density gives log Q ~ N(μ_q + μ_U, σ_q² + σ_U²). The moments are those
    of the product of independent q and U, which equal that law's:

        E[Q] = E[q] U,
        Var[Q] = sd[q]² s_U² + sd[q]² U² + E[q]² s_U².

    Args:
        speed: Mean wind speed U [m s⁻¹].
        speed_std: Its standard deviation s_U [m s⁻¹].

    Returns:
        The result with ``emission_rate``, ``emission_std`` and ``wind``
        set.

    Raises:
        ParameterError: If ``speed`` is not positive or ``speed_std`` is
            negative.
        PayloadError: If the result holds no line density.

    Examples:
        With no spread in the wind, Q is q times the speed:

        >>> import jax.numpy as jnp
        >>> result = CoupledResult(
        ...     map_estimate={"log_line_density": jnp.log(0.1)},
        ...     std={"log_line_density": jnp.asarray(0.15)},
        ...     mean=jnp.log(0.1)[None],
        ...     covariance=None,
        ...     emission_rate=jnp.asarray(jnp.nan),
        ...     emission_std=jnp.asarray(jnp.nan),
        ...     converged=True,
        ...     n_steps=1,
        ...     cost=0.0,
        ...     per_instrument_residuals={},
        ...     pixels_used={},
        ...     line_density=jnp.asarray(0.1),
        ...     line_density_std=jnp.asarray(0.015),
        ... )
        >>> rate = result.with_wind(speed=3.5, speed_std=0.0)
        >>> bool(jnp.allclose(rate.emission_rate, 0.35))
        True
    """
    require_positive("speed", speed, caller="with_wind")
    require_positive("speed_std", speed_std, caller="with_wind", allow_zero=True)
    if self.line_density is None or self.line_density_std is None:
        raise PayloadError(
            "CoupledResult.with_wind: this result retrieved Q, not the line "
            "density q = Q / U; only a column-plume solve needs a wind."
        )
    # E[Q] = E[q] U
    mean = self.line_density * speed
    # sd[q]² (s_U² + U²)
    spread_of_line_density = jnp.square(self.line_density_std) * (
        speed_std**2 + speed**2
    )
    # E[q]² s_U²
    spread_of_wind = jnp.square(self.line_density) * speed_std**2
    # sd[Q] = √(sd[q]² s_U² + sd[q]² U² + E[q]² s_U²)
    deviation = jnp.sqrt(spread_of_line_density + spread_of_wind)
    return dataclasses.replace(
        self,
        emission_rate=mean,
        emission_std=deviation,
        wind=(float(speed), float(speed_std)),
    )

samples

samples(key: Array, n: int) -> Float[Array, ' member']

n draws of Q from the Laplace marginal of its block.

For a line density, Q = q U with U from the lognormal wind of :meth:with_wind.

Raises:

Type Description
PayloadError

Without the Laplace posterior, for a vector Q, or for a line density with no wind applied.

Source code in src/plumax/coupled/_src/inversion.py
def samples(self, key: jax.Array, n: int) -> Float[Array, " member"]:
    """n draws of Q from the Laplace marginal of its block.

    For a line density, Q = q U with U from the lognormal wind of
    :meth:`with_wind`.

    Raises:
        PayloadError: Without the Laplace posterior, for a vector Q, or
            for a line density with no wind applied.
    """
    block = self._payload_block(self.map_estimate)
    if self.std is None:
        raise PayloadError(
            "CoupledResult.samples needs the Laplace posterior; solve with "
            "laplace=True."
        )
    center = self.map_estimate[block]
    spread = self.std[block]
    require_scalar(center, owner="CoupledResult", method="samples")
    if block in _LINE_DENSITY_BLOCKS:
        wind = self._wind_law("samples")
        if block == "log_line_density":
            # log Q ~ N(μ_q + μ_U, σ_q² + σ_U²)
            law = LognormalEmission(
                center + wind.loc, jnp.hypot(spread, wind.scale)
            )
            return law.sample(key, n)
        line_key, wind_key = jax.random.split(key)
        # Q = q U
        line_density = GaussianEmission(center, spread).sample(line_key, n)
        return line_density * wind.sample(wind_key, n)
    if block.startswith("log_"):
        return LognormalEmission(center, spread).sample(key, n)
    return GaussianEmission(center, spread).sample(key, n)

prior_logpdf

prior_logpdf(q: Array) -> jax.Array

log π(Q) of the prior marginal of Q's block.

For a log line density the prior's (μ_q,0, σ²_q,0) take the place of the posterior's: log Q ~ N(μ_q,0 + μ_U, σ²_q,0 + σ_U²).

Raises:

Type Description
PayloadError

Without the prior, for a vector Q, for a line density with no wind applied, or for a linear line density, whose product with a lognormal wind has no closed-form density.

Source code in src/plumax/coupled/_src/inversion.py
def prior_logpdf(self, q: jax.Array) -> jax.Array:
    """log π(Q) of the prior marginal of Q's block.

    For a log line density the prior's (μ_q,0, σ²_q,0) take the place of
    the posterior's: log Q ~ N(μ_q,0 + μ_U, σ²_q,0 + σ_U²).

    Raises:
        PayloadError: Without the prior, for a vector Q, for a line density
            with no wind applied, or for a linear line density, whose
            product with a lognormal wind has no closed-form density.
    """
    if self.prior is None:
        raise PayloadError(
            "CoupledResult.prior_logpdf: this result carries no prior; build "
            "it with solve_coupled."
        )
    block = self._payload_block(self.prior.mean)
    center = jnp.asarray(self.prior.mean[block], dtype=float)
    require_scalar(center, owner="CoupledResult", method="prior_logpdf")
    # Q's diagonal entry of Σ_θ, at its offset in the flattened layout
    offset = 0
    for name, length in self.prior.layout:
        if name == block:
            break
        offset += length
    covariance = jnp.asarray(self.prior.covariance, dtype=float)
    if covariance.ndim == 1:
        variance = covariance[offset]
    else:
        variance = covariance[offset, offset]
    if block == "line_density":
        raise PayloadError(
            "CoupledResult.prior_logpdf: a Gaussian line density times a "
            "lognormal wind has no closed-form density; fit "
            "log_line_density instead."
        )
    if block == "log_line_density":
        wind = self._wind_law("prior_logpdf")
        # log Q ~ N(μ_q,0 + μ_U, σ²_q,0 + σ_U²)
        law = LognormalEmission(
            center + wind.loc, jnp.hypot(jnp.sqrt(variance), wind.scale)
        )
        return law.log_prob(q)
    if block.startswith("log_"):
        return LognormalEmission(center, jnp.sqrt(variance)).log_prob(q)
    return GaussianEmission(center, jnp.sqrt(variance)).log_prob(q)

RadianceOperator

Bases: Protocol

A JAX radiance operator: column enhancement → per-receptor channels.

RadianceObservationOperator, LinearisedRadianceOperator and LayeredRadianceOperator qualify.

predict

predict(column_enhancement: Array) -> jax.Array

Radiance per receptor and channel, shape (n_obs, n_channels).

Source code in src/plumax/coupled/_src/inversion.py
def predict(self, column_enhancement: jax.Array) -> jax.Array:
    """Radiance per receptor and channel, shape ``(n_obs, n_channels)``."""
    ...

plume_response

plume_response(source: PlumeSource, instrument: Instrument, location: Float[Array, ' 2'], wind: Float[Array, ' 2']) -> Float[Array, ' obs']

Tier I unit-emission column at a traced source position and wind.

coupled.column_response with the horizontal position and the wind (speed, meteorological direction) as JAX arrays, so the coupled cost can differentiate through them. The source height, stability class and levels stay those of source.

Parameters:

Name Type Description Default
source PlumeSource

The Tier I source (height, stability, levels).

required
instrument Instrument

The observing instrument.

required
location Float[Array, ' 2']

Source (x, y) [m].

required
wind Float[Array, ' 2']

(speed [m/s], direction [deg from North]).

required

Returns:

Type Description
Float[Array, ' obs']

The unit-emission column through the averaging kernel.

Source code in src/plumax/coupled/_src/forward.py
def plume_response(
    source: PlumeSource,
    instrument: Instrument,
    location: Float[Array, " 2"],
    wind: Float[Array, " 2"],
) -> Float[Array, " obs"]:
    """Tier I unit-emission column at a traced source position and wind.

    ``coupled.column_response`` with the horizontal position and the wind
    (speed, meteorological direction) as JAX arrays, so the coupled cost can
    differentiate through them. The source height, stability class and levels
    stay those of ``source``.

    Args:
        source: The Tier I source (height, stability, levels).
        instrument: The observing instrument.
        location: Source ``(x, y)`` [m].
        wind: ``(speed [m/s], direction [deg from North])``.

    Returns:
        The unit-emission column through the averaging kernel.
    """
    levels = jnp.asarray(source.column_z, dtype=float)
    receptors = jnp.asarray(instrument.receptors, dtype=float)
    num_levels = levels.shape[0]
    # every receptor at every level, level fastest
    easting = einx.id("obs -> (obs level)", receptors[:, 0], level=num_levels)
    northing = einx.id("obs -> (obs level)", receptors[:, 1], level=num_levels)
    height = einx.id("level -> (obs level)", levels, obs=receptors.shape[0])
    wind_u, wind_v = wind_components(wind[0], wind[1])
    concentration = plume_concentration_vmap(
        easting,
        northing,
        height,
        location[0],
        location[1],
        source.location[2],
        wind_u,
        wind_v,
        1.0,
        get_dispersion_params(source.stability_class),
    )
    profiles = einx.id("(obs level) -> obs level", concentration, level=num_levels)
    observation = ColumnObservation.trapezoid(levels, averaging_kernel=instrument.ak)
    return observation.column(profiles)

solve_coupled

solve_coupled(problem: CoupledProblem, *, initial: Mapping[str, Float[Array, '*shape'] | float] | None = None, method: Literal['lbfgs', 'gauss_newton'] = 'lbfgs', laplace: bool = True, rtol: float = 1e-08, atol: float = 1e-10, max_steps: int = 200) -> CoupledResult

MAP and Laplace posterior of the coupled problem, on vardax.

θ = argmin 𝒥(θ), Σ_θ|y = (Σ_θ⁻¹ + J_hᵀ Σ_ε⁻¹ J_h)⁻¹ at θ.

Algorithm
  1. Flatten the prior to μ_θ, factor Σ_θ = L Lᵀ.
  2. Stack observations, masks and Σ_ε over the instruments.
  3. vardax.ThreeDVar with the stacked forward as a CallableObs on the flat (D_θ,) control. "lbfgs" minimises 𝒥 in the whitened control θ = μ_θ + L χ from χ₀ = L⁻¹ (θ₀ − μ_θ), where θ₀ is initial (μ_θ by default); "gauss_newton" solves the whitened residuals with argminax.solve.GaussNewtonCG from μ_θ.
  4. vardax.LaplaceCovariance at θ*, materialised.

Parameters:

Name Type Description Default
problem CoupledProblem

The coupled problem.

required
initial Mapping[str, Float[Array, '*shape'] | float] | None

Control the minimiser starts from, by block; blocks left out start at the prior mean. The prior is not changed, so the cost is the same from every start. L-BFGS only.

None
method Literal['lbfgs', 'gauss_newton']

"lbfgs" or "gauss_newton". Gauss–Newton starts at the prior mean and reaches the same MAP in fewer steps. It is undamped, so from a prior mean far from the MAP it can overshoot and stop unconverged; CoupledResult.converged reports that.

'lbfgs'
laplace bool

Also compute the Laplace posterior.

True
rtol float

Relative tolerance of the minimiser.

1e-08
atol float

Absolute tolerance of the minimiser.

1e-10
max_steps int

Iteration cap.

200

Returns:

Name Type Description
The CoupledResult

class:CoupledResult.

Raises:

Type Description
NotImplementedError

For method="gauss_newton" with initial: vardax starts a least-squares solve only at the prior mean (jejjohnson/vardax#315).

ValueError

For an unknown method.

ControlBlockError

If initial names a block the prior lacks, or one of the wrong shape.

ImportError

Without the assim extra.

Source code in src/plumax/coupled/_src/inversion.py
def solve_coupled(
    problem: CoupledProblem,
    *,
    initial: Mapping[str, Float[Array, "*shape"] | float] | None = None,
    method: Literal["lbfgs", "gauss_newton"] = "lbfgs",
    laplace: bool = True,
    rtol: float = 1e-8,
    atol: float = 1e-10,
    max_steps: int = 200,
) -> CoupledResult:
    """MAP and Laplace posterior of the coupled problem, on vardax.

    θ* = argmin 𝒥(θ),   Σ_θ|y = (Σ_θ⁻¹ + J_hᵀ Σ_ε⁻¹ J_h)⁻¹ at θ*.

    Algorithm:
        1. Flatten the prior to μ_θ, factor Σ_θ = L Lᵀ.
        2. Stack observations, masks and Σ_ε over the instruments.
        3. ``vardax.ThreeDVar`` with the stacked forward as a ``CallableObs``
           on the flat ``(D_θ,)`` control. ``"lbfgs"`` minimises 𝒥 in the
           whitened control θ = μ_θ + L χ from χ₀ = L⁻¹ (θ₀ − μ_θ), where θ₀
           is ``initial`` (μ_θ by default); ``"gauss_newton"`` solves the
           whitened residuals with ``argminax.solve.GaussNewtonCG`` from μ_θ.
        4. ``vardax.LaplaceCovariance`` at θ*, materialised.

    Args:
        problem: The coupled problem.
        initial: Control the minimiser starts from, by block; blocks left
            out start at the prior mean. The prior is not changed, so the
            cost is the same from every start. L-BFGS only.
        method: ``"lbfgs"`` or ``"gauss_newton"``. Gauss–Newton starts at the
            prior mean and reaches the same MAP in fewer steps. It is
            undamped, so from a prior mean far from the MAP it can overshoot
            and stop unconverged; ``CoupledResult.converged`` reports that.
        laplace: Also compute the Laplace posterior.
        rtol: Relative tolerance of the minimiser.
        atol: Absolute tolerance of the minimiser.
        max_steps: Iteration cap.

    Returns:
        The :class:`CoupledResult`.

    Raises:
        NotImplementedError: For ``method="gauss_newton"`` with ``initial``:
            vardax starts a least-squares solve only at the prior mean
            (jejjohnson/vardax#315).
        ValueError: For an unknown ``method``.
        ControlBlockError: If ``initial`` names a block the prior lacks, or
            one of the wrong shape.
        ImportError: Without the ``assim`` extra.
    """
    if method not in ("lbfgs", "gauss_newton"):
        raise ValueError(f"solve_coupled: unknown method {method!r}.")
    if method == "gauss_newton" and initial is not None:
        raise NotImplementedError(
            "solve_coupled: Gauss–Newton starts at the prior mean until vardax "
            "can start it elsewhere (jejjohnson/vardax#315); use method='lbfgs' "
            "with `initial`."
        )
    import optimistix as optx

    vdx = require_vardax("solve_coupled")

    # --- observations ---
    prior = problem.prior
    prior_mean, unflatten = prior.flatten()
    stacked = problem.stacked_observations()

    def stacked_prediction(state: jax.Array) -> jax.Array:
        # h(θ)
        return problem.predict_stacked(unflatten(state))

    # 𝒥(θ) on the flat (D_θ,) control; the minimiser is chosen below
    three_dvar = functools.partial(
        vdx.ThreeDVar,
        obs_op=vdx.CallableObs(fn=stacked_prediction, materialise=True),
        prior_mean=prior_mean,
        prior_cov_op=prior.covariance_operator(),
        obs_cov_op=stacked.obs_cov_op(),
        max_steps=max_steps,
        cov_solver=lx.AutoLinearSolver(well_posed=True),
    )
    batch = stacked.batch()

    # --- minimiser ---
    if method == "gauss_newton":
        argminax = require_argminax("solve_coupled")
        model = three_dvar(minimiser=argminax.solve.GaussNewtonCG(rtol=rtol, atol=atol))
        posterior_model = model
    else:
        # Σ_θ = L Lᵀ
        cholesky = prior.cholesky()
        # θ = μ_θ + L χ, ½ ‖χ‖²
        basis = vdx.linear_basis(cholesky, variance=1.0)
        linear_control = vdx.LinearParameterization(basis, background=prior_mean)
        control = linear_control
        if initial is not None:
            # χ₀ = L⁻¹ (θ₀ − μ_θ)
            start = _initial_control(prior, initial)
            whitened_start = jax.scipy.linalg.solve_triangular(
                cholesky, start - prior_mean, lower=True
            )
            control = _StartedParameterization(linear_control, whitened_start)
        lbfgs = vdx.OptimistixMinimiser(
            optx.LBFGS(rtol=rtol, atol=atol), max_steps=max_steps
        )
        model = three_dvar(minimiser=lbfgs, parameterization=control)
        # the posterior at θ* does not depend on the start, and vardax takes it
        # from the affine parameterization
        posterior_model = eqx.tree_at(
            lambda module: module.parameterization, model, linear_control
        )

    # --- MAP ---
    # θ* = argmin 𝒥(θ)
    analysis, outcome = model.analyse(batch)
    params = analysis[0]
    map_estimate = unflatten(params)

    # --- Laplace posterior ---
    covariance = None
    std = None
    if laplace:
        # Σ_θ|y = (Σ_θ⁻¹ + J_hᵀ Σ_ε⁻¹ J_h)⁻¹
        posterior = vdx.LaplaceCovariance(solver=lx.AutoLinearSolver(well_posed=True))(
            params, posterior_model, batch
        )
        covariance = gaussx_linalg.symmetrize(posterior.cov.as_matrix())
        marginal_std = jnp.sqrt(jnp.clip(jnp.diagonal(covariance), 0.0, None))
        std = unflatten(marginal_std)

    block = problem.emission_block
    moments = _emission_moments(block, map_estimate, std)
    line_density = None
    line_density_std = None
    if block in _LINE_DENSITY_BLOCKS:
        # Q and U enter only as q = Q / U: Q waits on the wind (with_wind)
        line_density, line_density_std = moments
        emission_rate = jnp.full_like(line_density, jnp.nan)
        emission_std = jnp.full_like(line_density, jnp.nan)
    else:
        emission_rate, emission_std = moments

    # --- diagnostics ---
    predictions = problem.predict(map_estimate)
    residuals = {}
    for instrument in problem.forward.instruments:
        observation = jnp.asarray(problem.observations[instrument.name], dtype=float)
        residual = observation - predictions[instrument.name]
        mask = instrument.observation_mask()
        if residual.ndim == 2:
            mask = einx.id("obs -> obs channel", mask, channel=1)
        residuals[instrument.name] = jnp.where(mask > 0.0, residual, jnp.nan)
    return CoupledResult(
        map_estimate=map_estimate,
        std=std,
        mean=params,
        covariance=covariance,
        emission_rate=emission_rate,
        emission_std=emission_std,
        converged=bool(outcome.converged[0]),
        n_steps=int(outcome.num_steps[0]),
        cost=float(outcome.cost[0]),
        per_instrument_residuals=residuals,
        pixels_used=contribution_report(problem.forward.instruments),
        prior=prior,
        line_density=line_density,
        line_density_std=line_density_std,
        emission_block=block,
    )

Multistart

The image-fit cost has several minima in the source position, so solve_coupled_multistart runs solve_coupled(problem, initial=...) from each of several starts, with the same prior, and keeps the converged start with the lowest cost.

The coupled solve from several starting controls (implementation in plumax.coupled._src.multistart).

MultistartResult dataclass

MultistartResult(best: CoupledResult, index: int, costs: Float[ndarray, ' start'], converged: Bool[ndarray, ' start'], map_estimates: list[dict[str, Array]])

Every start's outcome, and the one that won.

Attributes:

Name Type Description
best CoupledResult

Result of the converged start with the lowest cost.

index int

Position j* of that start.

costs Float[ndarray, ' start']

Cost 𝒥(θ*_j) at each start's minimum.

converged Bool[ndarray, ' start']

Whether each start converged.

map_estimates list[dict[str, Array]]

MAP control of each start, by block.

solve_coupled_multistart

solve_coupled_multistart(problem: CoupledProblem, starts: Mapping[str, Float[Array, 'start ...']], **solve_options: Any) -> MultistartResult

The coupled solve from each start, keeping the lowest cost.

θ_j = argmin 𝒥(θ) from θ⁽⁰⁾_j; j = argmin_j 𝒥(θ*_j) over the converged j.

Algorithm
  1. Check that every block of starts has the same number J of starts.
  2. For each j, solve from the j-th start of each block; blocks not in starts start at the prior mean.
  3. Keep the converged start with the lowest cost.

The starts run one after another in a Python loop; each is a full :func:~plumax.coupled.solve_coupled.

Parameters:

Name Type Description Default
problem CoupledProblem

The coupled problem; its prior is the same for every start.

required
starts Mapping[str, Float[Array, 'start ...']]

Starting values by block, with a leading axis of J starts.

required
**solve_options Any

Passed to every :func:~plumax.coupled.solve_coupled (laplace, rtol, max_steps, ...).

{}

Returns:

Name Type Description
The MultistartResult

class:MultistartResult.

Raises:

Type Description
ControlBlockError

If starts is empty, its blocks differ in their number of starts, or a block is not in the prior.

ConvergenceError

If no start converges.

ValueError

If solve_options holds initial.

Source code in src/plumax/coupled/_src/multistart.py
def solve_coupled_multistart(
    problem: CoupledProblem,
    starts: Mapping[str, Float[Array, "start ..."]],
    **solve_options: Any,
) -> MultistartResult:
    """The coupled solve from each start, keeping the lowest cost.

    θ*_j = argmin 𝒥(θ) from θ⁽⁰⁾_j;  j* = argmin_j 𝒥(θ*_j) over the converged j.

    Algorithm:
        1. Check that every block of ``starts`` has the same number J of starts.
        2. For each j, solve from the j-th start of each block; blocks not in
           ``starts`` start at the prior mean.
        3. Keep the converged start with the lowest cost.

    The starts run one after another in a Python loop; each is a full
    :func:`~plumax.coupled.solve_coupled`.

    Args:
        problem: The coupled problem; its prior is the same for every start.
        starts: Starting values by block, with a leading axis of J starts.
        **solve_options: Passed to every :func:`~plumax.coupled.solve_coupled`
            (``laplace``, ``rtol``, ``max_steps``, ...).

    Returns:
        The :class:`MultistartResult`.

    Raises:
        ControlBlockError: If ``starts`` is empty, its blocks differ in their
            number of starts, or a block is not in the prior.
        ConvergenceError: If no start converges.
        ValueError: If ``solve_options`` holds ``initial``.
    """
    if "initial" in solve_options:
        raise ValueError(
            "solve_coupled_multistart: give the starts in `starts`, not `initial`."
        )
    if not starts:
        raise ControlBlockError("solve_coupled_multistart: `starts` is empty.")
    values = {name: jnp.asarray(value, dtype=float) for name, value in starts.items()}
    counts = {
        name: value.shape[0] if value.ndim else 0 for name, value in values.items()
    }
    num_starts = next(iter(counts.values()))
    if num_starts == 0 or any(count != num_starts for count in counts.values()):
        raise ControlBlockError(
            "solve_coupled_multistart: every block of `starts` needs the same "
            f"leading number of starts, at least one; got {counts}."
        )

    # --- one solve per start ---
    results = []
    for start_index in range(num_starts):
        # θ⁽⁰⁾_j
        initial = {name: value[start_index] for name, value in values.items()}
        results.append(solve_coupled(problem, initial=initial, **solve_options))

    # --- the lowest converged cost ---
    costs = np.array([result.cost for result in results], dtype=float)
    converged = np.array([result.converged for result in results], dtype=bool)
    if not bool(converged.any()):
        raise ConvergenceError(
            f"solve_coupled_multistart: none of the {num_starts} starts converged; "
            "raise `max_steps` or check the starts."
        )
    # j* = argmin_j 𝒥(θ*_j) over the converged j
    index = int(np.argmin(np.where(converged, costs, np.inf)))
    return MultistartResult(
        best=results[index],
        index=index,
        costs=costs,
        converged=converged,
        map_estimates=[dict(result.map_estimate) for result in results],
    )

Fit diagnostics

fit_diagnostics reports what the data determined in a solved problem: the Fisher information at the MAP, the prior-free Cramér–Rao bound of each parameter, the share of each parameter's prior variance the data removed, the degrees of freedom for signal, how far the prior was pulled, and each instrument's residual statistics.

What the data determined in a coupled fit (implementation in plumax.coupled._src.diagnostics).

FitDiagnostics dataclass

FitDiagnostics(fisher_information: Float[ndarray, 'param param'], cramer_rao_std: dict[str, ndarray], data_fraction: dict[str, ndarray], dofs: float, prior_pull: dict[str, ndarray], reduced_chi2: dict[str, float], rms_residual: dict[str, float])

Information content and residual statistics of a coupled fit.

Attributes:

Name Type Description
fisher_information Float[ndarray, 'param param']

F = J_hᵀ Σ_ε⁻¹ J_h at θ*, in the prior's layout.

cramer_rao_std dict[str, ndarray]

Prior-free bound √[F⁻¹]_aa by block; inf where F is singular along the parameter. The null space is found on F scaled to unit diagonal, so it does not depend on the blocks' units.

data_fraction dict[str, ndarray]

1 − [Σ_θ|y]_aa / [Σ_θ]_aa by block: 0 when the prior set the parameter, near 1 when the data did.

dofs float

Degrees of freedom for signal d_s = tr A, with A the averaging kernel (gaussx_infer.information_diagnostics).

prior_pull dict[str, ndarray]

(θ*_a − μ_θ,a) / √[Σ_θ]_aa by block.

reduced_chi2 dict[str, float]

χ²_red = Σₙ ωₙ rₙ² / σₙ² / (N_i − d_s) by instrument.

rms_residual dict[str, float]

√(Σₙ ωₙ rₙ² / N_i) by instrument.

fit_diagnostics

fit_diagnostics(problem: CoupledProblem, result: CoupledResult) -> FitDiagnostics

Diagnostics of a solved coupled problem.

F = J_hᵀ Σ_ε⁻¹ J_h; V[a] ≥ [F⁻¹]_aa; Σ_θ|y = (Σ_θ⁻¹ + F)⁻¹.

Algorithm
  1. Evaluate the Jacobian J_h of the stacked prediction at θ*.
  2. Form F = J_hᵀ Σ_ε⁻¹ J_h with the masked, inflated variances.
  3. Eigendecompose F; bound each parameter, or report inf.
  4. Compute the posterior and d_s with gaussx_infer.information_diagnostics and compare the posterior with the prior, block by block.
  5. Compute the residual statistics of each instrument.

The posterior in step 4 is the Gauss–Newton one at θ*, the covariance solve_coupled reports, recomputed here so a solve with laplace=False can be diagnosed too. Each instrument's χ²_red uses the d_s of the whole fit.

Parameters:

Name Type Description Default
problem CoupledProblem

The coupled problem.

required
result CoupledResult

Its solution, from solve_coupled.

required

Returns:

Name Type Description
The FitDiagnostics

class:FitDiagnostics.

Examples:

A parameter the data never see has no prior-free bound and keeps its prior: here the bias of a second, fully masked instrument.

>>> import jax.numpy as jnp
>>> import plumax.coupled as cpl
>>> from plumax.gauss_plume import ColumnPlume, ColumnPlumeSource, PlumeGeometry
>>> receptors = jnp.stack(
...     [jnp.linspace(100.0, 1000.0, 20), jnp.zeros(20)], axis=-1
... )
>>> seen = cpl.Instrument("EMIT", receptors, retrieval_variance=1e-8)
>>> masked = cpl.Instrument(
...     "GHGSat", receptors, retrieval_variance=1e-8, mask=jnp.zeros(20)
... )
>>> geometry = PlumeGeometry(
...     location=jnp.zeros(2),
...     direction=0.0,
...     reference_width=150.0,
...     width_exponent=0.9,
... )
>>> source = ColumnPlumeSource(plume=ColumnPlume(), geometry=geometry)
>>> forward = cpl.build_coupled_forward(source, [seen, masked])
>>> observation = 0.1 * source.column_response(seen)
>>> prior = cpl.CoupledPrior.from_std(
...     {"line_density": 0.0, "biases": jnp.zeros(2)},
...     {"line_density": 1.0, "biases": 1e-3},
... )
>>> problem = cpl.CoupledProblem(
...     forward=forward,
...     prior=prior,
...     observations={"EMIT": observation, "GHGSat": observation},
... )
>>> report = fit_diagnostics(problem, cpl.solve_coupled(problem))
>>> report.cramer_rao_std["biases"].tolist()[1]
inf
>>> float(report.data_fraction["biases"][1])
0.0
Source code in src/plumax/coupled/_src/diagnostics.py
def fit_diagnostics(problem: CoupledProblem, result: CoupledResult) -> FitDiagnostics:
    """Diagnostics of a solved coupled problem.

    F = J_hᵀ Σ_ε⁻¹ J_h;  V[a] ≥ [F⁻¹]_aa;  Σ_θ|y = (Σ_θ⁻¹ + F)⁻¹.

    Algorithm:
        1. Evaluate the Jacobian J_h of the stacked prediction at θ*.
        2. Form F = J_hᵀ Σ_ε⁻¹ J_h with the masked, inflated variances.
        3. Eigendecompose F; bound each parameter, or report inf.
        4. Compute the posterior and d_s with ``gaussx_infer.information_diagnostics``
           and compare the posterior with the prior, block by block.
        5. Compute the residual statistics of each instrument.

    The posterior in step 4 is the Gauss–Newton one at θ*, the covariance
    ``solve_coupled`` reports, recomputed here so a solve with
    ``laplace=False`` can be diagnosed too. Each instrument's χ²_red uses the
    d_s of the whole fit.

    Args:
        problem: The coupled problem.
        result: Its solution, from ``solve_coupled``.

    Returns:
        The :class:`FitDiagnostics`.

    Examples:
        A parameter the data never see has no prior-free bound and keeps its
        prior: here the bias of a second, fully masked instrument.

        >>> import jax.numpy as jnp
        >>> import plumax.coupled as cpl
        >>> from plumax.gauss_plume import ColumnPlume, ColumnPlumeSource, PlumeGeometry
        >>> receptors = jnp.stack(
        ...     [jnp.linspace(100.0, 1000.0, 20), jnp.zeros(20)], axis=-1
        ... )
        >>> seen = cpl.Instrument("EMIT", receptors, retrieval_variance=1e-8)
        >>> masked = cpl.Instrument(
        ...     "GHGSat", receptors, retrieval_variance=1e-8, mask=jnp.zeros(20)
        ... )
        >>> geometry = PlumeGeometry(
        ...     location=jnp.zeros(2),
        ...     direction=0.0,
        ...     reference_width=150.0,
        ...     width_exponent=0.9,
        ... )
        >>> source = ColumnPlumeSource(plume=ColumnPlume(), geometry=geometry)
        >>> forward = cpl.build_coupled_forward(source, [seen, masked])
        >>> observation = 0.1 * source.column_response(seen)
        >>> prior = cpl.CoupledPrior.from_std(
        ...     {"line_density": 0.0, "biases": jnp.zeros(2)},
        ...     {"line_density": 1.0, "biases": 1e-3},
        ... )
        >>> problem = cpl.CoupledProblem(
        ...     forward=forward,
        ...     prior=prior,
        ...     observations={"EMIT": observation, "GHGSat": observation},
        ... )
        >>> report = fit_diagnostics(problem, cpl.solve_coupled(problem))
        >>> report.cramer_rao_std["biases"].tolist()[1]
        inf
        >>> float(report.data_fraction["biases"][1])
        0.0
    """
    prior = problem.prior
    prior_mean, unflatten = prior.flatten()
    params = jnp.asarray(result.mean, dtype=prior_mean.dtype)

    # --- Jacobian at the MAP ---
    # J_h = ∂h / ∂θ at θ*
    obs_jacobian = _stacked_jacobian(problem, unflatten)(params)

    # --- Fisher information ---
    stacked = problem.stacked_observations()
    # Σ_ε⁻¹ with masked pixels at zero weight: ωₙ / σₙ²
    obs_precision = stacked.mask / stacked.variance
    # Σ_ε⁻¹ J_h
    weighted_jacobian = einx.multiply(
        "obs param, obs -> obs param", obs_jacobian, obs_precision
    )
    # F = J_hᵀ Σ_ε⁻¹ J_h
    fisher = einx.dot("obs row, obs col -> row col", obs_jacobian, weighted_jacobian)
    transposed = einx.id("row col -> col row", fisher)
    fisher = 0.5 * (fisher + transposed)

    # --- prior-free bound ---
    # The blocks carry their own units, so F is scaled to unit diagonal before
    # its null space is found: C = D F D, with D = diag(F_aa^(-1/2)). A
    # parameter the data do not touch (F_aa = 0) keeps a zero row in C, and so
    # falls in the null space.
    diagonal = jnp.diagonal(fisher)
    touched = diagonal > 0.0
    scale = jnp.where(touched, 1.0 / jnp.sqrt(jnp.where(touched, diagonal, 1.0)), 1.0)
    # C = D F D
    scaled = einx.multiply("row col, row, col -> row col", fisher, scale, scale)
    # C = W M Wᵀ
    eigenvalues, eigenvectors = jnp.linalg.eigh(scaled)
    largest = jnp.maximum(jnp.max(eigenvalues), 0.0)
    informative = eigenvalues > _NULL_EIGENVALUE * largest
    safe_eigenvalues = jnp.where(informative, eigenvalues, 1.0)
    # 1 / μ_k on the informative eigenvalues, 0 elsewhere
    inverse_eigenvalues = jnp.where(informative, 1.0 / safe_eigenvalues, 0.0)
    # [F⁻¹]_aa = D_aa² Σ_k W_ak² / μ_k
    squared_loadings = jnp.square(eigenvectors)
    scaled_variance = einx.dot(
        "param k, k -> param", squared_loadings, inverse_eigenvalues
    )
    bound_variance = jnp.square(scale) * scaled_variance
    # Σ_k W_ak² over μ_k ≈ 0: the share of parameter a the data cannot see
    null_weight = einx.dot(
        "param k, k -> param", squared_loadings, (~informative).astype(fisher.dtype)
    )
    bound_std = jnp.where(null_weight > _NULL_WEIGHT, jnp.inf, jnp.sqrt(bound_variance))

    # --- posterior against prior ---
    # Σ_ε^{-1/2} J_h, so the noise is white; a masked pixel is a zero row
    whitened_jacobian = einx.multiply(
        "obs param, obs -> obs param", obs_jacobian, jnp.sqrt(obs_precision)
    )
    # Σ_θ = L Lᵀ
    cholesky = prior.cholesky()
    prior_covariance = einx.dot("row a, col a -> row col", cholesky, cholesky)
    # Σ_θ|y, d_s = tr A, by a QR of [Σ_ε^{-1/2} J_h; L⁻¹] (Rodgers 2000)
    information = gaussx_infer.information_diagnostics(
        whitened_jacobian,
        lx.DiagonalLinearOperator(jnp.ones(whitened_jacobian.shape[0])),
        lx.MatrixLinearOperator(prior_covariance, PSD_TAGS),
    )
    dofs = information.dofs
    posterior_covariance = information.posterior_cov
    prior_variance = jnp.diagonal(prior_covariance)
    # 1 − [Σ_θ|y]_aa / [Σ_θ]_aa
    data_fraction = 1.0 - jnp.diagonal(posterior_covariance) / prior_variance
    # (θ* − μ_θ) / √[Σ_θ]_aa
    prior_pull = (params - prior_mean) / jnp.sqrt(prior_variance)

    # --- residuals ---
    predictions = problem.predict(unflatten(params))
    reduced_chi2, rms_residual = {}, {}
    start = 0
    for instrument in problem.forward.instruments:
        size = int(np.size(predictions[instrument.name]))
        stop = start + size
        # rₙ = yₙ − hₙ(θ*)
        predicted = einx.id("... -> (...)", predictions[instrument.name])
        residual = stacked.values[start:stop] - predicted
        # ωₙ, σₙ²
        weight = stacked.mask[start:stop]
        variance = stacked.variance[start:stop]
        start = stop
        # N_i = Σₙ ωₙ
        num_kept = einx.sum("[obs]", weight)
        # Σₙ ωₙ rₙ² / σₙ²
        chi2 = einx.sum("[obs]", weight * jnp.square(residual) / variance)
        # χ²_red = Σₙ ωₙ rₙ² / σₙ² / (N_i − d_s)
        reduced_chi2[instrument.name] = _ratio(chi2, num_kept - dofs)
        # rms = √(Σₙ ωₙ rₙ² / N_i)
        squared = einx.sum("[obs]", weight * jnp.square(residual))
        rms_residual[instrument.name] = float(np.sqrt(_ratio(squared, num_kept)))

    return FitDiagnostics(
        fisher_information=np.asarray(fisher),
        cramer_rao_std=_blocks(unflatten, bound_std),
        data_fraction=_blocks(unflatten, data_fraction),
        dofs=float(dofs),
        prior_pull=_blocks(unflatten, prior_pull),
        reduced_chi2=reduced_chi2,
        rms_residual=rms_residual,
    )