Algorithm Search⌘K

Data structureresearch

Bayes tree

Also called Bayes tree of a factor graph.

A directed tree of cliques from the elimination of a factor graph that encodes the square root information matrix and supports local updates.

Time
O(K + n w^2) buildO(n w) solveO(t w^2 + o) update
Space
O(n w) total
Where
K = the number of factors; n = the number of variables; o = the number of orphans; t = the number of variables in the removed top; w = the number of variables in the largest clique
Origin
Michael Kaess, Viorela Ila, Richard Roberts, Frank Dellaert, 2010

A Bayes tree stores the result of variable elimination on a linear Gaussian factor graph. Elimination in an order turns the factors into one Gaussian conditional per variable, Rvxv+∑sSvsxs=dvR_v x_v + \sum_s S_{vs} x_s = d_v, given its parents ss. These conditionals are the block rows of the square root information matrix RR, so they form a Bayesian network that is chordal. The Bayes tree groups the conditionals into cliques. Each clique holds frontal variables FF and separator variables SS, and the conditionals of FF given SS, and the separator lies in the parent clique. The root holds a joint density. Back substitution walks down the tree. A new factor changes only the clique where its first variable lives and the path above it to the root, so an update re-eliminates that top and keeps the rest. The tree is a directed form of the junction tree, and it is the data structure of iSAM2.

In plain words

Solving a big system of measurements one unknown at a time leaves a chain of small rules. Each rule says how to compute one unknown from a few unknowns that come later. The Bayes tree puts these rules in small groups and hangs the groups in a tree, so that a group only needs the answers of the group above it. To get the answer, start at the top and go down. When a new measurement arrives, only the groups that hold its unknowns, and the groups above them, can change. The tree removes that part, redoes it with the new measurement, and hangs the old lower branches back where they fit.

The abstract type

A Bayes tree over vector variables holds:

  • a set of cliques, each with an ordered list of frontal variables FF, a set of separator variables SS, a parent clique (none for a root) and child cliques;
  • for each frontal variable vv, a Gaussian conditional (Rv,{Svs},dv)(R_v, \{S_{vs}\}, d_v) whose parents lie in the later frontal variables of its clique and in SS;
  • a map from each variable to the clique where it is frontal.

The tree must satisfy three rules: every variable is frontal in exactly one clique, the parents of each conditional lie in its clique, and the separator of each clique lies in the variables F∪SF \cup S of its parent (the running intersection property). The tree encodes the quadratic ∑v12∥Rvxv+∑sSvsxs−dv∥2\sum_v \tfrac12\|R_v x_v + \sum_s S_{vs} x_s - d_v\|^2, which equals the sum of the input factors up to a constant.

The operations are BUILD (from factors and an elimination order), SOLVE (the minimizer of the encoded quadratic), and UPDATE (add new factors).

Representation

A clique is a record with the list of frontal variables in elimination order, the separator list, a parent pointer, a list of children, and a map from each frontal variable to its conditional. The conditional of vv holds the upper triangular RvR_v, a block SvsS_{vs} for each parent, and the vector dvd_v. The tree keeps a list of roots and a hash map from each variable to its clique. The code stores factors as 12∥∑kAkxk−b∥2\tfrac12\|\sum_k A_k x_k - b\|^2 with dense blocks, and works inside one elimination step in information form.

Operations

  1. ELIMINATE(factors, order)
  2. 1for each variable v in order do
  3. 2G ← the remaining factors whose first variable in order is v
  4. 3(conditional of v given P_v, factor on P_v) ← eliminate v from the sum of G
  5. 4put the factor on P_v with the factors of its first variable
  6. GROUP-INTO-CLIQUES(conditionals)
  7. 5for each conditional of v given P_v, in the reverse of the order do
  8. 6if P_v is empty then make a new root clique with F = [v]
  9. 7else p ← the clique of the first variable of P_v in the order
  10. 8if P_v = F_p ∪ S_p then put v at the front of F_p
  11. 9else make a new child clique of p with F = [v] and S = P_v
  12. SOLVE(tree)
  13. 10for each clique, parents before children do
  14. 11for each v in F, from the last to the first do x_v ← R_v⁻¹ (d_v - Σ_s S_vs x_s)
  15. UPDATE(tree, new factors F')
  16. 12top ← the cliques where a variable of F' is frontal, and all their ancestors
  17. 13orphans ← the children of top cliques that are not in the top
  18. 14G ← the conditionals of the top, read as factors, and the factors F'
  19. 15ELIMINATE G in a new order (the variables of F' last) and GROUP-INTO-CLIQUES
  20. 16for each orphan o do attach o under the new clique of the first variable of S_o in the new order

BUILD is ELIMINATE followed by GROUP-INTO-CLIQUES. Line L3 is one step of block Gaussian elimination: with R⊤R=ΛvvR^\top R = \Lambda_{vv} from the Cholesky decomposition, Ss=R−⊤ΛvsS_s = R^{-\top}\Lambda_{vs} and d=R−⊤ηvd = R^{-\top}\eta_v, and the factor on PvP_v is Λab−Sa⊤Sb\Lambda_{ab} - S_a^\top S_b, ηa−Sa⊤d\eta_a - S_a^\top d. QR on the stacked Jacobian rows gives the same conditionals up to the signs of the rows of RR.

Line L8 is the merge rule of Kaess et al. It puts a variable into the clique of its first parent only if its parents are all the variables of that clique. This makes each clique a clique of the chordal graph of the Bayes net.

Line L14 is valid because a conditional is itself a quadratic factor on vv and its parents. The first conditional of a clique involves all of F∪SF \cup S, so the separator of every orphan lies in one factor of GG, and after elimination it lies in one new clique. That is why line L16 can always place the orphan. iSAM2 adds relinearization to this update: it rebuilds the top from the original nonlinear factors instead of from the conditionals, and then needs the cached factors of the orphans.

Example

Three poses x1,x2,x3x_1, x_2, x_3 and two landmarks ℓ1,ℓ2\ell_1, \ell_2 lie on a line. All factors have unit noise:

factor equation
prior x1=0x_1 = 0
odometry x2−x1=1x_2 - x_1 = 1, x3−x2=1x_3 - x_2 = 1
landmark ℓ1\ell_1 ℓ1−x1=2.1\ell_1 - x_1 = 2.1, ℓ1−x2=0.9\ell_1 - x_2 = 0.9
landmark ℓ2\ell_2 ℓ2−x3=1\ell_2 - x_3 = 1

Eliminate in the order ℓ1,ℓ2,x1,x2,x3\ell_1, \ell_2, x_1, x_2, x_3. The conditionals, rounded to four digits, are:

variable RvR_v SvsS_{vs} dvd_v
ℓ1\ell_1 1.4142 x1x_1: -0.7071, x2x_2: -0.7071 2.1213
ℓ2\ell_2 1 x3x_3: -1 1
x1x_1 1.5811 x2x_2: -0.9487 -1.0119
x2x_2 1.2649 x3x_3: -0.7906 -0.2846
x3x_3 0.6124 1.2656

Grouping from x3x_3 back: x3x_3 starts the root. The parents of x2x_2 are {x3}\{x_3\}, all of the root, so x2x_2 merges into it. The parents of x1x_1 are {x2}\{x_2\}, not all of {x2,x3}\{x_2, x_3\}, so x1x_1 starts a child clique with the separator {x2}\{x_2\}. The parents of ℓ2\ell_2 are {x3}\{x_3\}, again not all of the root, so ℓ2\ell_2 starts a second child. The parents of ℓ1\ell_1 are {x1,x2}\{x_1, x_2\}, all of the clique of x1x_1, so ℓ1\ell_1 merges there. The tree is the root {x2,x3}\{x_2, x_3\} with the children {ℓ1,x1∣x2}\{\ell_1, x_1 \mid x_2\} and {ℓ2∣x3}\{\ell_2 \mid x_3\}.

SOLVE gives x3=1.2656/0.6124=2.0667x_3 = 1.2656 / 0.6124 = 2.0667 at the root, then x2=1.0667x_2 = 1.0667, then x1=0x_1 = 0 and ℓ1=2.0333\ell_1 = 2.0333 in the first child, and ℓ2=3.0667\ell_2 = 3.0667 in the second. Odometry says that x2−x1=1x_2 - x_1 = 1, and the landmark says 1.21.2. The three unit residuals of this loop share the gap of 0.20.2 equally.

Now add a pose x4x_4 with the odometry x4−x3=1x_4 - x_3 = 1. The variable x3x_3 is frontal in the root, so the top is the root only, and both children are orphans. The two root conditionals and the new factor are eliminated in the order x2,x3,x4x_2, x_3, x_4. The conditional of x2x_2 comes out the same as before. The new ones are 1.1726 x3−0.8528 x4=−0.19191.1726\,x_3 - 0.8528\,x_4 = -0.1919 and 0.5222 x4=1.60150.5222\,x_4 = 1.6015. The new root is {x3,x4}\{x_3, x_4\} with the child {x2∣x3}\{x_2 \mid x_3\}. The orphan {ℓ1,x1∣x2}\{\ell_1, x_1 \mid x_2\} goes under the clique of x2x_2, and the orphan {ℓ2∣x3}\{\ell_2 \mid x_3\} under the root. One clique was removed, two were made, and two were kept without any computation. SOLVE gives x4=3.0667x_4 = 3.0667 and leaves the other values unchanged, because the new measurement agrees with the old estimate.

Correctness

The correctness proof shows that ELIMINATE preserves the sum of the factors, that GROUP-INTO-CLIQUES gives a tree with the three rules above, and that SOLVE makes every conditional zero, which is the unique minimizer. For UPDATE it shows that the tree encodes the old system plus the new factors, and that each orphan's separator lies in the new clique where line L16 puts it. The tests compare SOLVE with a dense solve of the normal equations, and the sum of the conditionals with the dense Λ\Lambda and η\eta, on random graphs with variables of size 1 and 2, under any order and after a sequence of updates.

Proof: The Bayes tree encodes the linear system of its factors, solves it by back substitution, and stays valid and exact under updatesfull

Setting. A linear factor is qf(x)=12∥∑k∈VfAf,kxk−bf∥2q_f(x) = \tfrac12 \|\sum_{k \in V_f} A_{f,k} x_k - b_f\|^2 on the variables VfV_f. The system of a set of factors is Q=∑fqfQ = \sum_f q_f. A conditional on vv with the parents PvP_v is the factor cv(x)=12∥Rvxv+∑s∈PvSvsxs−dv∥2c_v(x) = \tfrac12 \|R_v x_v + \sum_{s \in P_v} S_{vs} x_s - d_v\|^2 with RvR_v upper triangular and invertible. A Bayes tree encodes QQ if Q=∑vcv+constQ = \sum_v c_v + \text{const} for all xx, the sum over all conditionals in the tree. The tree is valid if:

  • (T1) every variable is frontal in exactly one clique;
  • (T2) the parents of each frontal variable lie in the later frontal variables of its clique and in its separator;
  • (T3) the separator of each clique lies in the variables F∪SF \cup S of its parent, and a root has an empty separator.

Assumptions.

  • (A1) Exact arithmetic.
  • (A2) Every information block Λvv\Lambda_{vv} met during elimination is positive definite. If not, the code raises an error.

Lemma 1 (one elimination step). Let gg be a quadratic in vv and the variables PP, with the information blocks Λ\Lambda and η\eta. Let R⊤R=ΛvvR^\top R = \Lambda_{vv}, Ss=R−⊤ΛvsS_s = R^{-\top}\Lambda_{vs} and d=R−⊤ηvd = R^{-\top}\eta_v. Then g=c+g′g = c + g' up to a constant, where cc is the conditional (R,S,d)(R, S, d) on vv with the parents PP, and g′g' is the quadratic on PP with the blocks Λab−Sa⊤Sb\Lambda_{ab} - S_a^\top S_b and ηa−Sa⊤d\eta_a - S_a^\top d.

Proof. The (v,v)(v, v) block of cc is R⊤R=ΛvvR^\top R = \Lambda_{vv}, its (v,s)(v, s) block is R⊤Ss=ΛvsR^\top S_s = \Lambda_{vs}, its (a,b)(a, b) block on PP is Sa⊤SbS_a^\top S_b, and its linear part is R⊤d=ηvR^\top d = \eta_v in vv and Sa⊤dS_a^\top d in aa. So g−cg - c has no term with vv, and its blocks are those of g′g'. □\square

Claim 1 (elimination). ELIMINATE returns one conditional per variable, the parents of each conditional come later in the order, and the sum of the conditionals is the sum of the input factors up to a constant.

Proof. Lines L2 and L3 take the factors whose first variable in the order is vv and apply Lemma 1 to their sum. The new factor of line L4 is on variables later than vv. Every factor that contains vv has its first variable at or before vv; one with its first variable before vv was already consumed, and its remainder is on later variables, so it is in the pool of vv or later. Hence the sum at line L3 holds all of the remaining factors that involve vv, and after this step no factor involves vv. By induction over the order, the sum of all conditionals plus the remaining factors stays equal to the input sum, and at the end no factor remains (a factor with no variables is a constant). □\square

A fact used below: if a set KK of variables lies in one factor of the input, then when the first variable uu of KK is eliminated, every other variable of KK is a parent of uu. Indeed, the factor that holds KK is either still in the input or has been summed into a remainder, and remainders keep all variables except the eliminated one, so at line L3 for uu the sum contains a factor on KK.

Claim 2 (grouping). GROUP-INTO-CLIQUES on the output of ELIMINATE gives a valid tree.

Proof. The conditionals are visited in the reverse order, so all parents of vv already have cliques. Line L6 makes a root with an empty separator. Otherwise let uu be the first parent of vv in the order and pp its clique. The remainder that vv produced is on PvP_v and enters the elimination of uu, so Pv∖{u}⊆PuP_v \setminus \{u\} \subseteq P_u. The clique pp holds uu and, by induction on (T2) and the merge rule, all of PuP_u, so Pv⊆Fp∪SpP_v \subseteq F_p \cup S_p. At line L8, Pv=Fp∪SpP_v = F_p \cup S_p, and vv becomes the first frontal variable of pp; its parents are the old variables of pp, which keeps (T2). At line L9 the new clique has the separator Pv⊆Fp∪SpP_v \subseteq F_p \cup S_p, which is (T3), and (T2) holds for its single frontal variable. Each variable is placed once, which is (T1). □\square

Claim 3 (back substitution). SOLVE returns the unique minimizer of QQ.

Proof. Lines L10 and L11 visit a clique after its parent, and the frontal variables from the last eliminated to the first. By (T2) and (T3), the parents of a conditional are either later frontal variables of the same clique or separator variables, which are variables of the parent clique, and by induction they were solved earlier. So each xv=Rv−1(dv−∑sSvsxs)x_v = R_v^{-1}(d_v - \sum_s S_{vs} x_s) makes cv=0c_v = 0. All conditionals are zero, which is the minimum of ∑vcv\sum_v c_v, and so of QQ by Claim 1. The matrix of ∑vcv\sum_v c_v is R⊤RR^\top R for the block upper triangular RR with invertible diagonal blocks RvR_v, so it is positive definite, and the minimizer is unique. □\square

Claim 4 (update). If the tree is valid and encodes QQ, then after UPDATE with the new factors F′F' it is valid and encodes Q+∑f∈F′qfQ + \sum_{f \in F'} q_f.

Proof. Line L12 marks the clique of each old variable of F′F' and all its ancestors. This top is closed under taking the parent, so the rest of the tree is a set of whole subtrees, rooted at the orphans of line L13. The conditionals in these subtrees are not touched.

Encoding. Line L14 reads each conditional of the top as a factor, which is the same quadratic. By Claim 1, the new conditionals of line L15 sum to the conditionals of the top plus F′F'. Adding the conditionals of the orphan subtrees gives all old conditionals plus F′F', which is Q+∑F′qfQ + \sum_{F'} q_f.

Variables. Each variable of a factor in line L14 is a frontal variable of a top clique, or a separator variable of one, which by (T3) is a variable of its parent and, going up, frontal in a top clique. Each variable of F′F' is frontal in a top clique or is new. So line L15 eliminates exactly the frontal variables of the top and the new variables, and (T1) holds.

Orphans. Let oo be an orphan with the parent pp in the old tree, a top clique. By (T3), sep(o)⊆Fp∪Sp\mathrm{sep}(o) \subseteq F_p \cup S_p. The first frontal variable of pp has all other variables of pp as parents, by (T2) and the merge rule, so its conditional, read as a factor at line L14, holds all of Fp∪SpF_p \cup S_p. By the fact after Claim 1, the first eliminated variable uu of sep(o)\mathrm{sep}(o) has the rest of sep(o)\mathrm{sep}(o) as parents, so sep(o)⊆{u}∪Pu\mathrm{sep}(o) \subseteq \{u\} \cup P_u, which lies in the new clique of uu by Claim 2. Line L16 attaches oo there, which keeps (T3). Inside the subtree of oo nothing changed. The new cliques satisfy (T2) and (T3) by Claim 2. □\square

What this does not show. The size of the cliques, and so the cost, depends on the elimination order; nothing here bounds the fill-in. An update that touches a variable near the bottom of a deep tree removes the whole path to the root. The proof is for linear factors; for nonlinear factors the conditionals hold a linearization, and iSAM2 handles relinearization.

Complexity

Let nn be the number of variables, KK the number of factors, ww the number of variables of the largest clique, tt the number of variables in the removed top, and oo the number of orphans, with blocks of a fixed size.

  • BUILD: O(K+nw2)O(K + n w^2), because each elimination forms a new factor on at most ww variables.
  • SOLVE: O(nw)O(n w) block products.
  • UPDATE: O(tw2+o)O(t w^2 + o), plus the time to find the top, which is the length of the paths to the root.
  • Space: O(nw)O(n w) blocks for the conditionals.

The value of ww depends on the elimination order and the fill-in. Its smallest value over all orders is the treewidth plus one, and finding that order is NP-hard. Heuristics such as minimum degree and nested dissection are used in practice.

Variants

  • Marginals. The root clique holds a joint density. The marginal of a clique follows from its parent by a recursion down the tree, so a marginal covariance near the root is cheap.
  • Nonlinear factors. iSAM2 keeps a linearization point and relinearizes the variables that moved more than a threshold, by including their cliques in the top.
  • Partial back substitution. Stop the descent where the values of the separator did not change by more than a threshold.
  • Multifrontal solvers. The cliques are the supernodes of the multifrontal method, and the tree is a supernodal form of the elimination tree of RR.

When to use it

Use a Bayes tree when a sparse least squares problem grows over time and the solution is needed after each addition, as in online SLAM, and when the new factors mostly touch recent variables. For a single batch solve, a sparse Cholesky or QR factorization, as in square root SAM, is simpler and has the same cost.

Pitfalls

  • New variables early in the order. If the new variables are not eliminated last, they end up deep in the tree, and the next update removes a long path. Put the variables of the new factors last.
  • Wrong orphan placement. An orphan must go under the clique of the first eliminated variable of its separator. A different place breaks the running intersection property, and SOLVE then reads a separator value that is not computed yet.
  • Missing anchor. A graph without a prior has a singular information matrix, and elimination fails at a block that is not positive definite.
  • Large cliques from loops. A long loop closure joins old and new variables, and the cliques along the loop grow. The size of the tree is then close to that of a dense factor.
  • Confusing it with the junction tree. A junction tree holds undirected potentials and passes messages both ways. A Bayes tree holds directed conditionals from one elimination and is solved by one pass from the root down.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

bayes_tree.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bayes-tree/. The authors are listed in prov/XZ2CJC.jsonl.

"""The Bayes tree of a linear Gaussian factor graph (Kaess et al.).

A linear factor is the cost 1/2 || sum_k A_k x_k - b ||^2 on a few vector
variables x_k. Eliminating the variables in an order turns the factor graph
into a Bayes net: one Gaussian conditional per variable,

    R x_v + sum over the parents s of S_s x_s = d,

with R upper triangular. These are the block rows of the square root
information matrix. The Bayes tree groups the conditionals into cliques:
a clique has frontal variables F (in elimination order) and separator
variables S, and each separator lies in the variables of the parent clique.

Operations:
  eliminate(factors, order)    the conditionals, by variable elimination
  BayesTree.build(factors)     eliminate, then group the conditionals
  tree.solve()                 back substitution from the roots down
  tree.update(new_factors)     add factors: remove the top of the tree above
                               the touched variables, turn its conditionals
                               back into factors, add the new factors,
                               eliminate them again, and put the untouched
                               subtrees (the orphans) back.
"""

import math

# ------------------------------------------------------------ dense helpers


def tr(a):
    return [list(r) for r in zip(*a)]


def mm(a, b):
    bt = tr(b)
    return [[sum(x * y for x, y in zip(r, c)) for c in bt] for r in a]


def mv(a, x):
    return [sum(p * q for p, q in zip(r, x)) for r in a]


def upper_cholesky(a):
    """Upper triangular R with R^T R = a; ValueError if a is not positive definite."""
    n = len(a)
    r = [[0.0] * n for _ in range(n)]
    for i in range(n):
        s = a[i][i] - sum(r[k][i] ** 2 for k in range(i))
        if s <= 1e-12 * max(1.0, abs(a[i][i])):
            raise ValueError("the information block is not positive definite")
        r[i][i] = math.sqrt(s)
        for j in range(i + 1, n):
            r[i][j] = (a[i][j] - sum(r[k][i] * r[k][j] for k in range(i))) / r[i][i]
    return r


def forward(r, b):
    """Solve R^T y = b."""
    y = [0.0] * len(r)
    for i in range(len(r)):
        y[i] = (b[i] - sum(r[k][i] * y[k] for k in range(i))) / r[i][i]
    return y


def backward(r, b):
    """Solve R x = b."""
    n = len(r)
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (b[i] - sum(r[i][k] * x[k] for k in range(i + 1, n))) / r[i][i]
    return x


# ------------------------------------------------------------------ factors


class LinearFactor:
    """1/2 || sum_k A_k x_k - b ||^2, with blocks = {key: A_k}."""

    def __init__(self, blocks, b):
        self.keys = list(blocks)
        self.blocks = {k: [list(row) for row in a] for k, a in blocks.items()}
        self.b = list(b)


class InfoFactor:
    """1/2 x^T Lambda x - eta^T x, with the blocks lam[(u, w)] and eta[u]."""

    def __init__(self, keys, lam, eta):
        self.keys = list(keys)
        self.lam = lam
        self.eta = eta


def to_info(f):
    if isinstance(f, InfoFactor):
        return f
    lam, eta = {}, {}
    for u in f.keys:
        aut = tr(f.blocks[u])
        eta[u] = mv(aut, f.b)
        for w in f.keys:
            lam[(u, w)] = mm(aut, f.blocks[w])
    return InfoFactor(f.keys, lam, eta)


def _accumulate(dst, key, blk):
    if key not in dst:
        dst[key] = [list(r) if isinstance(r, list) else r for r in blk]
        return
    cur = dst[key]
    for i in range(len(cur)):
        if isinstance(cur[i], list):
            for j in range(len(cur[i])):
                cur[i][j] += blk[i][j]
        else:
            cur[i] += blk[i]


def product(factors, pos):
    lam, eta = {}, {}
    keys = set()
    for f in factors:
        f = to_info(f)
        keys |= set(f.keys)
        for kw, blk in f.lam.items():
            _accumulate(lam, kw, blk)
        for k, vec in f.eta.items():
            _accumulate(eta, k, vec)
    return InfoFactor(sorted(keys, key=pos.get), lam, eta)


class Conditional:
    """R x_v + sum over the parents s of S[s] x_s = d."""

    def __init__(self, var, parents, r, s, d):
        self.var = var
        self.parents = list(parents)
        self.r = r
        self.s = s
        self.d = d

    def solve(self, values):
        rhs = list(self.d)
        for p in self.parents:
            rhs = [a - b for a, b in zip(rhs, mv(self.s[p], values[p]))]
        return backward(self.r, rhs)

    def as_factor(self):
        """The conditional read as the factor 1/2 ||R x_v + sum S_s x_s - d||^2."""
        blocks = {self.var: self.r}
        blocks.update(self.s)
        return LinearFactor(blocks, self.d)


def eliminate_variable(joint, v):
    rest = [k for k in joint.keys if k != v]
    r = upper_cholesky(joint.lam[(v, v)])
    s = {}
    for k in rest:
        blk = joint.lam.get((v, k))
        if blk is None:
            blk = [[0.0] * len(joint.eta[k]) for _ in range(len(r))]
        s[k] = tr([forward(r, col) for col in tr(blk)])
    d = forward(r, joint.eta[v])
    lam, eta = {}, {}
    for a in rest:
        sat = tr(s[a])
        eta[a] = [x - y for x, y in zip(joint.eta[a], mv(sat, d))]
        for b in rest:
            corr = mm(sat, s[b])
            base = joint.lam.get((a, b))
            if base is None:
                lam[(a, b)] = [[-x for x in row] for row in corr]
            else:
                lam[(a, b)] = [[x - y for x, y in zip(r1, r2)] for r1, r2 in zip(base, corr)]
    return Conditional(v, rest, r, s, d), InfoFactor(rest, lam, eta)


def eliminate(factors, order):
    """Variable elimination in the given order; return the conditionals in that order."""
    pos = {v: i for i, v in enumerate(order)}
    pool = {v: [] for v in order}
    for f in factors:
        pool[min(f.keys, key=pos.get)].append(f)
    conds = []
    for v in order:  # @line L1
        group = pool.pop(v)  # @line L2
        cond, rest = eliminate_variable(product(group, pos), v)  # @line L3
        conds.append(cond)
        if rest.keys:
            pool[min(rest.keys, key=pos.get)].append(rest)  # @line L4
    return conds


def min_degree_order(variables, factors, last=()):
    """Minimum degree on the variables; the variables in last go after the others."""
    last = set(last)
    nb = {v: set() for v in variables}
    for f in factors:
        for u in f.keys:
            nb[u] |= set(f.keys) - {u}
    order = []
    for group in ([v for v in variables if v not in last], [v for v in variables if v in last]):
        left = set(group)
        while left:
            u = min(left, key=lambda v: (len(nb[v]), repr(v)))
            left.discard(u)
            around = nb.pop(u)
            for a in around:
                nb[a].discard(u)
                nb[a] |= around - {a}
            order.append(u)
    return order


# --------------------------------------------------------------- the tree


class Clique:
    def __init__(self, frontals, sep, parent):
        self.frontals = frontals  # in elimination order
        self.sep = sep
        self.parent = parent
        self.children = []
        self.conds = {}

    def variables(self):
        return set(self.frontals) | set(self.sep)


class BayesTree:
    def __init__(self):
        self.roots = []
        self.clique_of = {}

    @classmethod
    def build(cls, factors, order=None):
        tree = cls()
        variables = sorted({k for f in factors for k in f.keys}, key=repr)
        if order is None:
            order = min_degree_order(variables, factors)
        conds = eliminate(factors, order)
        _, roots, clique_of = group_into_cliques(conds, {v: i for i, v in enumerate(order)})
        tree.roots, tree.clique_of = roots, clique_of
        return tree

    def cliques(self):
        out, stack = [], list(self.roots)
        while stack:
            c = stack.pop()
            out.append(c)
            stack.extend(c.children)
        return out

    def solve(self):
        values = {}
        stack = list(self.roots)
        while stack:  # @line L10
            c = stack.pop()
            for v in reversed(c.frontals):
                values[v] = c.conds[v].solve(values)  # @line L11
            stack.extend(c.children)
        return values

    def update(self, new_factors):
        """Add linear factors; return (removed cliques, new cliques)."""
        new_keys = {k for f in new_factors for k in f.keys}
        top = set()
        for v in new_keys & set(self.clique_of):  # @line L12
            c = self.clique_of[v]
            while c is not None and c not in top:
                top.add(c)
                c = c.parent
        orphans = [ch for c in top for ch in c.children if ch not in top]  # @line L13
        group = [cond.as_factor() for c in top for cond in c.conds.values()]  # @line L14
        group += list(new_factors)
        variables = sorted({v for c in top for v in c.frontals} | (new_keys - set(self.clique_of)), key=repr)
        order = min_degree_order(variables, group, last=new_keys)
        conds = eliminate(group, order)  # @line L15
        pos = {v: i for i, v in enumerate(order)}
        made, roots, clique_of = group_into_cliques(conds, pos)
        for o in orphans:  # @line L16
            p = clique_of[min(o.sep, key=pos.get)]
            o.parent = p
            p.children.append(o)
        self.roots = [r for r in self.roots if r not in top] + roots
        self.clique_of.update(clique_of)
        return len(top), len(made)


def group_into_cliques(conds, pos):
    """Return (cliques, roots, map from a variable to its clique)."""
    clique_of, made, roots = {}, [], []
    for cond in reversed(conds):  # @line L5
        v = cond.var
        if not cond.parents:
            c = Clique([v], [], None)  # @line L6
            made.append(c)
            roots.append(c)
        else:
            p = clique_of[min(cond.parents, key=pos.get)]  # @line L7
            if p.variables() == set(cond.parents):
                p.frontals.insert(0, v)  # @line L8
                c = p
            else:
                c = Clique([v], list(cond.parents), p)  # @line L9
                p.children.append(c)
                made.append(c)
        c.conds[v] = cond
        clique_of[v] = c
    return made, roots, clique_of
test_bayes_tree.py 193 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bayes-tree/. The authors are listed in prov/XZ2CJC.jsonl.

import random

import pytest

from bayes_tree import BayesTree, LinearFactor, eliminate


def scalar(blocks, b):
    return LinearFactor({k: [[a]] for k, a in blocks.items()}, [b])


def kaess_example():
    """Poses x1, x2, x3 and landmarks l1, l2 on a line, unit noise."""
    return [
        scalar({"x1": 1.0}, 0.0),
        scalar({"x1": -1.0, "x2": 1.0}, 1.0),
        scalar({"x2": -1.0, "x3": 1.0}, 1.0),
        scalar({"x1": -1.0, "l1": 1.0}, 2.1),
        scalar({"x2": -1.0, "l1": 1.0}, 0.9),
        scalar({"x3": -1.0, "l2": 1.0}, 1.0),
    ]


def random_graph(rng, n, extra):
    """A connected random graph of variables of size 1 or 2 with an anchor on variable 0."""
    dims = {v: rng.choice([1, 2]) for v in range(n)}

    def block(v, rows):
        return [[rng.uniform(-1.0, 1.0) for _ in range(dims[v])] for _ in range(rows)]

    def factor(keys):
        rows = max(dims[k] for k in keys) + rng.choice([0, 1])
        return LinearFactor({k: block(k, rows) for k in keys}, [rng.uniform(-2.0, 2.0) for _ in range(rows)])

    fs = [LinearFactor({0: [[2.0 if i == j else 0.0 for j in range(dims[0])] for i in range(dims[0])]}, [0.5] * dims[0])]
    for v in range(1, n):
        fs.append(factor([rng.randrange(v), v]))
    for _ in range(extra):
        a, b = rng.sample(range(n), 2)
        fs.append(factor([a, b]))
    return fs, dims


def dense(factors, keys, dims):
    pos, n = {}, 0
    for k in keys:
        pos[k] = n
        n += dims[k]
    lam = [[0.0] * n for _ in range(n)]
    eta = [0.0] * n
    for f in factors:
        for u in f.keys:
            for w in f.keys:
                for i in range(dims[u]):
                    for j in range(dims[w]):
                        lam[pos[u] + i][pos[w] + j] += sum(f.blocks[u][r][i] * f.blocks[w][r][j] for r in range(len(f.b)))
            for i in range(dims[u]):
                eta[pos[u] + i] += sum(f.blocks[u][r][i] * f.b[r] for r in range(len(f.b)))
    return lam, eta, pos


def gauss(a, b):
    n = len(a)
    m = [list(a[r]) + [b[r]] for r in range(n)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        m[c], m[p] = m[p], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for k in range(c, n + 1):
                m[r][k] -= f * m[c][k]
    x = [0.0] * n
    for r in range(n - 1, -1, -1):
        x[r] = (m[r][n] - sum(m[r][k] * x[k] for k in range(r + 1, n))) / m[r][r]
    return x


def check_against_dense(tree, factors, dims, tol=1e-8):
    keys = sorted(dims, key=repr)
    lam, eta, pos = dense(factors, keys, dims)
    ref = gauss(lam, eta)
    got = tree.solve()
    for k in keys:
        for i in range(dims[k]):
            assert abs(got[k][i] - ref[pos[k] + i]) < tol
    # the conditionals, read as factors, give the same Lambda and eta (R^T R = Lambda)
    conds = [cond.as_factor() for c in tree.cliques() for cond in c.conds.values()]
    tl, te, _ = dense(conds, keys, dims)
    assert max(abs(x - y) for r1, r2 in zip(lam, tl) for x, y in zip(r1, r2)) < tol
    assert max(abs(x - y) for x, y in zip(eta, te)) < tol


def check_invariants(tree, variables):
    seen = {}
    for c in tree.cliques():
        for v in c.frontals:
            seen[v] = seen.get(v, 0) + 1
            assert tree.clique_of[v] is c
        if c.parent is None:
            assert c.sep == [] and c in tree.roots
        else:
            assert c in c.parent.children
            assert set(c.sep) <= c.parent.variables()
        for i, v in enumerate(c.frontals):
            assert set(c.conds[v].parents) <= set(c.frontals[i + 1:]) | set(c.sep)
    assert seen == {v: 1 for v in variables}


def test_kaess_example_has_the_expected_cliques():
    tree = BayesTree.build(kaess_example(), order=["l1", "l2", "x1", "x2", "x3"])
    (root,) = tree.roots
    assert root.frontals == ["x2", "x3"] and root.sep == []
    kids = sorted((c.frontals, c.sep) for c in root.children)
    assert kids == [(["l1", "x1"], ["x2"]), (["l2"], ["x3"])]
    sol = tree.solve()
    # odometry says x2 - x1 = 1, the landmark says 1.2: three unit residuals share 0.2
    want = {"x1": 0.0, "x2": 1.0 + 0.2 / 3, "x3": 2.0 + 0.2 / 3, "l1": 2.1 - 0.2 / 3, "l2": 3.0 + 0.2 / 3}
    assert all(abs(sol[k][0] - want[k]) < 1e-12 for k in want)


def test_tree_solve_and_square_root_information_match_the_dense_system():
    rng = random.Random(11)
    for _ in range(25):
        n = rng.randint(2, 12)
        fs, dims = random_graph(rng, n, rng.randint(0, 2 * n))
        tree = BayesTree.build(fs)
        check_invariants(tree, dims)
        check_against_dense(tree, fs, dims)


def test_any_order_gives_the_same_solution():
    rng = random.Random(12)
    fs, dims = random_graph(rng, 9, 10)
    ref = BayesTree.build(fs).solve()
    for _ in range(5):
        order = list(dims)
        rng.shuffle(order)
        tree = BayesTree.build(fs, order)
        check_invariants(tree, dims)
        sol = tree.solve()
        assert max(abs(a - b) for k in dims for a, b in zip(sol[k], ref[k])) < 1e-8


def test_updates_keep_the_tree_equal_to_the_full_system():
    rng = random.Random(13)
    fs, dims = random_graph(rng, 30, 20)
    tree = BayesTree.build(fs[:5])
    have = list(fs[:5])
    for i in range(5, len(fs), 3):
        batch = fs[i:i + 3]
        tree.update(batch)
        have += batch
        part = {k for f in have for k in f.keys}
        check_invariants(tree, part)
        check_against_dense(tree, have, {k: dims[k] for k in part})


def test_adding_odometry_at_the_newest_pose_touches_only_the_root():
    fs = kaess_example()
    tree = BayesTree.build(fs, order=["l1", "l2", "x1", "x2", "x3"])
    (old_root,) = tree.roots
    kids = list(old_root.children)
    new = scalar({"x3": -1.0, "x4": 1.0}, 1.0)
    removed, made = tree.update([new])
    assert (removed, made) == (1, 2)
    (root,) = tree.roots
    assert root.frontals == ["x3", "x4"]
    # the two old children are the same objects, moved under the new cliques
    assert all(k in tree.cliques() for k in kids)
    assert tree.clique_of["x1"].parent is tree.clique_of["x2"]
    assert tree.clique_of["l2"].parent is root
    dims = {v: 1 for v in ["x1", "x2", "x3", "x4", "l1", "l2"]}
    check_invariants(tree, dims)
    check_against_dense(tree, fs + [new], dims)


def test_chain_updates_eliminate_a_bounded_number_of_cliques():
    fs = [scalar({0: 1.0}, 0.0)]
    tree = BayesTree.build(fs)
    for t in range(1, 40):
        removed, made = tree.update([scalar({t - 1: -1.0, t: 1.0}, 1.0)])
        assert removed == 1 and made <= 2
    sol = tree.solve()
    assert all(abs(sol[t][0] - t) < 1e-9 for t in range(40))


def test_missing_anchor_is_rank_deficient():
    fs = [scalar({"a": -1.0, "b": 1.0}, 1.0)]
    with pytest.raises(ValueError):
        eliminate(fs, ["a", "b"])

History

The junction tree of probabilistic inference and the elimination tree of sparse matrix factorization both come from variable elimination on a chordal graph. Kaess, Ila, Roberts and Dellaert (WAFR 2010, published 2011) defined the Bayes tree as the directed version for the square root information matrix of SLAM, and gave the update that removes the top and reinserts the orphans. Kaess et al. (2012) built iSAM2 on it, which replaced the matrix updates of iSAM by tree edits. The GTSAM library uses Bayes trees for its incremental solvers.

References

  1. Michael Kaess, Viorela Ila, Richard Roberts and Frank Dellaert, The Bayes tree: an algorithmic foundation for probabilistic robot mapping, Algorithmic Foundations of Robotics IX (WAFR 2010), Springer Tracts in Advanced Robotics 68, 2011, pages 157 to 173, the definition of the Bayes tree from a chordal Bayes net, the clique creation rule, and the update with new factors that removes the top of the tree and reinserts the orphans
  2. Michael Kaess, Hordur Johannsson, Richard Roberts, Viorela Ila, John J. Leonard and Frank Dellaert, iSAM2: incremental smoothing and mapping using the Bayes tree, International Journal of Robotics Research 31(2), 2012, pages 216 to 235, the Bayes tree section: the algorithm that builds the tree from the eliminated factor graph, and the linear update of the tree with new factors
  3. Frank Dellaert and Michael Kaess, Factor graphs for robot perception, Foundations and Trends in Robotics 6(1-2), 2017, the chapters on variable elimination, the Bayes net and the Bayes tree, and incremental smoothing

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.build
  • a full proof of time.solve
  • a full proof of time.update
  • a full proof of space.total
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/XZ2CJC/text.yaml