Module contents
Lesson 5 of 27Core 110 min

Message passing: sum-product, max-product and loopy belief propagation

On a tree, variable elimination for all queries can be organized as two-pass message passing. Derive sum-product and max-product on factor graphs, outline junction trees for cyclic graphs, and study loopy belief propagation as an approximation applied to LDPC decoding.

After this lesson you can

  • Derive sum-product message equations on a factor graph and prove exactness on trees.
  • Implement max-product with backtracking to obtain the MPE configuration.
  • Explain the junction tree as cached variable elimination and estimate its cost.
  • Run damped loopy BP and empirically evaluate error and convergence.
  • Decode an LDPC code with BP over a binary symmetric channel.

Before you start

From variable elimination to reusing messages

In variable elimination we calculate a marginal by summing products in an order. If we need marginals for every node of a tree, repeating elimination per query duplicates work. Message passing retains and reuses subtree results.

A bipartite factor graph has variable nodes and factor nodes. An edge joins a variable to every factor containing it. For unnormalized joint ∏afa(xa)\prod_a f_a(\vb x_a), evidence can be included as a unary indicator factor. In sum-product messages are

mi→a(xi)=∏b∈N(i)∖amb→i(xi),ma→i(xi)=∑xa∖ifa(xa)∏j∈N(a)∖imj→a(xj).m_{i\to a}(x_i)=\prod_{b\in N(i)\setminus a}m_{b\to i}(x_i),\qquad m_{a\to i}(x_i)=\sum_{\vb x_{a\setminus i}}f_a(\vb x_a) \prod_{j\in N(a)\setminus i}m_{j\to a}(x_j).

An empty product equals one. A variable’s belief is proportional to the product of all incoming messages, including its evidence indicator. Normalizing each message by a positive constant preserves normalized marginals but loses scale constants: computing the partition or P(e)P(e) requires recording them or recovering them by another procedure.

InteractiveMessages on a tree
←X0X1X2X3X4
  • Current belief
  • Exact marginal

Five spins with edge potential exp(0.8 xᵢxᵢ₊₁) and optional exact evidence. Each arrow summarizes variable-to-factor and factor-to-variable steps with local evidence. The reference enumerates all 32 configurations; intermediate beliefs may still be incorrect.

Evidence
Return: 4/4
Maximum error versus enumeration0.00000
Composite updates8
Fix evidence on any spin and replay the two passes. Compare each belief with exact enumeration.

The example has five binary spins, edge potentials exp⁡(0.8xixi+1)\exp(0.8x_ix_{i+1}) and optional exact evidence. First four edges update rightward, then four leftward. Each arrow summarizes one variable-to-factor and one factor-to-variable message including local evidence; it is not the full count of directed messages in the bipartite graph. The reference enumerates all 32 configurations and filters evidence. Partial beliefs may differ from it; after both passes they match to numerical precision.

Why it works on a tree

Mentally remove an edge of the factor graph. On a tree it separates the graph into two components. A message crossing from one side to the other summarizes the sum of products of all factors on that side for each boundary-variable value. At a leaf this is immediate. Assuming the property for incoming messages, the variable rule multiplies subtrees independent given the boundary value, and the factor rule sums its internal variables. By induction, each message correctly summarizes its component.

When a variable has received messages from all neighbors, their product collects all joint factors and sums every other variable once. Normalizing yields its exact marginal. One leaf-to-root pass and another root-to-leaf pass calculate each directed message once. For a tree factor graph with EE edges, a complete schedule sends 2E2E messages; an implementation needing only variable marginals can omit messages ending at leaf factors.

The sum of products is usually positive, but small probabilities can underflow. In log space, the variable message adds log messages and the factor message uses log-sum-exp. A message can be centered by subtracting its log-sum for stability. If every state is impossible, normalization is undefined: detect incompatible evidence rather than producing undefined numbers. Kschischang, Frey and Loeliger develop the general factor-graph formulation.

A small calculation shows direction. Suppose binary variables A,BA,B, factor ϕ(A,B)=(3113)\phi(A,B)=\begin{pmatrix}3&1\\1&3\end{pmatrix} and unary factor ψ(A)=(0.8,0.2)\psi(A)=(0.8,0.2). Observing B=1B=1, the evidence-to-ϕ\phi message is (0,1)(0,1) and the ϕ\phi-to-A message is (1,3)(1,3). Multiplying it by ψ\psi gives (0.8,0.6)(0.8,0.6); after normalization, P(A=1∣B=1)=0.6/1.4=3/7P(A=1\given B=1)=0.6/1.4=3/7. The message is a table indexed by the recipient state, not a single probability.

Without evidence factor ϕ\phi would send (4,4)(4,4) after summing B’s two values, which is uniform when normalized. Changing evidence only requires updating messages whose information changed. On a tree, propagating that change over necessary edges avoids rebuilding the complete joint. In a directed network, first represent each conditional table as a factor with all parents and the child; a message’s direction in the factor graph does not signify causality.

Max-product and backtracking

Replacing sum with maximum gives max-product; in log space it is max-sum. Messages give the best value of part of the tree for each boundary value. To reconstruct one coherent MPE configuration, save the states attaining each maximum. After choosing the best root state, follow those pointers toward the leaves.

InteractiveMax-product and backtracking

Noisy observations

−
−
+
−
+
+
+
−

States reconstructed by backtracking

−
−
−
−
+
+
+
−

Eight spins, transition potential exp(0.8 xᵢxᵢ₊₁) and flip channel 0.15. The algorithm saves one predecessor per state and uses fixed tie-breaking; choosing marginal modes separately is not equivalent to backtracking.

Backtrack 8/8
Stagebacktrack
Full MPE state− − − − + + + −
Change an observation, replay the forward pass and follow pointers backward to reconstruct the complete configuration.

The chain has eight spins, coupling 0.8 and observations through a flip channel with probability 0.15. The figure actually calculates maxima in log space and saves predecessors. Ties choose the first state deterministically; multiple MPEs can exist. Separate marginal modes are no substitute: they can select a state combination that does not maximize the joint.

In a chain, each current state stores the best prefix value and preceding state that achieved it. The next step combines the best prefix for each possible predecessor, transition potential and observation contribution. At the end choose a final state and traverse saved indices. This is the same dynamic-programming structure as Viterbi, although here the transition is a potential and is not claimed to be a normalized transition matrix.

With ties, a vector of per-node maxima does not record which decisions were selected together. A fixed tie-break rule per message plus backtracking returns a coherent solution. Recovering all tied solutions would require keeping all optimal predecessors and exploring their potentially numerous combinations.

From cycles to clique trees

In a cyclic graph, elimination creates cliques through fill. A junction tree organizes cliques of a triangulation into a tree. Separators are neighboring clique intersections and must satisfy the running-intersection property: cliques containing a variable form a connected subtree. Assign each original factor to a clique containing it and pass messages between cliques over separators.

This property prevents losing or duplicating dependencies when passing between cliques. A valid construction is exact but does not remove exponential cost: with maximum cardinality qq and induced width ww, a clique can have up to qw+1q^{w+1} entries. If the order induces large cliques, storing every message also requires substantial memory. Triangulating first and checking running intersection are correctness steps, not optional details.

For example, eliminating one variable from a four-cycle connects its two neighbors. This fill creates triangular cliques that can be arranged with the shared pair as separator. The resulting tree does not imply the original graph was a tree: it groups variables until scopes have an acyclic representation. Valid triangulations and clique trees can exist for many orders with very different sizes and costs.

Loopy BP is approximate

In loopy BP the same rules apply although subtree separation no longer holds. Messages can count information more than once. Update synchronously or sequentially and damp by mixing old and new messages. Damping can stabilize oscillation but guarantees neither convergence nor accuracy. Even a stable fixed point can yield biased or overconfident beliefs.

InteractiveLoopy BP on an Ising model
  • Loopy BP
  • Exact, 512 states

3×3 grid with fixed fields [0.12, −0.08, 0.03, −0.05, 0.14, −0.10, 0.04, −0.02, 0.08]. Synchronous updates; damping mixes old and new messages. Message convergence does not imply belief accuracy.

0.8
0.3
iteration 40
Mean absolute error0.3687
Maximum message change0.000090
Change coupling and damping on a 3×3 lattice and compare with enumeration.

The lattice has nine spins, twelve edges and fixed fields shown in the figure. Enumerating 29=5122^9=512 states measures error, rarely feasible on large graphs. A fixed seed initializes nonuniform messages. Compare message change with discrepancy from reference separately: the former can be small while the latter remains large. Murphy, Weiss and Jordan empirically study approximate BP in cyclic networks.

Synchronous scheduling computes every new message from old ones and then replaces them. Sequential scheduling can immediately use updated messages, so its trajectory and stopping criterion may differ. With probability-space damping λ\lambda, the new message is λmanterior+(1−λ)mcalculado\lambda m_{\rm anterior}+(1-\lambda)m_{\rm calculado}, followed by normalization if needed. Mixing log messages directly implements a different rule, so specify the convention.

With strong coupling, an initial condition may favor one of several fixed points. In a symmetric model, true marginals reflecting a mixture of modes do not force a local approximation to represent both. Compare multiple initializations and, when feasible, an exact reference or independent method. A satisfied tolerance says the algorithm stopped changing, not how close it is to the correct answer.

Decoding with a sparse graph

An LDPC code defines binary words c\vb c through sparse parity matrix H\mat H: Hc=0\mat H\vb c=0 modulo two. Variables represent bits and each check factor equals one when its neighbors have even parity. On a binary symmetric channel with flip probability p<1/2p<1/2, the log-likelihood ratio of received bit rir_i is

Li=(1−2ri)log⁡1−pp.L_i=(1-2r_i)\log\frac{1-p}{p}.

A variable-to-check message sums the channel LLR and messages from other checks. The check-to-variable message is 2atanh⁡ ⁣∏j≠itanh⁡(Lj→a/2)2\operatorname{atanh}\!\prod_{j\ne i}\tanh(L_{j\to a}/2). Numerically clip the atanh argument near ±1. After each iteration, form hard decisions and check the syndrome. A zero syndrome indicates a valid codeword but does not prove it was transmitted.

The check rule summarizes all combinations of its other bits satisfying parity. The product of hyperbolic tangents compactly combines their differences between even and odd probabilities. LLR sign matters: under our convention positive favors bit zero. Changing convention requires consistently changing input, updates and hard decision.

The decoder has two distinct limits. Zero-syndrome stopping detects arrival at a codeword, but another codeword can explain the channel better than the one actually sent. An iteration limit bounds work if beliefs oscillate or do not satisfy checks. In both cases simulation can count errors because it retains the original word; a real receiver cannot make that comparison.

InteractiveDecode with belief propagation

Received

011111100001000011000110011100111001

BP estimate

011110100001000011000110011101111001

Systematic 36-bit code with 12 checks, generated with seed 7 and distinct information columns; 48 messages and noise are simulated with another fixed seed. BP stops on zero syndrome or after 12 iterations. Zero syndrome does not guarantee a match with the transmitted block. Rates are small-sample estimates, not an asymptotic threshold.

0.06
iteration shown 5
Nonzero syndrome checks0
Received BER, 48 blocks0.058
BER after BP, 48 blocks0.044
Blocks with errors, 480.438
Change noise and replay BP on the first block; rates come from 48 simulated blocks.

The interactive builds a systematic matrix of 12 checks and 36 bits, with 24 information bits and distinct sparse columns generated with a fixed seed. It generates 48 new blocks per seed and shows errors by comparison with the transmitted word, known only in simulation. That small sample fluctuates; it does not demonstrate a universal threshold or channel capacity. Asymptotic thresholds depend on the code family, channel and decoder.

Lab: exact messages on trees

Reproduce lesson 4’s factor class and calculate log-space messages on an arbitrary connected bipartite tree. The implementation rejects cycles and impossible evidence. Max-product saves pointers and reconstructs coherent states; sum-product returns marginals. Different cardinalities are supported.

[ ]Factors from lesson 4Browser
"""Factores tabulares con ejes nombrados e inferencia exacta discreta."""
from itertools import product
import numpy as np


class Factor:
    def __init__(self, scope, values):
        self.scope = tuple(scope)
        self.values = np.asarray(values, dtype=float)
        if len(set(self.scope)) != len(self.scope) or self.values.ndim != len(self.scope):
            raise ValueError('cada eje debe tener un nombre distinto')
        if not np.all(np.isfinite(self.values)) or np.any(self.values < 0):
            raise ValueError('los factores deben ser finitos y no negativos')

    def restrict(self, variable, value):
        if variable not in self.scope:
            return self
        axis = self.scope.index(variable)
        if not isinstance(value, (int, np.integer)) or not 0 <= value < self.values.shape[axis]:
            raise ValueError('valor de evidencia fuera del dominio')
        scope = self.scope[:axis] + self.scope[axis+1:]
        return Factor(scope, np.take(self.values, value, axis=axis))

    def __mul__(self, other):
        union = self.scope + tuple(v for v in other.scope if v not in self.scope)
        for v in set(self.scope) & set(other.scope):
            if self.values.shape[self.scope.index(v)] != other.values.shape[other.scope.index(v)]:
                raise ValueError('cardinalidades incompatibles')
        def align(factor):
            ordered = [v for v in union if v in factor.scope]
            axes = [factor.scope.index(v) for v in ordered]
            data = np.transpose(factor.values, axes) if axes else factor.values
            shape = [factor.values.shape[factor.scope.index(v)] if v in factor.scope else 1 for v in union]
            return data.reshape(shape)
        return Factor(union, align(self) * align(other))

    def sum_out(self, variable):
        if variable not in self.scope:
            return self
        axis = self.scope.index(variable)
        return Factor(self.scope[:axis] + self.scope[axis+1:], self.values.sum(axis=axis))

    def reorder(self, order):
        order = tuple(order)
        if set(order) != set(self.scope) or len(order) != len(self.scope):
            raise ValueError('orden incompatible')
        return Factor(order, np.transpose(self.values, [self.scope.index(v) for v in order]))


def factor_graph(factors):
    graph = {v: set() for factor in factors for v in factor.scope}
    for factor in factors:
        for v in factor.scope:
            graph[v].update(set(factor.scope) - {v})
    return graph


def min_fill_order(graph, candidates=None):
    """Ordena candidatos; el ancho incluye vecinos retenidos en la consulta."""
    graph = {v: set(neighbors) for v, neighbors in graph.items()}
    if any(v in ns or any(u not in graph or v not in graph[u] for u in ns) for v, ns in graph.items()):
        raise ValueError('se requiere un grafo simple no dirigido')
    remaining = set(graph) if candidates is None else set(candidates)
    if not remaining <= set(graph):
        raise ValueError('candidato ausente del grafo')
    order, width = [], 0
    while remaining:
        def score(v):
            ns = list(graph[v])
            missing = sum(b not in graph[a] for i, a in enumerate(ns) for b in ns[i+1:])
            return missing, len(ns), str(v)
        v = min(remaining, key=score)
        neighbors = list(graph[v])
        width = max(width, len(neighbors))
        for a in neighbors:
            graph[a].update(set(neighbors) - {a})
            graph[a].discard(v)
        del graph[v]
        remaining.remove(v)
        order.append(v)
    return order, width


def variable_elimination(factors, query, evidence=None):
    evidence = {} if evidence is None else dict(evidence)
    query = tuple(query)
    if not factors:
        raise ValueError('se requiere al menos un factor')
    sizes = {}
    for factor in factors:
        for variable, size in zip(factor.scope, factor.values.shape):
            if variable in sizes and sizes[variable] != size:
                raise ValueError('cardinalidades incompatibles')
            sizes[variable] = size
    graph0 = factor_graph(factors)
    if len(set(query)) != len(query) or not set(query) <= set(graph0) or set(query) & set(evidence):
        raise ValueError('consulta y evidencia deben ser variables distintas del modelo')
    if not set(evidence) <= set(graph0):
        raise ValueError('evidencia ajena al modelo')
    reduced = list(factors)
    for variable, value in evidence.items():
        reduced = [factor.restrict(variable, value) for factor in reduced]
    graph = factor_graph(reduced)
    order, width = min_fill_order(graph, set(graph) - set(query))
    for variable in order:
        bucket = [factor for factor in reduced if variable in factor.scope]
        reduced = [factor for factor in reduced if variable not in factor.scope]
        joint = bucket[0]
        for factor in bucket[1:]:
            joint = joint * factor
        reduced.append(joint.sum_out(variable))
    joint = reduced[0]
    for factor in reduced[1:]:
        joint = joint * factor
    result = joint.reorder(query)
    evidence_weight = result.values.sum()
    if evidence_weight <= 0:
        raise ValueError('evidencia con peso cero')
    return Factor(query, result.values / evidence_weight), evidence_weight, order, width


def exhaustive(factors, query, evidence=None):
    evidence = {} if evidence is None else dict(evidence)
    sizes = {}
    for factor in factors:
        for variable, size in zip(factor.scope, factor.values.shape):
            if variable in sizes and sizes[variable] != size:
                raise ValueError('cardinalidades incompatibles')
            sizes[variable] = size
    variables = tuple(sizes)
    out = np.zeros(tuple(sizes[v] for v in query))
    for values in product(*(range(sizes[v]) for v in variables)):
        state = dict(zip(variables, values))
        if any(state[v] != x for v, x in evidence.items()):
            continue
        weight = np.prod([factor.values[tuple(state[v] for v in factor.scope)] for factor in factors])
        out[tuple(state[v] for v in query)] += weight
    if out.sum() <= 0:
        raise ValueError('evidencia con peso cero')
    return out/out.sum(), out.sum()
[ ]Tree messagesBrowser
"""Sum-product y max-product en árboles de factores discretos."""
from functools import lru_cache
import numpy as np
from scipy.special import logsumexp


def tree_bp(factors,evidence=None,mode='sum'):
    """Devuelve marginales o configuración MPE y mensajes normalizados.

    factors son instancias Factor de la lección 4. La evidencia fija índices.
    El grafo bipartito debe ser conexo y acíclico, y no admite factores escalares.
    """
    if mode not in ('sum','max') or not factors:raise ValueError('modo o factores inválidos')
    evidence={} if evidence is None else dict(evidence)
    sizes={};adj={};logtables=[]
    for i,factor in enumerate(factors):
        if not factor.scope:raise ValueError('factor escalar no soportado en el árbol')
        node=('f',i);adj[node]=[]
        with np.errstate(divide='ignore'):logtables.append(np.log(factor.values))
        for v,n in zip(factor.scope,factor.values.shape):
            if v in sizes and sizes[v]!=n:raise ValueError('cardinalidades incompatibles')
            sizes[v]=n;vn=('v',v);adj.setdefault(vn,[]).append(node);adj[node].append(vn)
    if not set(evidence)<=set(sizes):raise ValueError('evidencia desconocida')
    for v,s in evidence.items():
        if not isinstance(s,(int,np.integer)) or not 0<=s<sizes[v]:raise ValueError('evidencia fuera de rango')
    root=next(v for v in adj if v[0]=='v');seen=set();stack=[root]
    while stack:
        n=stack.pop()
        if n in seen:continue
        seen.add(n);stack.extend(adj[n])
    if len(seen)!=len(adj) or sum(map(len,adj.values()))//2!=len(adj)-1:
        raise ValueError('el grafo de factores debe ser un árbol conexo')
    pointers={}
    def normalize(x):
        norm=logsumexp(x) if mode=='sum' else np.max(x)
        if not np.isfinite(norm):raise ValueError('evidencia imposible')
        return x-norm
    def local(v):
        out=np.zeros(sizes[v])
        if v in evidence:out[:]=-np.inf;out[evidence[v]]=0.
        return out
    @lru_cache(None)
    def message(src,dst):
        if src[0]=='v':
            out=local(src[1])
            for neighbor in adj[src]:
                if neighbor!=dst:out=out+message(neighbor,src)
            return normalize(out)
        i=src[1];factor=factors[i];target=dst[1];axis=factor.scope.index(target)
        table=logtables[i].copy()
        for j,v in enumerate(factor.scope):
            if v==target:continue
            shape=[1]*len(factor.scope);shape[j]=sizes[v]
            table=table+message(('v',v),src).reshape(shape)
        axes=tuple(j for j in range(len(factor.scope)) if j!=axis)
        if mode=='sum':out=logsumexp(table,axis=axes) if axes else table
        else:
            reordered=np.moveaxis(table,axis,0).reshape(sizes[target],-1)
            indices=np.argmax(reordered,axis=1)
            out=np.max(reordered,axis=1)
            other=tuple(v for v in factor.scope if v!=target)
            dims=tuple(sizes[v] for v in other)
            pointers[(src,dst)]=(other,[np.unravel_index(k,dims) if dims else () for k in indices])
        return normalize(out)
    def belief(v):
        node=('v',v);out=local(v)
        for neighbor in adj[node]:out=out+message(neighbor,node)
        return normalize(out)
    if mode=='sum':
        result={v:np.exp(belief(v)) for v in sizes}
    else:
        first=root[1];result={first:int(np.argmax(belief(first)))}
        def visit_variable(v,parent):
            node=('v',v)
            for f in adj[node]:
                if f==parent:continue
                message(f,node)
                others,choices=pointers[(f,node)]
                for u,value in zip(others,choices[result[v]]):result[u]=int(value)
                for u in others:visit_variable(u,f)
        visit_variable(first,None)
    return result,message.cache_info().currsize
[ ]Verify messages against eliminationBrowser
from itertools import product
rng=np.random.default_rng(14)
factors=[Factor(('A','B','C'),rng.uniform(.05,1,(2,3,2))),
         Factor(('C','D'),rng.uniform(.05,1,(2,2))),
         Factor(('A',),rng.uniform(.05,1,2)),Factor(('D',),rng.uniform(.05,1,2))]
for evidence in ({},{'B':1},{'A':0,'D':1}):
    marginal,nmessages=tree_bp(factors,evidence,'sum')
    for v in ('A','B','C','D'):
        if v not in evidence:
            ve,_,_,_=variable_elimination(factors,(v,),evidence)
            assert np.allclose(marginal[v],ve.values)
    mpe,_=tree_bp(factors,evidence,'max')
    def weight(state):
        return np.prod([f.values[tuple(state[v] for v in f.scope)] for f in factors])
    assignments=[dict(zip(('A','B','C','D'),s)) for s in product(range(2),range(3),range(2),range(2))]
    best=max(weight(s) for s in assignments if all(s[k]==v for k,v in evidence.items()))
    assert np.isclose(weight(mpe),best)
    print('evidencia:',evidence,'mensajes calculados:',nmessages,'MPE:',mpe,'peso:',weight(mpe))

Messages are calculated on demand and cached: some directions ending at leaf factors are unnecessary for variable marginals. The MPE check uses independent enumeration, not the maximum of marginals.

Lab: cycles and LDPC

First calculate BP and enumeration for a 3×3 Ising model. Each case prints iteration count, final message change and mean belief error. Simulations use fixed fields and seed; results do not extrapolate to every lattice.

[ ]Loopy Ising BPBrowser
"""BP síncrona amortiguada en Ising y referencia por enumeración."""
import itertools
import numpy as np
from scipy.special import logsumexp


def grid_edges(n):
    return [(j*n+i,j*n+i+1) for j in range(n) for i in range(n-1)]+[(j*n+i,(j+1)*n+i) for j in range(n-1) for i in range(n)]


def exact_ising(n,J,h):
    edges=grid_edges(n);states=np.array(list(itertools.product((-1.,1.),repeat=n*n)))
    logp=states@np.asarray(h)+J*sum(states[:,i]*states[:,j] for i,j in edges)
    p=np.exp(logp-logsumexp(logp))
    return (p[:,None]*(states==1)).sum(axis=0)


def loopy_bp(n,J,h,damping=0.,steps=100,tol=1e-9,seed=1):
    if not 0<=damping<1:raise ValueError('amortiguación en [0,1)')
    edges=grid_edges(n);neighbors=[[] for _ in range(n*n)]
    for i,j in edges:neighbors[i].append(j);neighbors[j].append(i)
    rng=np.random.default_rng(seed);messages={}
    for i in range(n*n):
        for j in neighbors[i]:
            p=rng.uniform(.4,.6,2);messages[i,j]=p/p.sum()
    spins=np.array([-1.,1.]);history=[]
    for _ in range(steps):
        new={};change=0.
        for (i,j),old in messages.items():
            field=h[i]*spins
            for k in neighbors[i]:
                if k!=j:field=field+np.log(messages[k,i])
            logm=logsumexp(field[:,None]+J*spins[:,None]*spins[None,:],axis=0)
            proposal=np.exp(logm-logsumexp(logm))
            new[i,j]=damping*old+(1-damping)*proposal
            change=max(change,np.max(abs(new[i,j]-old)))
        messages=new;history.append(change)
        if change<tol:break
    marginal=[]
    for i in range(n*n):
        logb=h[i]*spins
        for k in neighbors[i]:logb=logb+np.log(messages[k,i])
        marginal.append(np.exp(logb-logsumexp(logb))[1])
    return np.array(marginal),np.array(history)
[ ]Compare BP with enumerationBrowser
h=np.array([.12,-.08,.03,-.05,.14,-.1,.04,-.02,.08])
for J in (.2,.8,1.4):
    exact=exact_ising(3,J,h)
    for damping in (0.,.5):
        estimate,history=loopy_bp(3,J,h,damping=damping,steps=200)
        print('J, amortiguación, iteraciones, cambio, error medio:',
              J,damping,len(history),history[-1],np.mean(abs(estimate-exact)))

The next matrix has shape 12×3612\times36: H=[A∣I]H=[A\mid I], with three ones per information column. The identity block encodes twelve parity bits without inverting a matrix. Simulate 100 blocks per noise level and report received BER, post-BP BER and fraction of erroneous blocks.

For each check, the code calculates prefix and suffix products of hyperbolic tangents. This obtains the product excluding each neighbor without re-multiplying all others or dividing by a potentially zero value. The organization changes update cost, not the BP equation.

[ ]LDPC matrix and decoderBrowser
"""Código sistemático disperso y BP en log-razones para canal binario."""
import numpy as np
import math


def parity_matrix(seed=7,m=12,k=24,degree=3):
    """H=[A | I], m controles, k bits de información y grado de A fijo."""
    if not 1<=degree<=m:raise ValueError('grado inválido')
    rng=np.random.default_rng(seed);A=np.zeros((m,k),dtype=int)
    for j in range(k):A[rng.choice(m,size=degree,replace=False),j]=1
    return np.column_stack((A,np.eye(m,dtype=int)))


def encode(info,H):
    m=H.shape[0];k=H.shape[1]-m
    info=np.asarray(info,dtype=int)
    if info.shape!=(k,) or not np.array_equal(H[:,k:],np.eye(m,dtype=int)):
        raise ValueError('H debe ser sistemática y el mensaje de longitud k')
    return np.r_[info,(H[:,:k]@info)%2]


def decode_bp(received,H,p,steps=40):
    """Retorna (bits, iteraciones, síndrome cero). LLR=log P(0)/P(1)."""
    if not 0<p<.5 or steps<1:raise ValueError('p debe estar en (0,0.5)')
    received=np.asarray(received,dtype=int);H=np.asarray(H,dtype=int)
    m,n=H.shape
    if received.shape!=(n,) or np.any((received!=0)&(received!=1)):
        raise ValueError('bits incompatibles')
    if np.all((H@received)%2==0):return received.copy(),0,True
    channel=(1-2*received)*np.log((1-p)/p)
    checks=[np.flatnonzero(H[a]).tolist() for a in range(m)]
    neighbors=[np.flatnonzero(H[:,i]).tolist() for i in range(n)]
    q={(a,i):channel[i] for a in range(m) for i in checks[a]}
    r={(a,i):0. for a in range(m) for i in checks[a]}
    for iteration in range(1,steps+1):
        for a in range(m):
            values=[math.tanh(q[a,j]/2) for j in checks[a]]
            prefix=[1.]
            for value in values:prefix.append(prefix[-1]*value)
            suffix=[1.]*(len(values)+1)
            for j in range(len(values)-1,-1,-1):suffix[j]=suffix[j+1]*values[j]
            for j,i in enumerate(checks[a]):
                product=max(-1+1e-12,min(1-1e-12,prefix[j]*suffix[j+1]))
                r[a,i]=2*math.atanh(product)
        posterior=channel+np.array([sum(r[a,i] for a in neighbors[i]) for i in range(n)])
        bits=(posterior<0).astype(int)
        if np.all((H@bits)%2==0):return bits,iteration,True
        for a in range(m):
            for i in checks[a]:q[a,i]=posterior[i]-r[a,i]
    return bits,steps,False
[ ]Simulate channel and decodeBrowser
H=parity_matrix();rng=np.random.default_rng(17)
print('forma y número de unos de H:',H.shape,H.sum())
noise_levels=(.01,.03,.06,.1,.15)
raw_rates=[];decoded_rates=[];block_rates=[]
for p in noise_levels:
    before=after=blocks=0;n_blocks=100
    for _ in range(n_blocks):
        info=rng.integers(0,2,24);code=encode(info,H)
        received=code^(rng.random(len(code))<p).astype(int)
        decoded,it,ok=decode_bp(received,H,p,steps=25)
        before+=np.sum(received!=code);after+=np.sum(decoded!=code)
        blocks+=int(np.any(decoded!=code))
    raw_rates.append(before/(n_blocks*len(code)))
    decoded_rates.append(after/(n_blocks*len(code)))
    block_rates.append(blocks/n_blocks)
    print('p, BER recibida, BER BP, error de bloque:',p,raw_rates[-1],decoded_rates[-1],block_rates[-1])
[ ]Experiment ratesBrowser
import matplotlib.pyplot as plt
plt.plot(noise_levels,raw_rates,'o-',label='Recibida')
plt.plot(noise_levels,decoded_rates,'o-',label='Tras BP')
plt.xlabel('Probabilidad de inversión');plt.ylabel('Tasa de error de bit')
plt.legend();plt.grid();plt.show()

Rates use only 100 blocks per point and share a generator sequence. A zero syndrome can correspond to a different valid word; measuring errors requires knowing the transmitted word. For a reliable curve, increase block count, report uncertainty and evaluate other matrices and seeds.

Exercises

ProofInduction on messages
Prove: Prove that sum-product calculates exact marginals on a tree factor graph.
0
Each edge separates the graph into two components.

Step 1 of 3. What does a message crossing an edge summarize?

Numeric
A tree factor graph has 12 variables and 11 pairwise factors. How many directed messages are sent in two complete passes?
Quiz
When do sum-product rules with an appropriate schedule guarantee exact marginals without additional contraction assumptions?
CodeFactor-to-variable message
Implement factor_message(log_phi,incoming,target). log_phi is an array with one axis per variable; incoming is a list of log messages with None at the target axis. Add incoming messages, marginalize other axes with logsumexp and normalize output so exp(out).sum() is one.
import numpy as np
from scipy.special import logsumexp
def factor_message(log_phi,incoming,target):
  return None
Shift+Enter to run
CodeParity decoder
Implement decode(received,H,p,max_iter). H is a binary parity matrix, received a binary vector, 0<p<0.5. Use LLR log P(0)/P(1), sum-product updates and zero-syndrome stopping. Return (bits,iterations,syndrome_zero).
import numpy as np
def decode(received,H,p,max_iter):
  return np.asarray(received),0,False
Shift+Enter to run
Key idea
On a tree, each message exactly summarizes a subtree and backtracking makes the maximum coherent. With cycles, the same mechanics are approximate: check convergence, error and each experiment’s scope.