Skip to content

Factor graph models

A CouplingGraph declares a rooted tree of Gaussian-coupled variables. It holds the shape a chain cannot: a node with three or more neighbours, inferred through the ones around it. Coupling edges carry the within-slice drive child = W·parent + noise, and each node's dynamics is a GaussianTransition. A node's observation is the sensor a flat model takes, a FixedSensor or a state-dependent CallableSensor. Moving a model onto a graph keeps its sensors. Run the graph through a CouplingGraphBackend.

CouplingGraph

CouplingGraph(
    dims: Sequence[int],
    couplings: Sequence[Coupling],
    observation_models: Mapping[int, ObservationModel],
)

A rooted tree of Gaussian-coupled variables.

The N nodes are indexed 0..N-1 with dimensions dims. couplings are the tree edges, each directed from parent to child, and the root is the one node no edge points to. observation_models maps a node index to the sensor on it. A node takes the sensor a flat model takes: a FixedSensor, a state-dependent CallableSensor, or any other ObservationModel. Construction validates the wiring and raises if it is malformed.

Parameters:

Name Type Description Default
dims Sequence[int]

dims[i] is the dimension of node i; its length is the node count.

required
couplings Sequence[Coupling]

the tree edges — one per non-root node, each that node's only parent. The node left without a parent is the root.

required
observation_models Mapping[int, ObservationModel]

maps a node index to the ObservationModel that reads it.

required

Raises:

Type Description
TypeError

if a dimension is not an int, an edge is not a Coupling, or an observation model is not an ObservationModel.

ValueError

if dims is empty or non-positive; if an edge or an observation model references an out-of-range node; if an edge's coupling_matrix is not (dim[child], dim[parent]); if a sensor's C is not as wide as the node it observes; or if the edges do not form a tree — a node has two parents, more than one node has none, or the edges contain a cycle.

The four fields are read-only once built. Construction is where the wiring is checked, so a graph that needs other wiring is a new graph.

Source code in src/cpomdp/ffg/graph.py
def __init__(
    self,
    dims: Sequence[int],
    couplings: Sequence[Coupling],
    observation_models: Mapping[int, ObservationModel],
) -> None:
    self._dims = tuple(_as_int(dim, f"dims[{i}]") for i, dim in enumerate(dims))
    self._couplings = tuple(couplings)
    self._observation_models = dict(observation_models)
    self._validate()
    self._root = self._find_root()
    self._sensor_at_zero = self._linearize_sensors_at_zero()
    self._parent_edge = {edge.child: edge for edge in self._couplings}
    # Deepest first, so a child folds into its parent before the parent moves up.
    self._collect_order = tuple(
        sorted(self._parent_edge, key=self._depth, reverse=True)
    )

root property

root: int

The one node no coupling points to, which the tree hangs from.

dims property

dims: tuple[int, ...]

dims[i] is the dimension of node i.

couplings property

couplings: tuple[Coupling, ...]

The tree edges, directed away from the root.

observation_models property

observation_models: Mapping[int, ObservationModel]

Each observed node's sensor, keyed by node index. A read-only view.

infer_root

infer_root(
    readings: Mapping[int, ArrayLike], prior: Belief
) -> Belief

Compute the marginal belief at the root from per-node readings and a prior.

Each reading becomes a message about its node; those messages are passed up the tree through the couplings and combined at the root with the prior, giving the root's posterior over every reading. Only the root is converted to and from moment form — once to lift the prior in, once to read the result out — while every message in between stays in canonical form.

The reading comes first and the belief second, the order InferenceBackend.infer_states takes.

Parameters:

Name Type Description Default
readings Mapping[int, ArrayLike]

maps a node index to that node's observation. Each such node must carry a fixed sensor, since static inference has no predicted mean to evaluate a state-dependent R(x) at.

required
prior Belief

the belief on the root node, taken as its prior.

required

Returns:

Type Description
Belief

The marginal belief at the root.

Raises:

Type Description
TypeError

if readings is not a mapping or prior is not a Belief.

ValueError

if prior is not over the root's state, or a reading is on a node with no sensor, on a node whose sensor is state-dependent, or not as wide as its sensor.

Source code in src/cpomdp/ffg/graph.py
def infer_root(self, readings: Mapping[int, ArrayLike], prior: Belief) -> Belief:
    """Compute the marginal belief at the root from per-node readings and a prior.

    Each reading becomes a message about its node; those messages are passed up the
    tree through the couplings and combined at the root with the prior, giving the
    root's posterior over every reading. Only the root is converted to and from
    moment form — once to lift the prior in, once to read the result out — while
    every message in between stays in canonical form.

    The reading comes first and the belief second, the order
    [`InferenceBackend.infer_states`][cpomdp.InferenceBackend.infer_states] takes.

    Args:
        readings: maps a node index to that node's observation. Each such node must
            carry a fixed sensor, since static inference has no predicted mean to
            evaluate a state-dependent ``R(x)`` at.
        prior: the belief on the root node, taken as its prior.

    Returns:
        The marginal belief at the root.

    Raises:
        TypeError: if ``readings`` is not a mapping or ``prior`` is not a
            ``Belief``.
        ValueError: if ``prior`` is not over the root's state, or a reading is on
            a node with no sensor, on a node whose sensor is state-dependent, or
            not as wide as its sensor.
    """
    self._check_readings(readings)
    self._check_prior(prior)

    # Lift the moment-form prior into a canonical message on the root.
    prior_precision = jnp.linalg.inv(prior.cov)  # Λ₀ = Σ⁻¹
    prior_msg = CanonicalGaussian._unchecked(
        prior_precision, prior_precision @ prior.mean
    )  # h₀ = Λ₀μ; invariant-preserving lift of a validated Belief — no re-validate

    # Seed each observed node with its reading's message, then fold in the prior at
    # the root (which may already hold the root's own observation).
    acc = {
        node: self._observation_message(node, reading)
        for node, reading in readings.items()
    }
    acc[self.root] = _combine(acc, self.root, prior_msg)

    # Pass messages up to the root, deepest nodes first.
    for node in self._collect_order:
        if node not in acc:  # an unobserved leaf has nothing to send up
            continue
        edge = self._parent_edge[node]
        # Summarise everything known at `node` onto its parent, eliminating `node`.
        up = edge._message_to_parent(acc[node])
        acc[edge.parent] = _combine(acc, edge.parent, up)

    # Read the accumulated root message back into moment form.
    mean, cov = acc[self.root].to_moment()  # Σ = Λ⁻¹, μ = Λ⁻¹h
    return Belief(mean=mean, cov=cov)

Coupling dataclass

Coupling(
    parent: int,
    child: int,
    coupling_matrix: ArrayLike,
    *,
    coupling_noise: ArrayLike,
    efe_relevant: bool = False,
)

A directed edge from a parent node to a child node: child = W·parent + noise.

parent and child are node indices, oriented so the parent is the endpoint nearer the tree's root. The edge is the linear-Gaussian factor N(child; W·parent, Q):

  • coupling_matrix — W, shape (dim[child], dim[parent]). It maps the parent's state onto the child's and need not be square.
  • coupling_noise — Q, shape (dim[child], dim[child]), positive-definite (it is inverted).

Where a GaussianTransition steps one node in time, an edge couples two nodes within a slice. The maths is the same. A node's timescale is its transition, so an edge carries none (ADR-074).

efe_relevant is a modeller's declaration that this edge carries information the instrumental epistemic depends on. It is a physics call. An edge can be observed and coupled and still carry nothing the epistemic needs. A carry partition (ADR-016) that severs a flagged edge drops the cross-temporal covariance it holds, and with it the integration of that information about a slow latent. Every graph EFE entry point refuses such a partition (ADR-018). Default False. The flag does not affect the factor or the filter.

Raises:

Type Description
TypeError

if parent or child is not an int, or efe_relevant is not a bool.

ValueError

if coupling_matrix is not 2-D, or coupling_noise is not a positive-definite matrix as tall as coupling_matrix.

Source code in src/cpomdp/ffg/graph.py
def __init__(
    self,
    parent: int,
    child: int,
    coupling_matrix: ArrayLike,
    *,
    coupling_noise: ArrayLike,
    efe_relevant: bool = False,
) -> None:
    object.__setattr__(self, "parent", _as_int(parent, "parent"))
    object.__setattr__(self, "child", _as_int(child, "child"))
    object.__setattr__(
        self, "coupling_matrix", jnp.asarray(coupling_matrix, dtype=float)
    )
    object.__setattr__(
        self, "coupling_noise", jnp.asarray(coupling_noise, dtype=float)
    )
    object.__setattr__(self, "efe_relevant", _as_bool(efe_relevant))
    self._validate()

GaussianTransition dataclass

GaussianTransition(
    dynamics_matrix: ArrayLike, *, dynamics_noise: ArrayLike
)

Tier-1 dynamics factor N(x'; Ax + b, Q): how one node steps in time.

Holds the node's fixed transition and dynamics noise. A CouplingGraphBackend takes one per node.

  • dynamics_matrix — A, shape (n, n).
  • dynamics_noise — Q, shape (n, n), positive-definite (it is inverted).
Source code in src/cpomdp/ffg/factors/linear_gaussian.py
def __init__(
    self, dynamics_matrix: ArrayLike, *, dynamics_noise: ArrayLike
) -> None:
    object.__setattr__(
        self, "dynamics_matrix", jnp.asarray(dynamics_matrix, dtype=float)
    )
    object.__setattr__(
        self, "dynamics_noise", jnp.asarray(dynamics_noise, dtype=float)
    )
    self._validate()

from_ou classmethod

from_ou(
    tau: float, *, stationary_var: float, dt: float
) -> GaussianTransition

Build a 1-D transition from Ornstein–Uhlenbeck (OU) parameters.

An Ornstein–Uhlenbeck process is a scalar state that relaxes toward zero on a timescale tau while random noise keeps it wobbling with a stationary variance stationary_var (Σ_stat). Exactly discretising it over a step dt gives the linear-Gaussian transition x' = A·x + noise(Q) (ADR-017):

A = exp(−dt / tau)             — the fraction of the state surviving a step
Q = stationary_var · (1 − A²)  — the kick that holds the stationary variance

Scalar (1-D) only: the vector OU would need a matrix exponential and a Lyapunov solve, which no cpomdp node needs.

Parameters:

Name Type Description Default
tau float

the relaxation timescale τ (same time unit as dt).

required
stationary_var float

the steady-state variance Σ_stat the node settles to; A (dynamics) and Q (dynamics_noise) are set so it holds this spread.

required
dt float

the discretisation step.

required

Returns:

Type Description
GaussianTransition

A GaussianTransition with 1×1 dynamics_matrix (A) and

GaussianTransition

dynamics_noise (Q).

Raises:

Type Description
ValueError

if tau, stationary_var or dt is not a finite positive number.

Source code in src/cpomdp/ffg/factors/linear_gaussian.py
@classmethod
def from_ou(
    cls, tau: float, *, stationary_var: float, dt: float
) -> "GaussianTransition":
    """Build a 1-D transition from Ornstein–Uhlenbeck (OU) parameters.

    An Ornstein–Uhlenbeck process is a scalar state that relaxes toward zero on a
    timescale ``tau`` while random noise keeps it wobbling with a stationary
    variance ``stationary_var`` (Σ_stat). Exactly discretising it over a step ``dt``
    gives the linear-Gaussian transition ``x' = A·x + noise(Q)`` (ADR-017):

        A = exp(−dt / tau)             — the fraction of the state surviving a step
        Q = stationary_var · (1 − A²)  — the kick that holds the stationary variance

    Scalar (1-D) only: the vector OU would need a matrix exponential and a Lyapunov
    solve, which no cpomdp node needs.

    Args:
        tau: the relaxation timescale τ (same time unit as ``dt``).
        stationary_var: the steady-state variance Σ_stat the node settles to; A
            (dynamics) and Q (dynamics_noise) are set so it holds this spread.
        dt: the discretisation step.

    Returns:
        A ``GaussianTransition`` with 1×1 ``dynamics_matrix`` (A) and
        ``dynamics_noise`` (Q).

    Raises:
        ValueError: if ``tau``, ``stationary_var`` or ``dt`` is not a finite
            positive number.
    """
    for name, value in (
        ("tau", tau),
        ("stationary_var", stationary_var),
        ("dt", dt),
    ):
        _require_positive(value, name)
    dynamics_matrix = jnp.exp(-dt / tau)  # A = e^(−dt/τ)
    dynamics_noise = stationary_var * (
        1.0 - dynamics_matrix * dynamics_matrix
    )  # Q = Σ_stat (1 − A²)
    return cls(
        jnp.reshape(dynamics_matrix, (1, 1)),
        dynamics_noise=jnp.reshape(dynamics_noise, (1, 1)),
    )

tree_flatten

tree_flatten() -> tuple[
    tuple[Float64[Array, "n n"], Float64[Array, "n n"]],
    None,
]

Leaves for JAX: (dynamics, dynamics_noise), no static aux data.

Source code in src/cpomdp/ffg/factors/linear_gaussian.py
def tree_flatten(
    self,
) -> tuple[tuple[Float64[Array, "n n"], Float64[Array, "n n"]], None]:
    """Leaves for JAX: ``(dynamics, dynamics_noise)``, no static aux data."""
    return (self.dynamics_matrix, self.dynamics_noise), None

tree_unflatten classmethod

tree_unflatten(
    aux_data: None,
    children: tuple[
        Float64[Array, "n n"], Float64[Array, "n n"]
    ],
) -> GaussianTransition

Rebuild from leaves without validating — the leaves may be tracers.

Source code in src/cpomdp/ffg/factors/linear_gaussian.py
@classmethod
def tree_unflatten(
    cls,
    aux_data: None,
    children: tuple[Float64[Array, "n n"], Float64[Array, "n n"]],
) -> "GaussianTransition":
    """Rebuild from leaves without validating — the leaves may be tracers."""
    dynamics_matrix, dynamics_noise = children
    obj = object.__new__(cls)
    object.__setattr__(obj, "dynamics_matrix", dynamics_matrix)
    object.__setattr__(obj, "dynamics_noise", dynamics_noise)
    return obj