Skip to content

Coupled inversion

End-to-end coupled, multi-instrument source inversion. Tier IV.

coupled

Tier IV — end-to-end coupled, multi-instrument source inversion.

Tier IV is assembly + multi-instrument fusion, not new physics (design Tier IV): it composes a transport tier with the observation operator (averaging kernel / RTM) and fuses several satellites' observations into one coherent posterior.

This v1 implements the design's build-order step 1 — Tier I (Gaussian plume) + averaging kernel + multi-instrument L2 fusion for a static emission rate, with the per-instrument bias as a first-class state element:

  • instrument — :class:Instrument: per-satellite receptor geometry, averaging kernel, and R = R_retr + R_repr + R_align error budget.
  • forward — the coupled Tier I → column → AK forward, kept per-instrument at native resolution (build_coupled_forward / CoupledForward); linear in the emission rate Q.
  • fusion — the closed-form joint posterior over (Q, bias_inst) (fuse_observations), exploiting that linearity (the design's linear-conditional-Gaussian limit).
  • rtm — additive RTM-based observation operators that map the plume column enhancement → gas ΔVMR → band-integrated normalised radiance via the :mod:radtrax.slab Beer–Lambert + SRF stack, as the build-order step toward L1-radiance fusion. Two complementary, well-known models: the exact nonlinear RadianceObservationOperator / radiance_response (L_norm = exp(-Δτ)), and its tangent-linear counterpart LinearisedRadianceOperator / radiance_response_linear (via linearise), which is linear in Q and pure-JAX so it feeds gradient -based and closed-form inversion. LayeredRadianceOperator maps the column through radtrax's layered ForwardModel instead of the slab, in JAX end to end, so jax.grad with respect to Q runs through plume and radiance together. The scalar-AK path above is unchanged.

  • backends — the Tier II and Tier III transports behind the same forward (:class:TransportBackend, :class:LagrangianSource, :class:EulerianSource), through the shared column observation, and :class:AbstractControlledSource, the base of a backend that declares the control blocks the inversion fits.

  • quality — the per-instrument quality-flag aggregator (:class:QualityPolicy, :func:apply_quality, :func:contribution_report): flagged pixels are masked or have their variance inflated, and :func:stack_observations hands the result to vardax.

  • inversion — the nonlinear end-to-end inversion (:func:solve_coupled) over the emission, source position, wind, background and biases, through the averaging kernel or a radiance operator per instrument: plumax builds the forward, prior and masks, vardax solves (ThreeDVar, L-BFGS) and gives the Laplace posterior. Needs the assim extra.

  • multistart — the inversion from several starting controls, keeping the lowest cost (:func:solve_coupled_multistart, :class:MultistartResult).

  • diagnostics — what the data determined in a fit and how well it fits (:func:fit_diagnostics, :class:FitDiagnostics): the Fisher information, the prior-free Cramér–Rao bound, the data fraction, the degrees of freedom for signal, the prior pull and the residual statistics.
  • k_sources — masked-K multi-source handling across instruments (:class:MaskedKPrior, :func:infer_masked_k_sources, :func:build_masked_k_problem, :func:saturation_rate), on Tier I's slot prior and posterior carrier.

Later build-order steps (the Q(t) stochastic process, coupled emulator, operational predictor) are future work; the fusion harness and likelihood structure here are designed to stay the same as those blocks are swapped in.

EulerianSource dataclass

EulerianSource(forward: EulerianForward4DVar, background: float = 0.0)

Tier III transport: the les_fvm finite-volume run through the shared column.

r_i = A_i Σ_k Δz c_k(x_i, t_inst; Q = 1),

the field of a unit constant emission at the overpass time t_inst, read in the T-cell that holds each receptor. The forward is linear in the emission with a zero initial field, so Q · r is the run at constant emission Q.

Attributes:

Name Type Description
forward EulerianForward4DVar

The differentiable transport (les_fvm.build_forward); its save times must include each instrument's overpass time.

background float

Additive background column c_bg.

unit_history cached property

unit_history: Float[Array, 'time level y x']

Interior field history of a unit constant emission, one solve.

plume_grid property

plume_grid: PlumeGrid3D

The analysis grid the transport runs on.

time_index

time_index(instrument: Instrument) -> int

Index of the save time that equals the instrument's overpass time.

Raises:

Type Description
GridMismatchError

If no save time matches it.

Source code in src/plumax/coupled/_src/backends.py
def time_index(self, instrument: Instrument) -> int:
    """Index of the save time that equals the instrument's overpass time.

    Raises:
        GridMismatchError: If no save time matches it.
    """
    save_times = np.asarray(self.forward.save_times, dtype=float)
    matches = np.flatnonzero(np.isclose(save_times, instrument.observation_time))
    if matches.size == 0:
        raise GridMismatchError(
            f"EulerianSource: overpass time {instrument.observation_time} s of "
            f"{instrument.name!r} is not one of the forward's save times; "
            "build the forward with it in `save_times`."
        )
    return int(matches[0])

column_response

column_response(instrument: Instrument) -> Float[Array, ' obs']

Column per unit emission at the instrument's receptors.

Parameters:

Name Type Description Default
instrument Instrument

The observing instrument.

required

Returns:

Type Description
Float[Array, ' obs']

The response r_inst.

Raises:

Type Description
GridMismatchError

If the overpass time is not a save time.

DomainError

If a receptor lies outside the grid.

Source code in src/plumax/coupled/_src/backends.py
def column_response(self, instrument: Instrument) -> Float[Array, " obs"]:
    """Column per unit emission at the instrument's receptors.

    Args:
        instrument: The observing instrument.

    Returns:
        The response r_inst.

    Raises:
        GridMismatchError: If the overpass time is not a save time.
        DomainError: If a receptor lies outside the grid.
    """
    index = self.time_index(instrument)
    observation = ColumnObservation.for_grid(self.plume_grid, instrument=instrument)
    return observation.from_field(self.unit_history[index])

LagrangianSource dataclass

LagrangianSource(emission_pattern: Float[Array, ' cell'] | Float[Array, 'cell param'], winds: tuple[Velocity, ...], turbulence: TurbulenceModel, domain_x: tuple[float, float, int], domain_y: tuple[float, float, int], column_z: Float[Array, ' level'], n_particles: int = 1000, t_back: float = 600.0, dt: float = 1.0, pbl_height: float = 1000.0, pbl_fraction: float = 0.5, air_density: float = 1.2, seed: int = 0, background: float = 0.0)

Tier II transport: met-ensemble backward footprints through the shared column.

c_k(x_i) = ρ_air F̄(x_i, z_k) q, F̄ = mean_e F_e, r_i = A_i Σ_k h_k c_k(x_i),

with F_e the footprint of member e at receptor (x_i, z_k), q the surface flux of a unit source and h_k the trapezoid weights over column_z.

Attributes:

Name Type Description
emission_pattern Float[Array, ' cell'] | Float[Array, 'cell param']

Surface flux per unit emission q [m⁻²] on the footprint grid, cells flattened row-major over (x, y). A second axis holds one pattern per emission parameter.

winds tuple[Velocity, ...]

One mean wind per met-ensemble member, a tracerax velocity (gridded or uniform). One member is a deterministic run.

turbulence TurbulenceModel

Turbulence model shared by the members.

domain_x tuple[float, float, int]

(start, stop, n_cells) of the footprint grid along x.

domain_y tuple[float, float, int]

(start, stop, n_cells) of the footprint grid along y.

column_z Float[Array, ' level']

Receptor levels z_k [m] of the column, strictly increasing and inside the layer, 0 ≤ z_k ≤ pbl_height: the model has no particles above its lid.

n_particles int

Particles per receptor level and member.

t_back float

Backward integration time [s].

dt float

Particle time step [s].

pbl_height float

Boundary-layer height [m].

pbl_fraction float

Fraction of the boundary layer that sees the surface flux.

air_density float

Air density ρ_air [kg m⁻³].

seed int

Base PRNG seed of the particle draws.

background float

Additive background column c_bg.

point classmethod

point(location: tuple[float, float], *, winds: Sequence[Velocity], turbulence: TurbulenceModel, domain_x: tuple[float, float, int], domain_y: tuple[float, float, int], column_z: Float[Array, ' level'], **settings: float | int) -> LagrangianSource

A point source: unit emission spread over the cell that holds it.

q_s = 1 / A_cell in the containing cell s, zero elsewhere.

Parameters:

Name Type Description Default
location tuple[float, float]

Source (x, y) [m].

required
winds Sequence[Velocity]

One mean wind per met member.

required
turbulence TurbulenceModel

Turbulence model.

required
domain_x tuple[float, float, int]

(start, stop, n_cells) along x.

required
domain_y tuple[float, float, int]

(start, stop, n_cells) along y.

required
column_z Float[Array, ' level']

Receptor levels z_k [m], inside the layer.

required
**settings float | int

Any other field of :class:LagrangianSource.

{}

Returns:

Type Description
LagrangianSource

The source, with a one-cell emission pattern.

Raises:

Type Description
DomainError

If the location lies outside the footprint grid.

Source code in src/plumax/coupled/_src/backends.py
@classmethod
def point(
    cls,
    location: tuple[float, float],
    *,
    winds: Sequence[Velocity],
    turbulence: TurbulenceModel,
    domain_x: tuple[float, float, int],
    domain_y: tuple[float, float, int],
    column_z: Float[Array, " level"],
    **settings: float | int,
) -> LagrangianSource:
    """A point source: unit emission spread over the cell that holds it.

    q_s = 1 / A_cell in the containing cell s, zero elsewhere.

    Args:
        location: Source ``(x, y)`` [m].
        winds: One mean wind per met member.
        turbulence: Turbulence model.
        domain_x: ``(start, stop, n_cells)`` along x.
        domain_y: ``(start, stop, n_cells)`` along y.
        column_z: Receptor levels z_k [m], inside the layer.
        **settings: Any other field of :class:`LagrangianSource`.

    Returns:
        The source, with a one-cell emission pattern.

    Raises:
        DomainError: If the location lies outside the footprint grid.
    """
    # The cell is found in NumPy float64: a tracerax deposit would decide it in
    # the array dtype, and in float32 a source just below an inner edge would
    # land in the cell above.
    x_edges = edge_axis(domain_x)
    y_edges = edge_axis(domain_y)
    col_index, in_x = containing_cell(np.asarray(location[0], dtype=float), x_edges)
    row_index, in_y = containing_cell(np.asarray(location[1], dtype=float), y_edges)
    if not (in_x and in_y):
        raise DomainError(
            f"LagrangianSource.point: {location} lies outside the footprint grid."
        )
    # A_cell = Δx Δy
    cell_area = (x_edges[1] - x_edges[0]) * (y_edges[1] - y_edges[0])
    pattern = np.zeros((x_edges.size - 1, y_edges.size - 1))
    # q_s = 1 / A_cell in the containing cell
    pattern[col_index, row_index] = 1.0 / cell_area
    flat_pattern = einx.id("x y -> (x y)", pattern)
    return cls(
        emission_pattern=jnp.asarray(flat_pattern),
        winds=tuple(winds),
        turbulence=turbulence,
        domain_x=domain_x,
        domain_y=domain_y,
        column_z=jnp.asarray(column_z),
        **settings,
    )

footprints

footprints(instrument: Instrument) -> Float[Array, 'member point cell']

Member footprints F_e at every receptor level, level fastest.

Parameters:

Name Type Description Default
instrument Instrument

The observing instrument; its overpass time is the receptor time of the backward runs.

required

Returns:

Type Description
Float[Array, 'member point cell']

One row per (receptor, level) pair, units s m² kg⁻¹.

Source code in src/plumax/coupled/_src/backends.py
def footprints(self, instrument: Instrument) -> Float[Array, "member point cell"]:
    """Member footprints F_e at every receptor level, level fastest.

    Args:
        instrument: The observing instrument; its overpass time is the
            receptor time of the backward runs.

    Returns:
        One row per (receptor, level) pair, units s m² kg⁻¹.
    """
    levels = np.asarray(self.column_z, dtype=float)
    receptors = np.asarray(instrument.receptors, dtype=float)
    # every receptor (x_i, y_i) at every level z_k, level fastest
    horizontal = einx.id(
        "receptor coord -> (receptor level) coord", receptors, level=levels.size
    )
    heights = einx.id(
        "level -> (receptor level) 1", levels, receptor=receptors.shape[0]
    )
    points = einx.id(
        "point coord, point 1 -> point (coord + 1)", horizontal, heights
    )
    return ensemble_footprints(
        list(self.winds),
        jnp.asarray(points),
        self.turbulence,
        self.domain_x,
        self.domain_y,
        n_particles=self.n_particles,
        t_back=self.t_back,
        dt=self.dt,
        pbl_height=self.pbl_height,
        pbl_fraction=self.pbl_fraction,
        air_density=self.air_density,
        receptor_time=instrument.observation_time,
        seed=self.seed,
    )

column_response

column_response(instrument: Instrument) -> Float[Array, ' obs'] | Float[Array, 'obs param']

Column per unit emission at the instrument's receptors.

Algorithm
  1. Backward footprints from every receptor level, per member.
  2. Average over the members: F̄ = mean_e F_e.
  3. Concentration of a unit source: c = ρ_air F̄ q.
  4. Column and averaging kernel: r_i = A_i Σ_k h_k c_k(x_i).

Parameters:

Name Type Description Default
instrument Instrument

The observing instrument.

required

Returns:

Type Description
Float[Array, ' obs'] | Float[Array, 'obs param']

The response r_inst, one column per emission pattern when the

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

pattern has a parameter axis.

Source code in src/plumax/coupled/_src/backends.py
def column_response(
    self, instrument: Instrument
) -> Float[Array, " obs"] | Float[Array, "obs param"]:
    """Column per unit emission at the instrument's receptors.

    Algorithm:
        1. Backward footprints from every receptor level, per member.
        2. Average over the members: F̄ = mean_e F_e.
        3. Concentration of a unit source: c = ρ_air F̄ q.
        4. Column and averaging kernel: r_i = A_i Σ_k h_k c_k(x_i).

    Args:
        instrument: The observing instrument.

    Returns:
        The response r_inst, one column per emission pattern when the
        pattern has a parameter axis.
    """
    num_levels = int(np.shape(self.column_z)[0])
    footprints = self.footprints(instrument)
    # F̄ = mean_e F_e
    mean_footprint = einx.mean("member point cell -> point cell", footprints)
    pattern = jnp.asarray(self.emission_pattern, dtype=mean_footprint.dtype)
    observation = ColumnObservation.trapezoid(
        jnp.asarray(self.column_z, dtype=mean_footprint.dtype),
        averaging_kernel=instrument.ak,
    )
    if pattern.ndim == 1:
        # F̄ q
        mixing_ratio = einx.dot(
            "point cell, cell -> point", mean_footprint, pattern
        )
        # c = ρ_air F̄ q
        concentration = self.air_density * mixing_ratio
        profiles = einx.id(
            "(obs level) -> obs level", concentration, level=num_levels
        )
        return observation.column(profiles)
    # F̄ q_p, one per pattern
    mixing_ratio = einx.dot(
        "point cell, cell param -> point param", mean_footprint, pattern
    )
    # c_p = ρ_air F̄ q_p
    concentration = self.air_density * mixing_ratio
    profiles = einx.id(
        "(obs level) param -> param obs level", concentration, level=num_levels
    )
    columns = jax.vmap(observation.column)(profiles)
    return einx.id("param obs -> obs param", columns)

TransportBackend

Bases: Protocol

A transport tier as the coupled forward sees it.

r_inst = A_inst col_z(c(·; Q = 1)), the column per unit emission at each of the instrument's receptors.

Attributes:

Name Type Description
background float

Additive background column c_bg, in the units of the observation.

column_response

column_response(instrument: Instrument) -> Float[Array, ' obs'] | Float[Array, 'obs param']

Column per unit emission at the instrument's receptors.

Parameters:

Name Type Description Default
instrument Instrument

The observing instrument (receptors and kernel).

required

Returns:

Type Description
Float[Array, ' obs'] | Float[Array, 'obs param']

The response r_inst: one value per receptor for a scalar emission

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

rate, or one column per emission parameter.

Source code in src/plumax/coupled/_src/backends.py
def column_response(
    self, instrument: Instrument
) -> Float[Array, " obs"] | Float[Array, "obs param"]:
    """Column per unit emission at the instrument's receptors.

    Args:
        instrument: The observing instrument (receptors and kernel).

    Returns:
        The response r_inst: one value per receptor for a scalar emission
        rate, or one column per emission parameter.
    """
    ...

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.

CoupledForward dataclass

CoupledForward(source: PlumeSource | TransportBackend, instruments: tuple[Instrument, ...], responses: tuple[Array, ...])

Multi-instrument coupled forward: a list of per-instrument observations.

Holds the shared source/met configuration and the instrument list, and pre-computes each instrument's unit-Q :func:column_response (the static, Q-independent part of the forward). Use :func:build_coupled_forward.

Attributes:

Name Type Description
source PlumeSource | TransportBackend

Shared transport backend (PlumeSource, LagrangianSource or EulerianSource).

instruments tuple[Instrument, ...]

The observing instruments (fusion list).

responses tuple[Array, ...]

Per-instrument unit-Q column responses (one (n_obs,) array each, or an (n_obs, n_param) design matrix for a multi-parameter emission), aligned with instruments.

predict

predict(emission_rate: Array | float, biases: Sequence[Array | float] | None = None) -> list[jax.Array]

Predicted observation vector per instrument (list, native resolution).

Parameters:

Name Type Description Default
emission_rate Array | float

Emission rate Q [kg/s], or the (n_param,) emission vector when the responses are design matrices.

required
biases Sequence[Array | float] | None

Per-instrument additive biases, one per instrument. Defaults to zero for every instrument.

None

Returns:

Type Description
list[Array]

A list of (n_obs_i,) predictions, aligned with instruments.

Source code in src/plumax/coupled/_src/forward.py
def predict(
    self,
    emission_rate: jax.Array | float,
    biases: Sequence[jax.Array | float] | None = None,
) -> list[jax.Array]:
    """Predicted observation vector per instrument (list, native resolution).

    Args:
        emission_rate: Emission rate ``Q`` [kg/s], or the ``(n_param,)``
            emission vector when the responses are design matrices.
        biases: Per-instrument additive biases, one per instrument. Defaults
            to zero for every instrument.

    Returns:
        A list of ``(n_obs_i,)`` predictions, aligned with ``instruments``.
    """
    if biases is None:
        biases = [0.0] * len(self.instruments)
    if len(biases) != len(self.instruments):
        raise ValueError(
            f"CoupledForward.predict: got {len(biases)} biases for "
            f"{len(self.instruments)} instruments."
        )
    return [
        _scale_response(resp, emission_rate) + self.source.background + bias
        for resp, bias in zip(self.responses, biases, strict=True)
    ]

PlumeSource

Bases: AbstractControlledSource

Static source + meteorology for the Tier I coupled forward.

The emission rate Q is deliberately not stored here — it is the scalar the inversion solves for, so the forward is parameterised by everything except Q (location, wind, stability, background) and is linear in it.

As a controlled source it declares location (x, y) and wind (speed, direction), scaled by emission_rate or log_emission_rate; the height, stability class and levels stay fixed.

Attributes:

Name Type Description
location tuple[float, float, float]

(x, y, z) source coordinates [m].

wind_speed float

Wind speed [m/s], > 0.

wind_direction float

Meteorological direction [deg from North] (270 = wind from the west, flowing east).

stability_class str

Pasquill class 'A'–'F'.

column_z Array

1-D vertical grid [m] for the column integral, shape (n_z,), strictly increasing.

background float

Additive background column (same units as the AK output), applied per receptor. Default 0.

control_blocks property

control_blocks: Mapping[str, tuple[int, ...]]

location: (2,) and wind: (2,).

emission_blocks property

emission_blocks: tuple[str, ...]

emission_rate and log_emission_rate.

wind_uv

wind_uv() -> tuple[float, float]

Wind (u, v) [m/s] from speed + meteorological direction.

Source code in src/plumax/coupled/_src/forward.py
def wind_uv(self) -> tuple[float, float]:
    """Wind ``(u, v)`` [m/s] from speed + meteorological direction."""
    wind_east, wind_north = wind_components(
        self.wind_speed, self.wind_direction, xp=np
    )
    return float(wind_east), float(wind_north)

column_response

column_response(instrument: Instrument) -> jax.Array

Unit-Q column response, the Tier I :class:TransportBackend method.

Delegates to the module-level :func:column_response.

Source code in src/plumax/coupled/_src/forward.py
def column_response(self, instrument: Instrument) -> jax.Array:
    """Unit-``Q`` column response, the Tier I :class:`TransportBackend` method.

    Delegates to the module-level :func:`column_response`.
    """
    return column_response(self, instrument)

response_at

response_at(instrument: Instrument, control: Mapping[str, Float[Array, '*shape']]) -> Float[Array, ' obs']

Unit-Q column with the position and wind taken from control.

Blocks missing from control keep this source's values; see :func:plume_response.

Parameters:

Name Type Description Default
instrument Instrument

The observing instrument.

required
control Mapping[str, Float[Array, '*shape']]

The control, by block.

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 response_at(
    self,
    instrument: Instrument,
    control: Mapping[str, Float[Array, "*shape"]],
) -> Float[Array, " obs"]:
    """Unit-``Q`` column with the position and wind taken from ``control``.

    Blocks missing from ``control`` keep this source's values; see
    :func:`plume_response`.

    Args:
        instrument: The observing instrument.
        control: The control, by block.

    Returns:
        The unit-emission column through the averaging kernel.
    """
    location = control.get("location", jnp.asarray(self.location[:2]))
    wind = control.get("wind", jnp.asarray([self.wind_speed, self.wind_direction]))
    return plume_response(self, instrument, location, wind)

FusionPosterior dataclass

FusionPosterior(emission_rate: Array, emission_std: Array, biases: Array, bias_std: Array, mean: Array, covariance: Array, instrument_names: tuple[str, ...], pixels_used: Array | None = None, prior_mean: Array | None = None, prior_covariance: Array | None = None)

Closed-form joint posterior over (Q, bias₁ … bias_M).

All numeric fields are kept as JAX arrays (the scalars as 0-d arrays) so the whole posterior stays differentiable / jittable — the design advertises the estimator for gradient-based workflows, and forcing float(...) here would raise a concretization error under jax.grad / jax.jit. Use float(post.emission_rate) at the call site when a Python scalar is wanted.

With design-matrix responses (n_param emission parameters, e.g. one per cell of a Tier II source) the emission fields are (n_param,) vectors and the state is [q₁ … q_P, bias₁ … bias_M].

Attributes:

Name Type Description
emission_rate Array

Posterior mean emission Q* [kg/s], 0-d array ((n_param,) for design-matrix responses).

emission_std Array

Posterior standard deviation of Q, 0-d array ((n_param,) for design-matrix responses).

biases Array

Posterior mean per-instrument biases, shape (n_inst,).

bias_std Array

Posterior standard deviations of the biases, shape (n_inst,).

mean Array

Full posterior mean state [Q, bias₁ … bias_M], shape (n_param + n_inst,).

covariance Array

Full posterior covariance P*, shape (n_param + n_inst, n_param + n_inst).

instrument_names tuple[str, ...]

Names aligned with the bias entries.

pixels_used Array | None

Pixels each instrument contributed at full weight (unmasked, not inflated), shape (n_inst,), aligned with instrument_names.

prior_mean Array | None

Prior mean state θ_b the fusion used (None when built by hand).

prior_covariance Array | None

Prior covariance B (None when built by hand).

For a scalar Q it also carries the Tier V per-event payload (population.PerEventPosterior): Q's posterior marginal N(Q, P₀₀) and its prior marginal N(θ_b,0, B₀₀) are exact.

samples

samples(key: Array, n: int) -> jax.Array

n exact draws of Q from its posterior marginal N(Q, P₀₀).

Raises:

Type Description
PayloadError

For design-matrix (vector) emissions.

Source code in src/plumax/coupled/_src/fusion.py
def samples(self, key: jax.Array, n: int) -> jax.Array:
    """n exact draws of Q from its posterior marginal N(Q*, P*₀₀).

    Raises:
        PayloadError: For design-matrix (vector) emissions.
    """
    require_scalar(self.emission_rate, owner="FusionPosterior", method="samples")
    return GaussianEmission(self.emission_rate, self.emission_std).sample(key, n)

prior_logpdf

prior_logpdf(q: Array) -> jax.Array

log π(Q) of Q's prior marginal N(θ_b,0, B₀₀).

Raises:

Type Description
PayloadError

For vector emissions, or without the prior.

Source code in src/plumax/coupled/_src/fusion.py
def prior_logpdf(self, q: jax.Array) -> jax.Array:
    """log π(Q) of Q's prior marginal N(θ_b,0, B₀₀).

    Raises:
        PayloadError: For vector emissions, or without the prior.
    """
    require_scalar(
        self.emission_rate, owner="FusionPosterior", method="prior_logpdf"
    )
    require_prior(
        "FusionPosterior.prior_logpdf",
        built_with="fuse_observations",
        prior_mean=self.prior_mean,
        prior_covariance=self.prior_covariance,
    )
    prior_std = jnp.sqrt(self.prior_covariance[0, 0])
    return GaussianEmission(self.prior_mean[0], prior_std).log_prob(q)

Instrument

Bases: Module

Fixed observation geometry + error budget for one satellite instrument.

Attributes:

Name Type Description
name str

Instrument identifier (e.g. "TROPOMI").

receptors ArrayLike

Ground sample locations (n_obs, 2) as (x, y) [m].

averaging_kernel ArrayLike | None

Per-receptor scalar AK A_inst applied to the column enhancement, shape (n_obs,). Defaults to all-ones (identity AK).

retrieval_variance ArrayLike

Per-receptor L2 retrieval error R_retr, shape (n_obs,).

representation_variance ArrayLike

Model-vs-footprint mismatch R_repr (scalar or (n_obs,)). Default 0.

alignment_variance ArrayLike

Temporal-misalignment error R_align (scalar or (n_obs,)). Default 0.

observation_time float

Overpass time [s] (used by time-resolved transport tiers; ignored by the steady-state Tier I forward). Default 0.

flags ArrayLike | None

Per-pixel quality bit flags, shape (n_obs,), 0 = clear (see :class:~plumax.coupled.quality.QualityFlag). None is all-clear.

mask ArrayLike | None

Per-pixel observation mask, shape (n_obs,): 1 keeps the pixel, 0 drops it from the likelihood. None keeps all.

variance_inflation ArrayLike | None

Per-pixel factor ≥ 1 on the total observation variance, shape (n_obs,). None is no inflation.

n_obs property

n_obs: int

Number of receptor pixels.

ak property

ak: Array

Averaging kernel as an array (identity ones if unset).

observation_mask

observation_mask() -> jax.Array

Per-pixel mask as a float array, 1 = used (all ones if unset).

Source code in src/plumax/coupled/_src/instrument.py
def observation_mask(self) -> jax.Array:
    """Per-pixel mask as a float array, ``1`` = used (all ones if unset)."""
    if self.mask is None:
        return jnp.ones(self.n_obs)
    return jnp.asarray(self.mask, dtype=float)

observation_variance

observation_variance() -> jax.Array

Total per-receptor observation variance R_retr + R_repr + R_align.

Each term broadcasts to (n_obs,). The design flags omitting the representation / alignment terms as a source of overconfident posteriors, so all three are summed here. A variance_inflation multiplies the sum pixel by pixel.

Raises:

Type Description
ValueError

if any resulting variance is non-positive (a zero/negative variance would blow up or invert the likelihood weight).

Source code in src/plumax/coupled/_src/instrument.py
def observation_variance(self) -> jax.Array:
    """Total per-receptor observation variance ``R_retr + R_repr + R_align``.

    Each term broadcasts to ``(n_obs,)``. The design flags omitting the
    representation / alignment terms as a source of overconfident posteriors,
    so all three are summed here. A ``variance_inflation`` multiplies the
    sum pixel by pixel.

    Raises:
        ValueError: if any resulting variance is non-positive (a zero/negative
            variance would blow up or invert the likelihood weight).
    """
    obs_size = self.n_obs
    # R = R_retr + R_repr + R_align
    obs_variance = (
        jnp.broadcast_to(
            jnp.asarray(self.retrieval_variance, dtype=float), (obs_size,)
        )
        + jnp.broadcast_to(
            jnp.asarray(self.representation_variance, dtype=float), (obs_size,)
        )
        + jnp.broadcast_to(
            jnp.asarray(self.alignment_variance, dtype=float), (obs_size,)
        )
    )
    # Eager positivity check, skipped under jit / grad / vmap — the fusion
    # forward calls this from inside a traced cost, where ``obs_variance`` is a tracer
    # (every jnp op inside a trace is, even on concrete inputs) and a
    # host-bool conversion would raise. Guard on ``obs_variance`` itself, using the
    # shared ``_is_traced`` helper to match the inversion modules.
    require_positive(
        "obs_variance", obs_variance, caller=f"Instrument {self.name!r}"
    )
    if self.variance_inflation is not None:
        # R ← ρ R, the per-pixel variance inflation
        obs_variance = obs_variance * jnp.asarray(
            self.variance_inflation, dtype=float
        )
    return obs_variance

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)

MaskedKPrior dataclass

MaskedKPrior(k_max: int = 10, prior_active: float = 0.3, emission_mean: float = 0.1, emission_std: float = 0.05, background_std: float = 1e-06)

The slot prior: how many slots, how likely each is on, and its Q_k.

a_k ~ Bernoulli(p_active), Q_k ~ LogNormal moment-matched to the real-scale mean and standard deviation, as :func:plumax.gauss_plume.inference.multi_source_plume_model.

Attributes:

Name Type Description
k_max int

K_max ≥ 1 (the design's v1 cap is 10).

prior_active float

p_active in (0, 1]; 1 keeps every slot on, with no discrete sites.

emission_mean float

Real-scale prior mean of each Q_k [kg/s].

emission_std float

Real-scale prior standard deviation of each Q_k [kg/s].

background_std float

HalfNormal scale of the shared background column.

Raises:

Type Description
ValueError

On a parameter out of range.

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.

FlagPolicy

Bases: StrEnum

What a rejected pixel becomes: dropped, or kept with an inflated variance.

QualityFlag

Bases: IntFlag

Per-pixel quality bits, 0 = clear.

The bits of the planned radtrax retrieval flags (jejjohnson/radtrax#110, which supersedes plumax#97). Any integer bitmask works; these name the common ones.

QualityPolicy dataclass

QualityPolicy(policy: FlagPolicy = FlagPolicy.MASK, inflate_factor: float = 10.0, reject: int = QualityFlag.CLOUD | QualityFlag.NOT_CONVERGED)

Which flags reject a pixel, and how a rejected pixel enters the fusion.

Attributes:

Name Type Description
policy FlagPolicy

MASK drops rejected pixels; INFLATE scales their variance by inflate_factor.

inflate_factor float

Variance factor κ ≥ 1 for INFLATE.

reject int

Bitmask of the flags that reject a pixel.

Raises:

Type Description
ParameterError

If inflate_factor is below 1 or reject is negative.

rejected

rejected(flags: Int[Array, ' obs']) -> Bool[Array, ' obs']

Whether each pixel carries a rejecting flag, (flags & reject) ≠ 0.

Source code in src/plumax/coupled/_src/quality.py
def rejected(self, flags: Int[Array, " obs"]) -> Bool[Array, " obs"]:
    """Whether each pixel carries a rejecting flag, (flags & reject) ≠ 0."""
    hits = jnp.bitwise_and(jnp.asarray(flags), int(self.reject))
    return hits != 0

StackedObservations

Bases: Module

Every instrument's observations, mask and variance on one stacked axis.

The form vardax takes: y with masked pixels filled by zeros, the mask m and the diagonal of R (inflation included), instrument after instrument.

Attributes:

Name Type Description
values Float[Array, ' obs']

Observations y, zero where masked.

mask Float[Array, ' obs']

Observation mask m, 1 = used.

variance Float[Array, ' obs']

Diagonal of the observation-error covariance R.

batch

batch() -> vardax.Batch1D

One-sample vardax.Batch1D of shape (1, D_y).

Raises:

Type Description
ImportError

Without the assim extra.

Source code in src/plumax/coupled/_src/quality.py
def batch(self) -> vardax.Batch1D:
    """One-sample ``vardax.Batch1D`` of shape ``(1, D_y)``.

    Raises:
        ImportError: Without the ``assim`` extra.
    """
    vdx = require_vardax("StackedObservations.batch")
    return vdx.Batch1D(
        input=einx.id("obs -> 1 obs", self.values),
        mask=einx.id("obs -> 1 obs", self.mask),
    )

obs_cov_op

obs_cov_op() -> lx.DiagonalLinearOperator

R as a diagonal operator on the (D_y,) observations.

Source code in src/plumax/coupled/_src/quality.py
def obs_cov_op(self) -> lx.DiagonalLinearOperator:
    """R as a diagonal operator on the ``(D_y,)`` observations."""
    return lx.DiagonalLinearOperator(self.variance)

LayeredRadianceOperator

Bases: Module

Map a column-mass enhancement to band radiance through radtrax's layered model.

The layered counterpart of :class:RadianceObservationOperator, on :class:radtrax.ForwardModel instead of the single slab::

column mass m [kg/m²]  →  ΔX = m / M_CH₄ [mol/m²]
    →  state.add_column(gas, ΔX, profile)  →  y = F(state, surface, geometry)

and, when normalise (the default), y(ΔX) / y(0), so zero enhancement gives ones as the slab operator's normalised radiance does. Every step is JAX, so jax.grad of a misfit flows through the plume model and the radiative transfer together, and predict is a jax.vmap over receptors. The layers remove the slab's error of broadening every line at one pressure; with one layer on a table node, an identity instrument and no shift it equals the slab operator.

Band values are divided after band integration, y_b(ΔX) / y_b(0), which is what a sensor's ratio is. The slab operator instead integrates exp(-Δτ) over each band, so with an SRF the two differ by the background spectrum's weighting within the band.

Attributes:

Name Type Description
model ForwardModel

The layered forward model (opacity, solver, instrument).

state AtmosphericState

The background atmosphere; it must carry gas.

surface Surface

The surface reflectance.

geometry ViewingGeometry

Sun and sensor directions.

profile Float[Array, ' L'] | None

The plume's relative weight per layer, (L,); None puts the whole enhancement in the bottom layer.

gas str

The gas the plume adds.

normalise bool

Divide by the background band values y(0).

Examples:

>>> import jax.numpy as jnp
>>> from radtrax import ForwardModel
>>> from radtrax.atmosphere import ViewingGeometry, layers_from_levels
>>> from radtrax.instrument import BandInstrument
>>> from radtrax.solvers import BeerLambert
>>> from radtrax.spectroscopy import CrossSectionTable, TableOpacity
>>> from radtrax.surface import Lambertian
>>> nu = jnp.array([4300.0, 4300.1, 4300.2])
>>> table = CrossSectionTable(
...     jnp.log(jnp.array([1e4, 1e5])),
...     jnp.array([200.0, 300.0]),
...     jnp.full((2, 2, 3), 1e-21),
... )
>>> model = ForwardModel(
...     TableOpacity(nu, {"CH4": table}),
...     BeerLambert(),
...     BandInstrument(nu, jnp.full((1, 3), 1 / 3)),
... )
>>> atm = layers_from_levels(
...     jnp.array([1e5, 5e4]),
...     jnp.array([288.0, 255.0]),
...     {"CH4": jnp.full(2, 1.9e-6)},
... )
>>> op = LayeredRadianceOperator(
...     model, atm, Lambertian(0.3), ViewingGeometry(1.0, 1.0)
... )
>>> float(op.predict_single(0.0)[0])
1.0

n_channels property

n_channels: int

Number of output channels per receptor (the instrument's bands).

delta_column

delta_column(column_mass_kg_m2: Array | float) -> jax.Array

Column mass [kg/m²] → column enhancement ΔX [mol/m²].

Source code in src/plumax/coupled/_src/rtm.py
def delta_column(self, column_mass_kg_m2: jax.Array | float) -> jax.Array:
    """Column mass [kg/m²] → column enhancement ``ΔX`` [mol/m²]."""
    return jnp.asarray(column_mass_kg_m2, dtype=float) / CH4_MOLAR_MASS_KG_PER_MOL

predict_single

predict_single(column_mass_kg_m2: Array | float) -> jax.Array

Band values for one receptor, shape (n_channels,).

Parameters:

Name Type Description Default
column_mass_kg_m2 Array | float

Scalar column mass enhancement [kg/m²].

required

Returns:

Type Description
Array

y(ΔX) / y(0) when normalise, else y(ΔX).

Source code in src/plumax/coupled/_src/rtm.py
def predict_single(self, column_mass_kg_m2: jax.Array | float) -> jax.Array:
    """Band values for one receptor, shape ``(n_channels,)``.

    Args:
        column_mass_kg_m2: Scalar column mass enhancement [kg/m²].

    Returns:
        ``y(ΔX) / y(0)`` when ``normalise``, else ``y(ΔX)``.
    """
    plume = self.state.add_column(
        self.gas, self.delta_column(column_mass_kg_m2), self.profile
    )
    radiance = self.model(plume, self.surface, self.geometry)
    if self.normalise:
        # y(ΔX) / y(0)
        radiance = radiance / self.model(self.state, self.surface, self.geometry)
    return radiance

predict

predict(column_enhancement: Array | ndarray) -> jax.Array

Per-receptor band values, shape (n_obs, n_channels).

Parameters:

Name Type Description Default
column_enhancement Array | ndarray

Per-receptor column mass enhancement [kg/m²], shape (n_obs,) (e.g. Q · column_response).

required
Source code in src/plumax/coupled/_src/rtm.py
def predict(self, column_enhancement: jax.Array | np.ndarray) -> jax.Array:
    """Per-receptor band values, shape ``(n_obs, n_channels)``.

    Args:
        column_enhancement: Per-receptor column mass enhancement [kg/m²],
            shape ``(n_obs,)`` (e.g. ``Q · column_response``).
    """
    column_mass = jnp.asarray(column_enhancement, dtype=float)
    if column_mass.ndim != 1:
        raise ValueError(
            "LayeredRadianceOperator.predict: `column_enhancement` must be "
            f"1-D (n_obs,); got shape {column_mass.shape}."
        )
    return jax.vmap(self.predict_single)(column_mass)

LinearisedRadianceOperator dataclass

LinearisedRadianceOperator(baseline: Array, gain: Array)

Tangent-linear radiance operator — the linearised counterpart of the RTM.

The full :class:RadianceObservationOperator is exponential in the column (L_norm = exp(-Δτ)), so it has no closed-form inversion. Linearising the normalised Beer–Lambert forward about the background (ΔVMR = 0, where L_norm = 1) gives the affine response

L_norm(ΔVMR)  ≈  1 + J₀ · ΔVMR,        J₀ = d(L_norm)/d(ΔVMR)|₀,

and since ΔVMR = slope · column_mass is itself linear (the constant slope of :func:column_mass_to_delta_vmr) and the Tier I column is linear in the emission rate Q, the whole radiance forward becomes linear in Q. That makes this the radiance analogue of the scalar averaging kernel: a per-channel linear gain J₀ · slope on the column mass, usable as a drop-in linear observation response (and, with one channel, in the closed-form fusion path the scalar AK uses).

This is the well-known linearised / optimal-estimation radiance model (first-order Beer–Lambert), complementary to the exact nonlinear operator; it is accurate for small enhancements and exact in the optically-thin limit.

Build with :func:linearise from a :class:RadianceObservationOperator so the two share the LUT, geometry and SRF configuration.

Attributes:

Name Type Description
baseline Array

Background normalised radiance L_norm(0), shape (n_channels,) (all ones for the normalised forward; kept explicit so the affine offset is auditable / overridable).

gain Array

Per-channel linear response to column mass d(L_norm)/d(mass) = J₀ · slope, shape (n_channels,) [per kg/m²].

n_channels property

n_channels: int

Number of output channels per receptor.

predict_single

predict_single(column_mass_kg_m2: Array | float) -> jax.Array

Linearised normalised radiance baseline + gain · mass for one receptor.

Source code in src/plumax/coupled/_src/rtm.py
def predict_single(self, column_mass_kg_m2: jax.Array | float) -> jax.Array:
    """Linearised normalised radiance ``baseline + gain · mass`` for one receptor."""
    column_mass = jnp.asarray(column_mass_kg_m2, dtype=float)
    # L = L₀ + g m
    return self.baseline + self.gain * column_mass

predict

predict(column_enhancement: Array) -> jax.Array

Per-receptor linearised radiance, shape (n_obs, n_channels).

Fully differentiable / vectorised JAX: baseline[None, :] + mass[:, None] · gain[None, :].

Source code in src/plumax/coupled/_src/rtm.py
def predict(self, column_enhancement: jax.Array) -> jax.Array:
    """Per-receptor linearised radiance, shape ``(n_obs, n_channels)``.

    Fully differentiable / vectorised JAX:
    ``baseline[None, :] + mass[:, None] · gain[None, :]``.
    """
    column_mass = jnp.asarray(column_enhancement, dtype=float)
    if column_mass.ndim != 1:
        raise ValueError(
            "LinearisedRadianceOperator.predict: `column_enhancement` must "
            f"be 1-D (n_obs,); got shape {column_mass.shape}."
        )
    if column_mass.shape[0] == 0:
        # einx rejects a zero-size axis; no receptors, no radiances
        dtype = jnp.result_type(self.baseline, column_mass, self.gain)
        return jnp.zeros((0, np.shape(self.gain)[0]), dtype=dtype)
    # g m
    scaled = einx.multiply("obs, channel -> obs channel", column_mass, self.gain)
    # L = L₀ + g m
    return einx.add("channel, obs channel -> obs channel", self.baseline, scaled)

RadianceObservationOperator

RadianceObservationOperator(ds: Dataset, *, T_K: float, p_atm: float, path_length_cm: float, amf: float, srf: SpectralResponseFunction | None = None, nu_obs: Float[ArrayLike, ' G'] | None = None, var: str = 'absorption_cross_section')

Bases: Module

Map a per-receptor column-enhancement field to normalised radiance via the slab.

The RTM analogue of the scalar averaging kernel: instead of y = A · column, this composes

column mass m [kg/m²]  →  ΔVMR  →  L_norm(ν) = exp(−a(ν) ΔVMR)  →  band radiance

with :func:column_mass_to_delta_vmr and the single-slab Beer–Lambert absorption a(ν) = σ(ν, T, p) n L AMF, which the constructor looks up from the table once. With srf the operator holds radtrax's :class:~radtrax.retrieval.var3d.RadianceObservationModel, whose spectral grid is the SRF's own (ν = 10⁷ / λ), and returns one value per band, y_b = Σ_g f_bg exp(−a_g ΔVMR). Without it, it holds a(ν) on nu_obs and returns the high-resolution spectrum.

Every step after the lookup is JAX: predict is a jax.vmap over receptors, :meth:linearize_single is jax.jacfwd, and :class:~plumax.coupled.CoupledProblem takes the operator as it takes :class:LayeredRadianceOperator.

Parameters:

Name Type Description Default
ds Dataset

Absorption-cross-section table (HAPI schema; see :func:radtrax.spectroscopy.hitran.build_lut_dataset).

required
T_K float

Layer temperature [K].

required
p_atm float

Layer pressure [atm].

required
path_length_cm float

Optical / absorbing-path length [cm].

required
amf float

Air-mass factor.

required
srf SpectralResponseFunction | None

Band integration; its wavelength grid is the spectral grid.

None
nu_obs Float[ArrayLike, ' G'] | None

Wavenumbers [cm⁻¹] of the spectrum returned without srf, (G,).

None
var str

Table cross-section variable name.

'absorption_cross_section'

Attributes:

Name Type Description
model RadianceObservationModel | None

The radtrax slab model with its band instrument, or None without an SRF.

absorption_coeff_hr Float[Array, ' G'] | None

a(ν) on nu_obs, (G,), or None with an SRF (the model holds it on the SRF's grid).

T_K float

Layer temperature [K], for the mass → ΔVMR conversion.

p_atm float

Layer pressure [atm], for the mass → ΔVMR conversion.

path_length_cm float

Path length [cm], for the mass → ΔVMR conversion.

Raises:

Type Description
ValueError

If not exactly one of srf and nu_obs is given.

DomainError

If the spectral grid, T_K or p_atm leaves the table, where the lookup would return NaN.

Source code in src/plumax/coupled/_src/rtm.py
def __init__(
    self,
    ds: xr.Dataset,
    *,
    T_K: float,
    p_atm: float,
    path_length_cm: float,
    amf: float,
    srf: SpectralResponseFunction | None = None,
    nu_obs: Float[ArrayLike, " G"] | None = None,
    var: str = "absorption_cross_section",
) -> None:
    if (srf is None) == (nu_obs is None):
        raise ValueError(
            "RadianceObservationOperator: give exactly one of `srf` (its "
            "wavelength grid is the spectral grid) and `nu_obs` (the "
            "spectrum without band integration)."
        )
    self.T_K, self.p_atm = float(T_K), float(p_atm)
    self.path_length_cm = float(path_length_cm)
    if srf is not None:
        # ν = 10⁷ / λ on the SRF's grid
        nu_hr = 1e7 / np.asarray(srf.wavelengths_hr_nm, dtype=float)
        _require_inside_table(ds, nu_hr, self.T_K, self.p_atm)
        # a(ν) = σ(ν, T, p) n L AMF, on the SRF's grid in ascending ν
        self.model = RadianceObservationModel.from_lut(
            ds,
            srf=srf,
            T_K=self.T_K,
            p_atm=self.p_atm,
            path_length_cm=self.path_length_cm,
            amf=float(amf),
            var=var,
        )
        self.absorption_coeff_hr = None
        return
    nu = np.asarray(nu_obs, dtype=float)
    _require_inside_table(ds, nu, self.T_K, self.p_atm)
    # a(ν) = −∂L_norm/∂ΔVMR at ΔVMR = 0, from radtrax's slab lookup
    tangent = forward_nonlinear_normalized(
        ds,
        nu,
        T_K=self.T_K,
        p_atm=self.p_atm,
        vmr_background=0.0,
        delta_vmr=0.0,
        path_length_cm=self.path_length_cm,
        amf=float(amf),
        var=var,
    )
    self.model = None
    self.absorption_coeff_hr = -jnp.asarray(tangent.jacobian, dtype=float)

n_channels property

n_channels: int

Number of output channels per receptor (bands if SRF, else n_nu).

delta_vmr

delta_vmr(column_mass_kg_m2: Array | float) -> jax.Array

Column mass [kg/m²] → ΔVMR via :func:column_mass_to_delta_vmr.

Source code in src/plumax/coupled/_src/rtm.py
def delta_vmr(self, column_mass_kg_m2: jax.Array | float) -> jax.Array:
    """Column mass [kg/m²] → ΔVMR via :func:`column_mass_to_delta_vmr`."""
    return column_mass_to_delta_vmr(
        column_mass_kg_m2,
        p_atm=self.p_atm,
        T_K=self.T_K,
        path_length_cm=self.path_length_cm,
    )

predict_delta_vmr

predict_delta_vmr(delta_vmr: Array | float) -> jax.Array

Normalised radiance for one receptor's ΔVMR, shape (n_channels,).

Parameters:

Name Type Description Default
delta_vmr Array | float

Scalar ΔVMR enhancement.

required

Returns:

Type Description
Array

exp(−a ΔVMR), band-integrated when an SRF is configured.

Source code in src/plumax/coupled/_src/rtm.py
def predict_delta_vmr(self, delta_vmr: jax.Array | float) -> jax.Array:
    """Normalised radiance for one receptor's ``ΔVMR``, shape ``(n_channels,)``.

    Args:
        delta_vmr: Scalar ``ΔVMR`` enhancement.

    Returns:
        ``exp(−a ΔVMR)``, band-integrated when an SRF is configured.
    """
    delta_vmr = jnp.asarray(delta_vmr, dtype=float)
    if self.model is not None:
        # one pixel: () → (1, 1)
        field = einx.id(" -> h w", delta_vmr, h=1, w=1)
        # y_b = Σ_g f_bg exp(−a_g ΔVMR): (1, 1) → (1, 1, B) → (B,)
        return self.model.forward(field)[0, 0]
    # L_norm(ν) = exp(−a(ν) ΔVMR)                                        (G,)
    return jnp.exp(-jnp.asarray(self.absorption_coeff_hr) * delta_vmr)

predict_single

predict_single(column_mass_kg_m2: Array | float) -> jax.Array

Normalised radiance for one receptor, shape (n_channels,).

Parameters:

Name Type Description Default
column_mass_kg_m2 Array | float

Scalar column mass enhancement [kg/m²].

required

Returns:

Type Description
Array

exp(−a ΔVMR), band-integrated when an SRF is configured.

Source code in src/plumax/coupled/_src/rtm.py
def predict_single(self, column_mass_kg_m2: jax.Array | float) -> jax.Array:
    """Normalised radiance for one receptor, shape ``(n_channels,)``.

    Args:
        column_mass_kg_m2: Scalar column mass enhancement [kg/m²].

    Returns:
        ``exp(−a ΔVMR)``, band-integrated when an SRF is configured.
    """
    return self.predict_delta_vmr(self.delta_vmr(column_mass_kg_m2))

predict

predict(column_enhancement: Array | ndarray) -> jax.Array

Per-receptor normalised radiance, shape (n_obs, n_channels).

Parameters:

Name Type Description Default
column_enhancement Array | ndarray

Per-receptor column mass enhancement [kg/m²], shape (n_obs,) (e.g. Q · column_response).

required
Source code in src/plumax/coupled/_src/rtm.py
def predict(self, column_enhancement: jax.Array | np.ndarray) -> jax.Array:
    """Per-receptor normalised radiance, shape ``(n_obs, n_channels)``.

    Args:
        column_enhancement: Per-receptor column mass enhancement [kg/m²],
            shape ``(n_obs,)`` (e.g. ``Q · column_response``).
    """
    column_mass = jnp.asarray(column_enhancement, dtype=float)
    if column_mass.ndim != 1:
        raise ValueError(
            "RadianceObservationOperator.predict: `column_enhancement` must "
            f"be 1-D (n_obs,); got shape {column_mass.shape}."
        )
    return jax.vmap(self.predict_single)(column_mass)

linearize_single

linearize_single(column_mass_kg_m2: Array | float) -> jax.Array

d(L_norm)/d(ΔVMR) at one receptor, by jax.jacfwd.

The tangent-linear with respect to ΔVMR, band-integrated when an SRF is configured; chain with d(ΔVMR)/d(column mass) (the constant slope of :func:column_mass_to_delta_vmr) for the column-space Jacobian, which :func:linearise takes directly.

Parameters:

Name Type Description Default
column_mass_kg_m2 Array | float

Scalar column mass enhancement [kg/m²].

required

Returns:

Type Description
Array

Jacobian, shape (n_channels,) (negative for an absorbing band).

Source code in src/plumax/coupled/_src/rtm.py
def linearize_single(self, column_mass_kg_m2: jax.Array | float) -> jax.Array:
    """``d(L_norm)/d(ΔVMR)`` at one receptor, by ``jax.jacfwd``.

    The tangent-linear with respect to ``ΔVMR``, band-integrated when an
    SRF is configured; chain with ``d(ΔVMR)/d(column mass)`` (the
    constant slope of :func:`column_mass_to_delta_vmr`) for the
    column-space Jacobian, which :func:`linearise` takes directly.

    Args:
        column_mass_kg_m2: Scalar column mass enhancement [kg/m²].

    Returns:
        Jacobian, shape ``(n_channels,)`` (negative for an absorbing band).
    """
    return jax.jacfwd(self.predict_delta_vmr)(self.delta_vmr(column_mass_kg_m2))

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,
    )

build_coupled_forward

build_coupled_forward(source: PlumeSource | TransportBackend, instruments: Sequence[Instrument]) -> CoupledForward

Assemble a :class:CoupledForward, precomputing unit-Q responses.

Parameters:

Name Type Description Default
source PlumeSource | TransportBackend

Shared transport backend: the Tier I PlumeSource, or a :class:~plumax.coupled.backends.LagrangianSource / :class:~plumax.coupled.backends.EulerianSource.

required
instruments Sequence[Instrument]

One or more observing instruments to fuse.

required

Returns:

Type Description
CoupledForward

The configured :class:CoupledForward.

Raises:

Type Description
ValueError

if instruments is empty.

Source code in src/plumax/coupled/_src/forward.py
def build_coupled_forward(
    source: PlumeSource | TransportBackend, instruments: Sequence[Instrument]
) -> CoupledForward:
    """Assemble a :class:`CoupledForward`, precomputing unit-``Q`` responses.

    Args:
        source: Shared transport backend: the Tier I ``PlumeSource``, or a
            :class:`~plumax.coupled.backends.LagrangianSource` /
            :class:`~plumax.coupled.backends.EulerianSource`.
        instruments: One or more observing instruments to fuse.

    Returns:
        The configured :class:`CoupledForward`.

    Raises:
        ValueError: if ``instruments`` is empty.
    """
    insts = tuple(instruments)
    if not insts:
        raise ValueError("build_coupled_forward: need at least one instrument.")
    responses = tuple(source.column_response(inst) for inst in insts)
    return CoupledForward(source=source, instruments=insts, responses=responses)

column_response

column_response(source: PlumeSource, instrument: Instrument) -> jax.Array

Per-receptor column enhancement at unit emission for one instrument.

Evaluates the Gaussian plume at unit Q on each receptor column, then integrates over source.column_z (trapezoidal) and applies the instrument averaging kernel with the shared :class:~plumax.gauss_plume.observation.ColumnObservation (whose module docstring states the units). The full observation at emission Q is then Q · column_response + bias (plus the background; see :func:predict_observation). Linearity in Q is what makes the coupled inversion closed-form. It is :func:plume_response at the source's own position and wind.

Parameters:

Name Type Description Default
source PlumeSource

The static source + met configuration.

required
instrument Instrument

The observing instrument (receptors + AK).

required

Returns:

Type Description
Array

Unit-Q AK-weighted column response, shape (n_obs,).

Source code in src/plumax/coupled/_src/forward.py
def column_response(source: PlumeSource, instrument: Instrument) -> jax.Array:
    """Per-receptor column enhancement at **unit emission** for one instrument.

    Evaluates the Gaussian plume at unit ``Q`` on each receptor column, then
    integrates over ``source.column_z`` (trapezoidal) and applies the instrument
    averaging kernel with the shared
    :class:`~plumax.gauss_plume.observation.ColumnObservation` (whose module
    docstring states the units). The full observation at emission ``Q`` is then
    ``Q · column_response + bias`` (plus the background; see
    :func:`predict_observation`). Linearity in ``Q`` is what makes the coupled
    inversion closed-form. It is :func:`plume_response` at the source's own
    position and wind.

    Args:
        source: The static source + met configuration.
        instrument: The observing instrument (receptors + AK).

    Returns:
        Unit-``Q`` AK-weighted column response, shape ``(n_obs,)``.
    """
    location = jnp.asarray(source.location[:2], dtype=float)
    wind = jnp.asarray([source.wind_speed, source.wind_direction], dtype=float)
    return plume_response(source, instrument, location, wind)

predict_observation

predict_observation(source: PlumeSource, instrument: Instrument, emission_rate: Array | float, bias: Array | float = 0.0) -> jax.Array

Predict one instrument's observation vector y_inst.

y = Q · column_response + background + bias — the affine forward the coupled cost compares against the observed enhancement.

Parameters:

Name Type Description Default
source PlumeSource

Static source + met configuration.

required
instrument Instrument

The observing instrument.

required
emission_rate Array | float

Emission rate Q [kg/s] (scalar).

required
bias Array | float

Per-instrument additive offset (scalar). Default 0.

0.0

Returns:

Type Description
Array

Predicted observation, shape (n_obs,).

Source code in src/plumax/coupled/_src/forward.py
def predict_observation(
    source: PlumeSource,
    instrument: Instrument,
    emission_rate: jax.Array | float,
    bias: jax.Array | float = 0.0,
) -> jax.Array:
    """Predict one instrument's observation vector ``y_inst``.

    ``y = Q · column_response + background + bias`` — the affine forward the
    coupled cost compares against the observed enhancement.

    Args:
        source: Static source + met configuration.
        instrument: The observing instrument.
        emission_rate: Emission rate ``Q`` [kg/s] (scalar).
        bias: Per-instrument additive offset (scalar). Default ``0``.

    Returns:
        Predicted observation, shape ``(n_obs,)``.
    """
    response = column_response(source, instrument)
    return emission_rate * response + source.background + bias

default_prior

default_prior(*, n_instruments: int, emission_prior_mean: float, emission_prior_std: float, bias_prior_std: float) -> tuple[jax.Array, jax.Array]

Build a diagonal prior (θ_b, B) for (Q, bias₁ … bias_M).

A convenience for the common case: a Gaussian prior on Q and zero-mean Gaussian biases (the design's bias_inst ~ N(0, σ²_inst)).

Parameters:

Name Type Description Default
n_instruments int

Number of instruments (bias slots).

required
emission_prior_mean float

Prior mean for Q [kg/s].

required
emission_prior_std float

Prior std for Q (> 0).

required
bias_prior_std float

Prior std for each per-instrument bias (> 0).

required

Returns:

Type Description
tuple[Array, Array]

(prior_mean, prior_covariance) ready for :func:fuse_observations.

Source code in src/plumax/coupled/_src/fusion.py
def default_prior(
    *,
    n_instruments: int,
    emission_prior_mean: float,
    emission_prior_std: float,
    bias_prior_std: float,
) -> tuple[jax.Array, jax.Array]:
    """Build a diagonal prior ``(θ_b, B)`` for ``(Q, bias₁ … bias_M)``.

    A convenience for the common case: a Gaussian prior on ``Q`` and zero-mean
    Gaussian biases (the design's ``bias_inst ~ N(0, σ²_inst)``).

    Args:
        n_instruments: Number of instruments (bias slots).
        emission_prior_mean: Prior mean for ``Q`` [kg/s].
        emission_prior_std: Prior std for ``Q`` (``> 0``).
        bias_prior_std: Prior std for each per-instrument bias (``> 0``).

    Returns:
        ``(prior_mean, prior_covariance)`` ready for :func:`fuse_observations`.
    """
    require_positive("emission_prior_std", emission_prior_std, caller="default_prior")
    require_positive("bias_prior_std", bias_prior_std, caller="default_prior")
    mean = jnp.concatenate([jnp.array([emission_prior_mean]), jnp.zeros(n_instruments)])
    variances = np.concatenate(
        [[emission_prior_std**2], np.full(n_instruments, bias_prior_std**2)]
    )
    return mean, jnp.diag(jnp.asarray(variances, dtype=float))

fuse_observations

fuse_observations(forward: CoupledForward, observations: Sequence[Array], *, prior_mean: Array, prior_covariance: Array, quality: QualityPolicy | None = None) -> FusionPosterior

Closed-form joint posterior over (Q, bias_inst) from fused observations.

Solves the BLUE update for the affine forward y = G θ + c_bg with a Gaussian prior θ ~ N(θ_b, B) and diagonal observation covariance R (the per-instrument R_retr + R_repr + R_align)::

P*⁻¹ = B⁻¹ + Gᵀ R⁻¹ G
θ*   = θ_b + P* Gᵀ R⁻¹ (y − G θ_b − c_bg)

solved as a vardax.OptimalInterpolation analysis in its state-space (information) form, which factorises only the small (n_param + n_inst) × (n_param + n_inst) posterior precision.

Each instrument's mask zeroes its pixels' weight in R⁻¹ and its variance_inflation scales their variance (see :mod:plumax.coupled.quality); a masked observation may hold anything, NaN included.

Parameters:

Name Type Description Default
forward CoupledForward

The assembled multi-instrument coupled forward.

required
observations Sequence[Array]

Observed enhancement vector per instrument, aligned with forward.instruments (each (n_obs_i,)).

required
prior_mean Array

Prior mean state [Q_b, bias_b₁ … bias_b_M], shape (n_param + n_inst,) with n_param = 1 for a scalar Q (biases typically prior-zero).

required
prior_covariance Array

Prior covariance B, shape (n_param + n_inst, n_param + n_inst) — e.g. diag(σ_Q², σ_bias², …).

required
quality QualityPolicy | None

Optional quality policy, applied to every instrument that carries flags (:func:~plumax.coupled.quality.apply_quality). Default None: use the instruments' masks and inflation as they are.

None

Returns:

Name Type Description
The FusionPosterior

class:FusionPosterior.

Raises:

Type Description
ValueError

on a per-instrument observation-count mismatch or a mis-shaped prior.

ImportError

Without the assim extra (vardax).

Source code in src/plumax/coupled/_src/fusion.py
def fuse_observations(
    forward: CoupledForward,
    observations: Sequence[jax.Array],
    *,
    prior_mean: jax.Array,
    prior_covariance: jax.Array,
    quality: QualityPolicy | None = None,
) -> FusionPosterior:
    """Closed-form joint posterior over ``(Q, bias_inst)`` from fused observations.

    Solves the BLUE update for the affine forward ``y = G θ + c_bg`` with a
    Gaussian prior ``θ ~ N(θ_b, B)`` and diagonal observation covariance ``R``
    (the per-instrument ``R_retr + R_repr + R_align``)::

        P*⁻¹ = B⁻¹ + Gᵀ R⁻¹ G
        θ*   = θ_b + P* Gᵀ R⁻¹ (y − G θ_b − c_bg)

    solved as a ``vardax.OptimalInterpolation`` analysis in its state-space
    (information) form, which factorises only the small
    ``(n_param + n_inst) × (n_param + n_inst)`` posterior precision.

    Each instrument's ``mask`` zeroes its pixels' weight in ``R⁻¹`` and its
    ``variance_inflation`` scales their variance (see
    :mod:`plumax.coupled.quality`); a masked observation may hold anything,
    NaN included.

    Args:
        forward: The assembled multi-instrument coupled forward.
        observations: Observed enhancement vector per instrument, aligned with
            ``forward.instruments`` (each ``(n_obs_i,)``).
        prior_mean: Prior mean state ``[Q_b, bias_b₁ … bias_b_M]``, shape
            ``(n_param + n_inst,)`` with ``n_param = 1`` for a scalar ``Q``
            (biases typically prior-zero).
        prior_covariance: Prior covariance ``B``, shape
            ``(n_param + n_inst, n_param + n_inst)`` — e.g.
            ``diag(σ_Q², σ_bias², …)``.
        quality: Optional quality policy, applied to every instrument that
            carries ``flags`` (:func:`~plumax.coupled.quality.apply_quality`).
            Default ``None``: use the instruments' masks and inflation as
            they are.

    Returns:
        The :class:`FusionPosterior`.

    Raises:
        ValueError: on a per-instrument observation-count mismatch or a
            mis-shaped prior.
        ImportError: Without the ``assim`` extra (vardax).
    """
    if quality is not None:
        screened = tuple(
            inst if inst.flags is None else apply_quality(inst, inst.flags, quality)
            for inst in forward.instruments
        )
        forward = dataclasses.replace(forward, instruments=screened)
    num_instruments = len(forward.instruments)
    param_size = _n_emission_params(forward)
    # D_x = n_param + n_inst
    state_size = param_size + num_instruments
    prior_mean_vector = jnp.asarray(prior_mean, dtype=float)
    prior_covariance_matrix = jnp.asarray(prior_covariance, dtype=float)
    if prior_mean_vector.shape != (state_size,):
        raise ValueError(
            f"fuse_observations: `prior_mean` must be (n_param + n_inst = "
            f"{state_size},); "
            f"got {prior_mean_vector.shape}."
        )
    if prior_covariance_matrix.shape != (state_size, state_size):
        raise ValueError(
            f"fuse_observations: `prior_covariance` must be "
            f"({state_size}, {state_size}); "
            f"got {prior_covariance_matrix.shape}."
        )
    if len(observations) != num_instruments:
        raise ValueError(
            f"fuse_observations: got {len(observations)} observation vectors for "
            f"{num_instruments} instruments."
        )
    # shape check, masked-pixel zero, and the stacked mask and variance
    stacked = stack_observations(forward.instruments, observations)
    design, background = _stack_design(forward)
    mask = stacked.mask
    obs_variance = stacked.variance
    # y − c_bg
    shifted_obs = stacked.values - background
    posterior_mean, posterior_cov = _information_form_analysis(
        design,
        shifted_obs,
        mask,
        obs_variance,
        prior_mean=prior_mean_vector,
        prior_covariance=prior_covariance_matrix,
    )

    std = jnp.sqrt(jnp.clip(jnp.diag(posterior_cov), 0.0, None))
    names = tuple(inst.name for inst in forward.instruments)
    emission = posterior_mean[0] if param_size == 1 else posterior_mean[:param_size]
    emission_std = std[0] if param_size == 1 else std[:param_size]
    return FusionPosterior(
        emission_rate=emission,
        emission_std=emission_std,
        biases=posterior_mean[param_size:],
        bias_std=std[param_size:],
        mean=posterior_mean,
        covariance=posterior_cov,
        instrument_names=names,
        pixels_used=jnp.stack(
            [full_weight_pixels(inst) for inst in forward.instruments]
        ),
        prior_mean=prior_mean_vector,
        prior_covariance=prior_covariance_matrix,
    )

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,
    )

build_masked_k_problem

build_masked_k_problem(instruments: Sequence[Instrument], *, transport: PlumeSource | TransportBackend, prior: MaskedKPrior, observations: Mapping[str, Array], active: Bool[Array, ' source'], candidate_locations: Float[Array, 'source 2'] | None = None) -> CoupledProblem

The coupled problem of one active set, for the MAP and Laplace path.

y_i = Σ_{k active} Q_k r_i(x_k, y_k) + c_bg + ε_i over log Q_k and c_bg, under the same lognormal prior as the slots. The background is the Gaussian N(0, σ²_bg) here, against the sampler's HalfNormal(σ_bg): the block prior is Gaussian, and the two have the same curvature at zero. Hand it to :func:~plumax.coupled.solve_coupled, which solves on vardax. This is the operational path; the active set itself comes from :func:infer_masked_k_sources or from the caller.

Parameters:

Name Type Description Default
instruments Sequence[Instrument]

The observing instruments.

required
transport PlumeSource | TransportBackend

The transport backend.

required
prior MaskedKPrior

The slot prior.

required
observations Mapping[str, Array]

Observations by instrument.

required
active Bool[Array, ' source']

a_k, with at least one slot on.

required
candidate_locations Float[Array, 'source 2'] | None

Fixed (x, y) per slot [m], for a PlumeSource.

None

Returns:

Type Description
CoupledProblem

The problem, with a log_emission_rate block over the active slots and a

CoupledProblem

background block.

Raises:

Type Description
ValueError

When active does not match the slots or has none on.

Source code in src/plumax/coupled/_src/k_sources.py
def build_masked_k_problem(
    instruments: Sequence[Instrument],
    *,
    transport: PlumeSource | TransportBackend,
    prior: MaskedKPrior,
    observations: Mapping[str, Array],
    active: Bool[Array, " source"],
    candidate_locations: Float[Array, "source 2"] | None = None,
) -> CoupledProblem:
    """The coupled problem of one active set, for the MAP and Laplace path.

    y_i = Σ_{k active} Q_k r_i(x_k, y_k) + c_bg + ε_i over log Q_k and c_bg, under the
    same lognormal prior as the slots. The background is the Gaussian N(0, σ²_bg) here,
    against the sampler's HalfNormal(σ_bg): the block prior is Gaussian, and the two
    have the same curvature at zero. Hand it to :func:`~plumax.coupled.solve_coupled`,
    which solves on vardax. This is the operational path; the active set itself comes
    from :func:`infer_masked_k_sources` or from the caller.

    Args:
        instruments: The observing instruments.
        transport: The transport backend.
        prior: The slot prior.
        observations: Observations by instrument.
        active: a_k, with at least one slot on.
        candidate_locations: Fixed ``(x, y)`` per slot [m], for a ``PlumeSource``.

    Returns:
        The problem, with a ``log_emission_rate`` block over the active slots and a
        ``background`` block.

    Raises:
        ValueError: When ``active`` does not match the slots or has none on.
    """
    mask = np.asarray(active, dtype=bool)
    matrices = slot_responses(transport, instruments, candidate_locations)
    if mask.shape != (prior.k_max,) or not mask.any():
        raise ValueError(
            f"build_masked_k_problem: active must have shape ({prior.k_max},) with "
            f"at least one slot on, got {mask.tolist()}."
        )
    emission = LognormalEmission.from_moments(prior.emission_mean, prior.emission_std)
    num_active = int(mask.sum())
    forward = CoupledForward(
        source=transport,
        instruments=tuple(instruments),
        responses=tuple(matrix[:, mask] for matrix in matrices),
    )
    coupled_prior = CoupledPrior.from_std(
        {
            "log_emission_rate": emission.loc * jnp.ones(num_active),
            "background": 0.0,
        },
        {
            "log_emission_rate": emission.scale * jnp.ones(num_active),
            "background": prior.background_std,
        },
    )
    return CoupledProblem(
        forward=forward, prior=coupled_prior, observations=dict(observations)
    )

infer_masked_k_sources

infer_masked_k_sources(observations: Mapping[str, Array], *, instruments: Sequence[Instrument], transport: PlumeSource | TransportBackend, prior: MaskedKPrior, candidate_locations: Float[Array, 'source 2'] | None = None, source_bounds: tuple[tuple[float, float], tuple[float, float]] | None = None, num_warmup: int = 500, num_samples: int = 1000, seed: int = 0) -> MultiSourcePosterior

Posterior over the active count and the per-slot Q_k, from every instrument.

Tier I's runner on :func:masked_k_coupled_model: NUTS for the continuous sites, a Gibbs step for the a_k.

Parameters:

Name Type Description Default
observations Mapping[str, Array]

Column observations by instrument.

required
instruments Sequence[Instrument]

The observing instruments.

required
transport PlumeSource | TransportBackend

The transport backend.

required
prior MaskedKPrior

The slot prior.

required
candidate_locations Float[Array, 'source 2'] | None

Fixed (x, y) per slot [m].

None
source_bounds tuple[tuple[float, float], tuple[float, float]] | None

Box of free slots, instead of candidates.

None
num_warmup int

NUTS warm-up steps.

500
num_samples int

Posterior draws.

1000
seed int

PRNG seed.

0

Returns:

Type Description
MultiSourcePosterior

The posterior: count_probabilities() is P(K | y), and per_source(k)

MultiSourcePosterior

the slot's summary, which population.event_from_posterior accepts.

Raises:

Type Description
ValueError

On missing observations or an invalid slot layout.

Source code in src/plumax/coupled/_src/k_sources.py
def infer_masked_k_sources(
    observations: Mapping[str, Array],
    *,
    instruments: Sequence[Instrument],
    transport: PlumeSource | TransportBackend,
    prior: MaskedKPrior,
    candidate_locations: Float[Array, "source 2"] | None = None,
    source_bounds: tuple[tuple[float, float], tuple[float, float]] | None = None,
    num_warmup: int = 500,
    num_samples: int = 1000,
    seed: int = 0,
) -> MultiSourcePosterior:
    """Posterior over the active count and the per-slot Q_k, from every instrument.

    Tier I's runner on :func:`masked_k_coupled_model`: NUTS for the continuous sites,
    a Gibbs step for the a_k.

    Args:
        observations: Column observations by instrument.
        instruments: The observing instruments.
        transport: The transport backend.
        prior: The slot prior.
        candidate_locations: Fixed ``(x, y)`` per slot [m].
        source_bounds: Box of free slots, instead of candidates.
        num_warmup: NUTS warm-up steps.
        num_samples: Posterior draws.
        seed: PRNG seed.

    Returns:
        The posterior: ``count_probabilities()`` is P(K | y), and ``per_source(k)``
        the slot's summary, which ``population.event_from_posterior`` accepts.

    Raises:
        ValueError: On missing observations or an invalid slot layout.
    """
    from plumax.gauss_plume._src.inference import (
        _check_multi_source_layout,
        _run_masked_k,
    )

    names = {instrument.name for instrument in instruments}
    if set(observations) != names:
        raise ValueError(
            f"infer_masked_k_sources: observations for {sorted(observations)} but "
            f"the instruments are {sorted(names)}."
        )
    fixed_slots = source_bounds is None
    is_plume = isinstance(transport, PlumeSource)
    if is_plume or not fixed_slots:
        _check_multi_source_layout(
            prior.k_max, candidate_locations, source_bounds, prior.prior_active
        )
    if not fixed_slots and not is_plume:
        raise ValueError(
            "infer_masked_k_sources: free slots rerun the Tier I plume and need a "
            "PlumeSource."
        )
    fixed_responses = None
    if fixed_slots:
        fixed_responses = slot_responses(transport, instruments, candidate_locations)
        widths = {matrix.shape[-1] for matrix in fixed_responses}
        if widths != {prior.k_max}:
            raise ValueError(
                f"infer_masked_k_sources: the responses have {widths} slots but "
                f"k_max is {prior.k_max}."
            )
    layout = candidate_locations
    if layout is None and fixed_slots:
        # a backend's slots have no coordinates of their own
        layout = jnp.full((prior.k_max, 2), jnp.nan)
    return _run_masked_k(
        masked_k_coupled_model,
        observations,
        k_max=prior.k_max,
        candidate_locations=layout,
        prior_active=prior.prior_active,
        num_warmup=num_warmup,
        num_samples=num_samples,
        num_chains=1,
        seed=seed,
        progress_bar=False,
        instruments=instruments,
        transport=transport,
        source_bounds=source_bounds,
        emission_mean=prior.emission_mean,
        emission_std=prior.emission_std,
        background_std=prior.background_std,
        fixed_responses=fixed_responses,
    )

masked_k_coupled_model

masked_k_coupled_model(observations: Mapping[str, Array] | None, *, instruments: Sequence[Instrument], transport: PlumeSource | TransportBackend, k_max: int, candidate_locations: Float[Array, 'source 2'] | None = None, source_bounds: tuple[tuple[float, float], tuple[float, float]] | None = None, prior_active: float = 0.3, emission_mean: float = 0.1, emission_std: float = 0.05, background_std: float = 1e-06, fixed_responses: Sequence[Array] | None = None) -> None

NumPyro masked-K model over every instrument's columns.

y_i ~ Normal(Σ_k a_k Q_k r_i(x_k, y_k) + c_bg, Σ_ε,i), with Σ_ε,i and the mask of each :class:~plumax.coupled.Instrument, under Tier I's slot prior. With source_bounds the slots move, so a PlumeSource is rerun at each draw.

Parameters:

Name Type Description Default
observations Mapping[str, Array] | None

Column observations by instrument, or None to predict.

required
instruments Sequence[Instrument]

The observing instruments.

required
transport PlumeSource | TransportBackend

The transport backend.

required
k_max int

K_max.

required
candidate_locations Float[Array, 'source 2'] | None

Fixed (x, y) per slot [m].

None
source_bounds tuple[tuple[float, float], tuple[float, float]] | None

Box of free, x-ordered slots; needs a PlumeSource.

None
prior_active float

p_active.

0.3
emission_mean float

Real-scale prior mean of each Q_k [kg/s].

0.1
emission_std float

Real-scale prior standard deviation of each Q_k [kg/s].

0.05
background_std float

HalfNormal scale of the background column.

1e-06
fixed_responses Sequence[Array] | None

:func:slot_responses, when the slots are fixed; passed in so they are computed once rather than at every model evaluation.

None
Source code in src/plumax/coupled/_src/k_sources.py
def masked_k_coupled_model(
    observations: Mapping[str, Array] | None,
    *,
    instruments: Sequence[Instrument],
    transport: PlumeSource | TransportBackend,
    k_max: int,
    candidate_locations: Float[Array, "source 2"] | None = None,
    source_bounds: tuple[tuple[float, float], tuple[float, float]] | None = None,
    prior_active: float = 0.3,
    emission_mean: float = 0.1,
    emission_std: float = 0.05,
    background_std: float = 1e-6,
    fixed_responses: Sequence[Array] | None = None,
) -> None:
    """NumPyro masked-K model over every instrument's columns.

    y_i ~ Normal(Σ_k a_k Q_k r_i(x_k, y_k) + c_bg, Σ_ε,i), with Σ_ε,i and the mask of
    each :class:`~plumax.coupled.Instrument`, under Tier I's slot prior. With
    ``source_bounds`` the slots move, so a ``PlumeSource`` is rerun at each draw.

    Args:
        observations: Column observations by instrument, or ``None`` to predict.
        instruments: The observing instruments.
        transport: The transport backend.
        k_max: K_max.
        candidate_locations: Fixed ``(x, y)`` per slot [m].
        source_bounds: Box of free, x-ordered slots; needs a ``PlumeSource``.
        prior_active: p_active.
        emission_mean: Real-scale prior mean of each Q_k [kg/s].
        emission_std: Real-scale prior standard deviation of each Q_k [kg/s].
        background_std: HalfNormal scale of the background column.
        fixed_responses: :func:`slot_responses`, when the slots are fixed; passed in so
            they are computed once rather than at every model evaluation.
    """
    import numpyro
    import numpyro.distributions as dist

    from plumax.gauss_plume._src.inference import _masked_source_prior

    sources, background = _masked_source_prior(
        k_max=k_max,
        candidate_locations=candidate_locations,
        source_bounds=source_bounds,
        prior_emission_rate_mean=emission_mean,
        prior_emission_rate_std=emission_std,
        prior_active=prior_active,
        background_prior_std=background_std,
    )
    # a_k Q_k
    active_rates = sources.active * sources.emission_rate
    for index, instrument in enumerate(instruments):
        if fixed_responses is not None:
            design = fixed_responses[index]
        else:
            # x_k = (x_k, y_k)
            locations = einx.id(
                "source, source -> source (1 + 1)", sources.x, sources.y
            )
            design = slot_responses(transport, [instrument], locations)[0]
        # Σ_k a_k Q_k r_i(x_k, y_k) + c_bg
        predicted = design @ active_rates + background
        noise_std = jnp.sqrt(instrument.observation_variance())
        keep = instrument.observation_mask() > 0.0
        likelihood = dist.Normal(predicted, noise_std).mask(keep)
        observed = None
        if observations is not None:
            # masked pixels may hold anything, and the mask drops them
            observed = jnp.where(keep, jnp.asarray(observations[instrument.name]), 0.0)
        numpyro.sample(f"obs_{instrument.name}", likelihood.to_event(1), obs=observed)

saturation_rate

saturation_rate(posteriors: Sequence[MultiSourcePosterior]) -> float

Fraction of overpasses whose most probable active count is K_max.

K̂ = argmax_k P(K = k | y), rate = #{K̂ = K_max} / N. Above 0.05 the cap is binding and the RJMCMC model is due (see the module docstring).

Parameters:

Name Type Description Default
posteriors Sequence[MultiSourcePosterior]

One masked-K posterior per overpass.

required

Returns:

Type Description
float

The saturated fraction.

Raises:

Type Description
ValueError

With no posteriors.

Examples:

One overpass at the cap, one below it:

>>> import numpy as np
>>> def posterior(active):
...     shape = np.shape(active)
...     return MultiSourcePosterior(
...         emission_rate=np.ones(shape),
...         x=np.zeros(shape),
...         y=np.zeros(shape),
...         active=np.asarray(active),
...         background=np.zeros(shape[0]),
...     )
>>> full = posterior([[True, True], [True, True]])
>>> partial = posterior([[True, False], [True, False]])
>>> saturation_rate([full, partial])
0.5
Source code in src/plumax/coupled/_src/k_sources.py
def saturation_rate(posteriors: Sequence[MultiSourcePosterior]) -> float:
    """Fraction of overpasses whose most probable active count is K_max.

    K̂ = argmax_k P(K = k | y), rate = #{K̂ = K_max} / N. Above 0.05 the cap is binding
    and the RJMCMC model is due (see the module docstring).

    Args:
        posteriors: One masked-K posterior per overpass.

    Returns:
        The saturated fraction.

    Raises:
        ValueError: With no posteriors.

    Examples:
        One overpass at the cap, one below it:

        >>> import numpy as np
        >>> def posterior(active):
        ...     shape = np.shape(active)
        ...     return MultiSourcePosterior(
        ...         emission_rate=np.ones(shape),
        ...         x=np.zeros(shape),
        ...         y=np.zeros(shape),
        ...         active=np.asarray(active),
        ...         background=np.zeros(shape[0]),
        ...     )
        >>> full = posterior([[True, True], [True, True]])
        >>> partial = posterior([[True, False], [True, False]])
        >>> saturation_rate([full, partial])
        0.5
    """
    if not posteriors:
        raise ValueError("saturation_rate: no posteriors given.")
    saturated = [
        int(np.argmax(posterior.count_probabilities())) == posterior.k_max
        for posterior in posteriors
    ]
    return float(np.mean(saturated))

slot_responses

slot_responses(transport: PlumeSource | TransportBackend, instruments: Sequence[Instrument], candidate_locations: Float[Array, 'source 2'] | None = None) -> list[Array]

Unit-emission column of every slot, as one design matrix per instrument.

R_i[n, k] = r_i(x_k, y_k) at receptor n. The Tier I plume is rerun at each candidate. Any other backend has its emission parameters as the slots already: its column_response must return the (obs, source) matrix.

Parameters:

Name Type Description Default
transport PlumeSource | TransportBackend

The transport backend.

required
instruments Sequence[Instrument]

The observing instruments.

required
candidate_locations Float[Array, 'source 2'] | None

(x, y) per slot [m], for a PlumeSource.

None

Returns:

Type Description
list[Array]

One (obs, source) matrix per instrument.

Raises:

Type Description
ValueError

For a PlumeSource without candidates, or a backend with candidates, or whose response is not a matrix.

Source code in src/plumax/coupled/_src/k_sources.py
def slot_responses(
    transport: PlumeSource | TransportBackend,
    instruments: Sequence[Instrument],
    candidate_locations: Float[Array, "source 2"] | None = None,
) -> list[Array]:
    """Unit-emission column of every slot, as one design matrix per instrument.

    R_i[n, k] = r_i(x_k, y_k) at receptor n. The Tier I plume is rerun at each
    candidate. Any other backend has its emission parameters as the slots already:
    its ``column_response`` must return the ``(obs, source)`` matrix.

    Args:
        transport: The transport backend.
        instruments: The observing instruments.
        candidate_locations: ``(x, y)`` per slot [m], for a ``PlumeSource``.

    Returns:
        One ``(obs, source)`` matrix per instrument.

    Raises:
        ValueError: For a ``PlumeSource`` without candidates, or a backend with
            candidates, or whose response is not a matrix.
    """
    if isinstance(transport, PlumeSource):
        if candidate_locations is None:
            raise ValueError(
                "slot_responses: a PlumeSource needs candidate_locations (x, y)."
            )
        locations = jnp.asarray(candidate_locations, dtype=float)
        wind = jnp.asarray([transport.wind_speed, transport.wind_direction])

        def design(instrument: Instrument) -> Array:
            response = jax.vmap(plume_response, (None, None, 0, None), 1)
            return response(transport, instrument, locations, wind)

        return [design(instrument) for instrument in instruments]
    if candidate_locations is not None:
        raise ValueError(
            "slot_responses: only a PlumeSource reruns at candidate_locations; another "
            "backend's emission parameters are its slots."
        )
    matrices = [transport.column_response(instrument) for instrument in instruments]
    if any(jnp.ndim(matrix) != 2 for matrix in matrices):
        raise ValueError(
            "slot_responses: the backend must return one column per slot, (obs, source)."
        )
    return [jnp.asarray(matrix, dtype=float) for matrix in matrices]

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],
    )

apply_quality

apply_quality(instrument: Instrument, flags: Int[Array, ' obs'] | None = None, policy: QualityPolicy | None = None) -> Instrument

The instrument with its flags and the policy's mask or inflation set.

m_i = 0 for a rejected pixel under MASK; R_ii ← κ R_ii under INFLATE. The geometry, kernel and error budget are unchanged, so the coupled forward's responses stay valid. The result depends only on the flags and the policy, so applying it twice is the same as once.

Parameters:

Name Type Description Default
instrument Instrument

The instrument to screen.

required
flags Int[Array, ' obs'] | None

Per-pixel bit flags. Default: the instrument's own flags (all clear when it has none).

None
policy QualityPolicy | None

The quality policy. Default QualityPolicy() (mask cloud and failed convergence).

None

Returns:

Type Description
Instrument

A copy of instrument with flags, mask and

Instrument

variance_inflation set.

Examples:

Mask the cloudy pixel of three:

>>> import jax.numpy as jnp
>>> from plumax.coupled import Instrument
>>> instrument = Instrument("A", jnp.zeros((3, 2)))
>>> flags = jnp.array([0, QualityFlag.CLOUD, QualityFlag.AOD])
>>> apply_quality(instrument, flags).observation_mask().tolist()
[1.0, 0.0, 1.0]

Inflate instead, by 100:

>>> inflate = QualityPolicy(FlagPolicy.INFLATE, inflate_factor=100.0)
>>> apply_quality(instrument, flags, inflate).observation_variance().tolist()
[1.0, 100.0, 1.0]
Source code in src/plumax/coupled/_src/quality.py
def apply_quality(
    instrument: Instrument,
    flags: Int[Array, " obs"] | None = None,
    policy: QualityPolicy | None = None,
) -> Instrument:
    """The instrument with its flags and the policy's mask or inflation set.

    m_i = 0 for a rejected pixel under ``MASK``; R_ii ← κ R_ii under
    ``INFLATE``. The geometry, kernel and error budget are unchanged, so the
    coupled forward's responses stay valid. The result depends only on the
    flags and the policy, so applying it twice is the same as once.

    Args:
        instrument: The instrument to screen.
        flags: Per-pixel bit flags. Default: the instrument's own ``flags``
            (all clear when it has none).
        policy: The quality policy. Default ``QualityPolicy()`` (mask cloud
            and failed convergence).

    Returns:
        A copy of ``instrument`` with ``flags``, ``mask`` and
        ``variance_inflation`` set.

    Examples:
        Mask the cloudy pixel of three:

        >>> import jax.numpy as jnp
        >>> from plumax.coupled import Instrument
        >>> instrument = Instrument("A", jnp.zeros((3, 2)))
        >>> flags = jnp.array([0, QualityFlag.CLOUD, QualityFlag.AOD])
        >>> apply_quality(instrument, flags).observation_mask().tolist()
        [1.0, 0.0, 1.0]

        Inflate instead, by 100:

        >>> inflate = QualityPolicy(FlagPolicy.INFLATE, inflate_factor=100.0)
        >>> apply_quality(instrument, flags, inflate).observation_variance().tolist()
        [1.0, 100.0, 1.0]
    """
    policy = QualityPolicy() if policy is None else policy
    if flags is None and instrument.flags is not None:
        flags = jnp.asarray(instrument.flags)
    if flags is None:
        flags = jnp.zeros(instrument.n_obs, dtype=int)
    rejected = policy.rejected(flags)
    if policy.policy is FlagPolicy.MASK:
        # m_i = 0 for a rejected pixel
        mask = jnp.where(rejected, 0.0, 1.0)
        return dataclasses.replace(
            instrument, flags=jnp.asarray(flags), mask=mask, variance_inflation=None
        )
    # κ_i = κ for a rejected pixel, 1 otherwise
    inflation = jnp.where(rejected, policy.inflate_factor, 1.0)
    return dataclasses.replace(
        instrument, flags=jnp.asarray(flags), mask=None, variance_inflation=inflation
    )

contribution_report

contribution_report(instruments: Sequence[Instrument]) -> dict[str, int]

Pixels each instrument contributes at full weight, by name.

Masked pixels and inflated pixels both count as not contributing in full, so the report is the effective per-instrument observation count the design asks to keep auditable.

Parameters:

Name Type Description Default
instruments Sequence[Instrument]

The instruments of a fusion.

required

Returns:

Type Description
dict[str, int]

{name: pixel count}.

Raises:

Type Description
ValueError

If two instruments share a name.

Examples:

>>> import jax.numpy as jnp
>>> from plumax.coupled import Instrument
>>> clear = Instrument("A", jnp.zeros((2, 2)))
>>> cloudy = apply_quality(
...     Instrument("B", jnp.zeros((2, 2))), jnp.full(2, QualityFlag.CLOUD)
... )
>>> contribution_report([clear, cloudy])
{'A': 2, 'B': 0}
Source code in src/plumax/coupled/_src/quality.py
def contribution_report(instruments: Sequence[Instrument]) -> dict[str, int]:
    """Pixels each instrument contributes at full weight, by name.

    Masked pixels and inflated pixels both count as not contributing in full,
    so the report is the effective per-instrument observation count the design
    asks to keep auditable.

    Args:
        instruments: The instruments of a fusion.

    Returns:
        ``{name: pixel count}``.

    Raises:
        ValueError: If two instruments share a name.

    Examples:
        >>> import jax.numpy as jnp
        >>> from plumax.coupled import Instrument
        >>> clear = Instrument("A", jnp.zeros((2, 2)))
        >>> cloudy = apply_quality(
        ...     Instrument("B", jnp.zeros((2, 2))), jnp.full(2, QualityFlag.CLOUD)
        ... )
        >>> contribution_report([clear, cloudy])
        {'A': 2, 'B': 0}
    """
    names = [instrument.name for instrument in instruments]
    if len(set(names)) != len(names):
        raise ValueError(f"contribution_report: instrument names repeat: {names}.")
    return {
        instrument.name: int(full_weight_pixels(instrument))
        for instrument in instruments
    }

stack_observations

stack_observations(instruments: Sequence[Instrument], observations: Sequence[Float[Array, ' ...']], *, masks: Sequence[Float[Array, ' ...']] | None = None, variances: Sequence[Float[Array, ' ...']] | None = None) -> StackedObservations

Stack the instruments' observations, masks and variances for vardax.

Each instrument's observation, mask and variance is flattened and the blocks are concatenated; this is the one place that checks the shapes and zeroes the masked pixels.

Parameters:

Name Type Description Default
instruments Sequence[Instrument]

The instruments, with any quality policy already applied.

required
observations Sequence[Float[Array, ' ...']]

One observation vector per instrument, aligned with instruments. Masked entries may hold anything, NaN included.

required
masks Sequence[Float[Array, ' ...']] | None

A mask per instrument in place of its observation_mask(), for observations with more than one value per pixel (a radiance channel axis). The observation must have the mask's shape.

None
variances Sequence[Float[Array, ' ...']] | None

A variance per instrument in place of its observation_variance(), with the shape of the mask.

None

Returns:

Type Description
StackedObservations

The stacked observations, masked entries set to zero.

Raises:

Type Description
ValueError

On a count or shape mismatch.

Examples:

A NaN under the mask becomes a zero:

>>> import jax.numpy as jnp
>>> from plumax.coupled import Instrument
>>> instrument = Instrument("A", jnp.zeros((2, 2)), mask=jnp.array([1.0, 0.0]))
>>> stacked = stack_observations([instrument], [jnp.array([3.0, jnp.nan])])
>>> stacked.values.tolist(), stacked.mask.tolist()
([3.0, 0.0], [1.0, 0.0])
Source code in src/plumax/coupled/_src/quality.py
def stack_observations(
    instruments: Sequence[Instrument],
    observations: Sequence[Float[Array, " ..."]],
    *,
    masks: Sequence[Float[Array, " ..."]] | None = None,
    variances: Sequence[Float[Array, " ..."]] | None = None,
) -> StackedObservations:
    """Stack the instruments' observations, masks and variances for vardax.

    Each instrument's observation, mask and variance is flattened and the
    blocks are concatenated; this is the one place that checks the shapes and
    zeroes the masked pixels.

    Args:
        instruments: The instruments, with any quality policy already applied.
        observations: One observation vector per instrument, aligned with
            ``instruments``. Masked entries may hold anything, NaN included.
        masks: A mask per instrument in place of its ``observation_mask()``,
            for observations with more than one value per pixel (a radiance
            channel axis). The observation must have the mask's shape.
        variances: A variance per instrument in place of its
            ``observation_variance()``, with the shape of the mask.

    Returns:
        The stacked observations, masked entries set to zero.

    Raises:
        ValueError: On a count or shape mismatch.

    Examples:
        A NaN under the mask becomes a zero:

        >>> import jax.numpy as jnp
        >>> from plumax.coupled import Instrument
        >>> instrument = Instrument("A", jnp.zeros((2, 2)), mask=jnp.array([1.0, 0.0]))
        >>> stacked = stack_observations([instrument], [jnp.array([3.0, jnp.nan])])
        >>> stacked.values.tolist(), stacked.mask.tolist()
        ([3.0, 0.0], [1.0, 0.0])
    """
    if len(observations) != len(instruments):
        raise ValueError(
            f"stack_observations: got {len(observations)} observation vectors for "
            f"{len(instruments)} instruments."
        )
    values, mask_blocks, variance_blocks = [], [], []
    for index, (instrument, observation) in enumerate(
        zip(instruments, observations, strict=True)
    ):
        mask = instrument.observation_mask() if masks is None else masks[index]
        variance = (
            instrument.observation_variance() if variances is None else variances[index]
        )
        if np.shape(observation) != mask.shape:
            raise ValueError(
                f"stack_observations: observation for {instrument.name!r} must be "
                f"{mask.shape}; got {np.shape(observation)}."
            )
        # y_i = 0 where m_i = 0, so a NaN never reaches the cost
        filled = jnp.where(mask > 0.0, jnp.asarray(observation, dtype=float), 0.0)
        values.append(einx.id("... -> (...)", filled))
        mask_blocks.append(einx.id("... -> (...)", mask))
        variance_blocks.append(einx.id("... -> (...)", variance))
    return StackedObservations(
        values=jnp.concatenate(values),
        mask=jnp.concatenate(mask_blocks),
        variance=jnp.concatenate(variance_blocks),
    )

column_mass_to_delta_vmr

column_mass_to_delta_vmr(column_mass_kg_m2: Array | float, *, p_atm: Float[ArrayLike, ''], T_K: Float[ArrayLike, ''], path_length_cm: Float[ArrayLike, '']) -> jax.Array

Convert a plume column mass enhancement [kg/m²] to a gas ΔVMR.

The Tier I plume column integral gives a column mass enhancement m [kg/m²] of methane sitting above the pixel. The radtrax slab Beer–Lambert forward instead parameterises absorption by the enhancement in volume mixing ratio ΔVMR over the absorbing path. The column in ppm·m at the layer's (p, T), :func:geophysix.columns.convert from kg/m², spread over the path length L gives it::

X = 10⁶ (m / M_CH₄) R T / p,   ΔVMR = 10⁻⁶ X / L

which is the gas column number density divided by the air column, N_gas / (n(p, T) L): the standard "slant/vertical column density divided by the air column" relation used in trace-gas retrievals (cf. the partial-column-to-VMR conversion in e.g. TROPOMI / matched-filter retrievals); keeping L and (p, T) explicit makes the per-instrument geometry auditable.

Parameters:

Name Type Description Default
column_mass_kg_m2 Array | float

Column mass enhancement [kg/m²] (scalar or array; the Tier I plume column response is linear in the emission rate Q).

required
p_atm Float[ArrayLike, '']

Layer pressure [atm], > 0.

required
T_K Float[ArrayLike, '']

Layer temperature [K], > 0.

required
path_length_cm Float[ArrayLike, '']

Vertical absorbing-path length [cm], > 0 — the depth over which the column enhancement is spread (use the same value passed to the radtrax slab forward for consistency).

required

Returns:

Type Description
Array

The dimensionless ΔVMR enhancement, same shape as

Array

column_mass_kg_m2.

Raises:

Type Description
ValueError

if p_atm, T_K or path_length_cm is non-positive (eager check, skipped under JAX tracing via _is_traced).

Source code in src/plumax/coupled/_src/rtm.py
def column_mass_to_delta_vmr(
    column_mass_kg_m2: jax.Array | float,
    *,
    p_atm: Float[ArrayLike, ""],
    T_K: Float[ArrayLike, ""],
    path_length_cm: Float[ArrayLike, ""],
) -> jax.Array:
    """Convert a plume column **mass** enhancement [kg/m²] to a gas ``ΔVMR``.

    The Tier I plume column integral gives a column **mass enhancement**
    ``m`` [kg/m²] of methane sitting above the pixel. The radtrax slab Beer–Lambert
    forward instead parameterises absorption by the *enhancement in volume
    mixing ratio* ``ΔVMR`` over the absorbing path. The column in ppm·m at the
    layer's ``(p, T)``, :func:`geophysix.columns.convert` from kg/m², spread over
    the path length ``L`` gives it::

        X = 10⁶ (m / M_CH₄) R T / p,   ΔVMR = 10⁻⁶ X / L

    which is the gas column number density divided by the air column,
    ``N_gas / (n(p, T) L)``: the standard "slant/vertical column density divided
    by the air column" relation used in trace-gas retrievals (cf. the
    partial-column-to-VMR conversion in e.g. TROPOMI / matched-filter
    retrievals); keeping ``L`` and ``(p, T)`` explicit makes the per-instrument
    geometry auditable.

    Args:
        column_mass_kg_m2: Column mass enhancement [kg/m²] (scalar or array; the
            Tier I plume column response is linear in the emission rate ``Q``).
        p_atm: Layer pressure [atm], ``> 0``.
        T_K: Layer temperature [K], ``> 0``.
        path_length_cm: Vertical absorbing-path length [cm], ``> 0`` — the depth
            over which the column enhancement is spread (use the same value
            passed to the radtrax slab forward for consistency).

    Returns:
        The dimensionless ``ΔVMR`` enhancement, same shape as
        ``column_mass_kg_m2``.

    Raises:
        ValueError: if ``p_atm``, ``T_K`` or ``path_length_cm`` is non-positive
            (eager check, skipped under JAX tracing via ``_is_traced``).
    """
    # Eager geometry validation, skipped under jit/grad/vmap (the scalars could
    # be tracers in a differentiable pipeline) — mirrors the inversion modules.
    require_positive("p_atm", p_atm, caller="column_mass_to_delta_vmr")
    require_positive("T_K", T_K, caller="column_mass_to_delta_vmr")
    require_positive(
        "path_length_cm", path_length_cm, caller="column_mass_to_delta_vmr"
    )
    column_mass = jnp.asarray(column_mass_kg_m2, dtype=float)
    pressure = jnp.asarray(p_atm, dtype=float) * ATM_TO_PA
    # X = 10⁶ (m / M) R T / p  [ppm·m]
    column_ppm_m = convert(
        column_mass,
        "kg_m2",
        "ppm_m",
        gas=CH4,
        pressure=pressure,
        temperature=jnp.asarray(T_K, dtype=float),
    )
    # L [m]
    path_length_m = jnp.asarray(path_length_cm, dtype=float) / 100.0
    # ΔVMR = 10⁻⁶ X / L
    return column_ppm_m * 1e-6 / path_length_m

linearise

linearise(operator: RadianceObservationOperator | LayeredRadianceOperator) -> LinearisedRadianceOperator

Build the :class:LinearisedRadianceOperator tangent to operator at 0.

Evaluates the background radiance L_norm(0) and the gain g = d(L_norm)/d(mass)|₀, jax.jacfwd of the operator's predict_single at zero, so the slope of :func:column_mass_to_delta_vmr is already folded in and the gain is in column-mass units. The result is exact to first order in the enhancement.

Parameters:

Name Type Description Default
operator RadianceObservationOperator | LayeredRadianceOperator

The configured nonlinear RTM observation operator.

required

Returns:

Type Description
LinearisedRadianceOperator

The matching :class:LinearisedRadianceOperator.

Source code in src/plumax/coupled/_src/rtm.py
def linearise(
    operator: RadianceObservationOperator | LayeredRadianceOperator,
) -> LinearisedRadianceOperator:
    """Build the :class:`LinearisedRadianceOperator` tangent to ``operator`` at 0.

    Evaluates the background radiance ``L_norm(0)`` and the gain
    ``g = d(L_norm)/d(mass)|₀``, ``jax.jacfwd`` of the operator's
    ``predict_single`` at zero, so the slope of
    :func:`column_mass_to_delta_vmr` is already folded in and the gain is in
    column-mass units. The result is exact to first order in the enhancement.

    Args:
        operator: The configured nonlinear RTM observation operator.

    Returns:
        The matching :class:`LinearisedRadianceOperator`.
    """
    zero = jnp.asarray(0.0)
    return LinearisedRadianceOperator(
        baseline=operator.predict_single(zero),
        # g = ∂L_norm/∂m at m = 0
        gain=jax.jacfwd(operator.predict_single)(zero),
    )

radiance_response

radiance_response(source: PlumeSource, instrument: Instrument, operator: RadianceObservationOperator | LayeredRadianceOperator, emission_rate: Array | float) -> jax.Array

Per-receptor band radiances for one instrument under the RTM operator.

The radiance-forward parallel to :func:plumax.coupled.forward.predict_observation: it evaluates the Tier I unit-Q column response (:func:plumax.coupled.forward.column_response), scales by the emission rate to get the per-receptor column mass enhancement Q · column_response [kg/m²], then maps each receptor through the RTM observation operator to a band-integrated normalised radiance.

Unlike the scalar-AK forward this is not linear in Q (Beer–Lambert is exponential in the column), so it has no closed-form fusion path; it is intended for radiance simulation and as the forward of a gradient-based / linearised L1 inversion (future build-order step), leaving the existing closed-form :func:plumax.coupled.fuse_observations AK path intact.

Parameters:

Name Type Description Default
source PlumeSource

Static source + met configuration.

required
instrument Instrument

Observing instrument (receptors + AK). The RTM operator is the physical replacement for the scalar AK, so for a pure-RTM forward leave the instrument's averaging_kernel at its identity default; a non-identity AK is still applied to the column before the RTM (it then acts as a per-receptor column-scaling factor).

required
operator RadianceObservationOperator | LayeredRadianceOperator

The configured :class:RadianceObservationOperator or :class:LayeredRadianceOperator; with either the whole map from Q to radiance is JAX and differentiable in Q.

required
emission_rate Array | float

Emission rate Q [kg/s] (scalar).

required

Returns:

Type Description
Array

Per-receptor normalised radiance, shape (n_obs, n_channels).

Source code in src/plumax/coupled/_src/rtm.py
def radiance_response(
    source: PlumeSource,
    instrument: Instrument,
    operator: RadianceObservationOperator | LayeredRadianceOperator,
    emission_rate: jax.Array | float,
) -> jax.Array:
    """Per-receptor band radiances for one instrument under the RTM operator.

    The radiance-forward parallel to :func:`plumax.coupled.forward.predict_observation`:
    it evaluates the Tier I unit-``Q`` column response
    (:func:`plumax.coupled.forward.column_response`), scales by the emission rate
    to get the per-receptor column **mass** enhancement
    ``Q · column_response`` [kg/m²], then maps each receptor through the RTM
    observation operator to a band-integrated normalised radiance.

    Unlike the scalar-AK forward this is **not** linear in ``Q`` (Beer–Lambert
    is exponential in the column), so it has no closed-form fusion path; it is
    intended for radiance simulation and as the forward of a gradient-based /
    linearised L1 inversion (future build-order step), leaving the existing
    closed-form :func:`plumax.coupled.fuse_observations` AK path intact.

    Args:
        source: Static source + met configuration.
        instrument: Observing instrument (receptors + AK). The RTM operator is
            the physical replacement for the scalar AK, so for a pure-RTM forward
            leave the instrument's ``averaging_kernel`` at its identity default;
            a non-identity AK is still applied to the column before the RTM (it
            then acts as a per-receptor column-scaling factor).
        operator: The configured :class:`RadianceObservationOperator` or
            :class:`LayeredRadianceOperator`; with either the whole map from
            ``Q`` to radiance is JAX and differentiable in ``Q``.
        emission_rate: Emission rate ``Q`` [kg/s] (scalar).

    Returns:
        Per-receptor normalised radiance, shape ``(n_obs, n_channels)``.
    """
    response = column_response(source, instrument)
    return operator.predict(jnp.asarray(emission_rate, dtype=float) * response)

radiance_response_linear

radiance_response_linear(source: PlumeSource, instrument: Instrument, operator: LinearisedRadianceOperator, emission_rate: Array | float) -> jax.Array

Per-receptor linearised radiances for one instrument (differentiable).

The tangent-linear parallel of :func:radiance_response: it scales the Tier I unit-Q column response by Q and maps each receptor through the :class:LinearisedRadianceOperator. Unlike :func:radiance_response this is linear in Q and stays in pure JAX end-to-end, so it is jax.grad / jax.jit-friendly and (single-channel) feeds the closed-form :func:plumax.coupled.fuse_observations path.

Parameters:

Name Type Description Default
source PlumeSource

Static source + met configuration.

required
instrument Instrument

Observing instrument (receptors + AK).

required
operator LinearisedRadianceOperator

The linearised radiance operator (from :func:linearise).

required
emission_rate Array | float

Emission rate Q [kg/s].

required

Returns:

Type Description
Array

Per-receptor linearised normalised radiance, shape (n_obs, n_channels).

Source code in src/plumax/coupled/_src/rtm.py
def radiance_response_linear(
    source: PlumeSource,
    instrument: Instrument,
    operator: LinearisedRadianceOperator,
    emission_rate: jax.Array | float,
) -> jax.Array:
    """Per-receptor linearised radiances for one instrument (differentiable).

    The tangent-linear parallel of :func:`radiance_response`: it scales the
    Tier I unit-``Q`` column response by ``Q`` and maps each receptor through the
    :class:`LinearisedRadianceOperator`. Unlike :func:`radiance_response` this is
    **linear in ``Q``** and stays in pure JAX end-to-end, so it is
    ``jax.grad`` / ``jax.jit``-friendly and (single-channel) feeds the
    closed-form :func:`plumax.coupled.fuse_observations` path.

    Args:
        source: Static source + met configuration.
        instrument: Observing instrument (receptors + AK).
        operator: The linearised radiance operator (from :func:`linearise`).
        emission_rate: Emission rate ``Q`` [kg/s].

    Returns:
        Per-receptor linearised normalised radiance, shape ``(n_obs, n_channels)``.
    """
    response = column_response(source, instrument)
    column_mass = jnp.asarray(emission_rate, dtype=float) * response
    return operator.predict(column_mass)