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
- Model
- Real RAM
- Evidence
- Proof sketchCode in 1 languages
- 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, , given its parents . These conditionals are the block rows of the square root information matrix , so they form a Bayesian network that is chordal. The Bayes tree groups the conditionals into cliques. Each clique holds frontal variables and separator variables , and the conditionals of given , 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 , a set of separator variables , a parent clique (none for a root) and child cliques;
- for each frontal variable , a Gaussian conditional whose parents lie in the later frontal variables of its clique and in ;
- 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 of its parent (the running intersection property). The tree encodes the quadratic , 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 holds the upper triangular , a block for each parent, and the vector . The tree keeps a list of roots and a hash map from each variable to its clique. The code stores factors as with dense blocks, and works inside one elimination step in information form.
Operations
ELIMINATE(factors, order)- 1
for each variable v in order do - 2
G ← the remaining factors whose first variable in order is v - 3
(conditional of v given P_v, factor on P_v) ← eliminate v from the sum of G - 4
put the factor on P_v with the factors of its first variable GROUP-INTO-CLIQUES(conditionals)- 5
for each conditional of v given P_v, in the reverse of the order do - 6
if P_v is empty then make a new root clique with F = [v] - 7
else p ← the clique of the first variable of P_v in the order - 8
if P_v = F_p ∪ S_p then put v at the front of F_p - 9
else make a new child clique of p with F = [v] and S = P_v SOLVE(tree)- 10
for each clique, parents before children do - 11
for each v in F, from the last to the first do x_v ← R_v⁻¹ (d_v - Σ_s S_vs x_s) UPDATE(tree, new factors F')- 12
top ← the cliques where a variable of F' is frontal, and all their ancestors - 13
orphans ← the children of top cliques that are not in the top - 14
G ← the conditionals of the top, read as factors, and the factors F' - 15
ELIMINATE G in a new order (the variables of F' last) and GROUP-INTO-CLIQUES - 16
for 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 from the Cholesky decomposition, and , and the factor on is , . QR on the stacked Jacobian rows gives the same conditionals up to the signs of the rows of .
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 and its parents. The first conditional of a clique involves all of , so the separator of every orphan lies in one factor of , 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 and two landmarks lie on a line. All factors have unit noise:
| factor | equation |
|---|---|
| prior | |
| odometry | , |
| landmark | , |
| landmark |
Eliminate in the order . The conditionals, rounded to four digits, are:
| variable | |||
|---|---|---|---|
| 1.4142 | : -0.7071, : -0.7071 | 2.1213 | |
| 1 | : -1 | 1 | |
| 1.5811 | : -0.9487 | -1.0119 | |
| 1.2649 | : -0.7906 | -0.2846 | |
| 0.6124 | 1.2656 |
Grouping from back: starts the root. The parents of are , all of the root, so merges into it. The parents of are , not all of , so starts a child clique with the separator . The parents of are , again not all of the root, so starts a second child. The parents of are , all of the clique of , so merges there. The tree is the root with the children and .
SOLVE gives at the root, then , then and in the first child, and in the second. Odometry says that , and the landmark says . The three unit residuals of this loop share the gap of equally.
Now add a pose with the odometry . The variable 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 . The conditional of comes out the same as before. The new ones are and . The new root is with the child . The orphan goes under the clique of , and the orphan under the root. One clique was removed, two were made, and two were kept without any computation. SOLVE gives 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 and , 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 on the variables . The system of a set of factors is . A conditional on with the parents is the factor with upper triangular and invertible. A Bayes tree encodes if for all , 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 of its parent, and a root has an empty separator.
Assumptions.
- (A1) Exact arithmetic.
- (A2) Every information block met during elimination is positive definite. If not, the code raises an error.
Lemma 1 (one elimination step). Let be a quadratic in and the variables , with the information blocks and . Let , and . Then up to a constant, where is the conditional on with the parents , and is the quadratic on with the blocks and .
Proof. The block of is , its block is , its block on is , and its linear part is in and in . So has no term with , and its blocks are those of .
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 and apply Lemma 1 to their sum. The new factor of line L4 is on variables later than . Every factor that contains has its first variable at or before ; one with its first variable before was already consumed, and its remainder is on later variables, so it is in the pool of or later. Hence the sum at line L3 holds all of the remaining factors that involve , and after this step no factor involves . 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).
A fact used below: if a set of variables lies in one factor of the input, then when the first variable of is eliminated, every other variable of is a parent of . Indeed, the factor that holds 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 the sum contains a factor on .
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 already have cliques. Line L6 makes a root with an empty separator. Otherwise let be the first parent of in the order and its clique. The remainder that produced is on and enters the elimination of , so . The clique holds and, by induction on (T2) and the merge rule, all of , so . At line L8, , and becomes the first frontal variable of ; its parents are the old variables of , which keeps (T2). At line L9 the new clique has the separator , which is (T3), and (T2) holds for its single frontal variable. Each variable is placed once, which is (T1).
Claim 3 (back substitution). SOLVE returns the unique minimizer of .
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 makes . All conditionals are zero, which is the minimum of , and so of by Claim 1. The matrix of is for the block upper triangular with invertible diagonal blocks , so it is positive definite, and the minimizer is unique.
Claim 4 (update). If the tree is valid and encodes , then after UPDATE with the new factors it is valid and encodes .
Proof. Line L12 marks the clique of each old variable of 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 . Adding the conditionals of the orphan subtrees gives all old conditionals plus , which is .
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 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 be an orphan with the parent in the old tree, a top clique. By (T3), . The first frontal variable of has all other variables of as parents, by (T2) and the merge rule, so its conditional, read as a factor at line L14, holds all of . By the fact after Claim 1, the first eliminated variable of has the rest of as parents, so , which lies in the new clique of by Claim 2. Line L16 attaches there, which keeps (T3). Inside the subtree of nothing changed. The new cliques satisfy (T2) and (T3) by Claim 2.
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 be the number of variables, the number of factors, the number of variables of the largest clique, the number of variables in the removed top, and the number of orphans, with blocks of a fixed size.
- BUILD: , because each elimination forms a new factor on at most variables.
- SOLVE: block products.
- UPDATE: , plus the time to find the top, which is the length of the paths to the root.
- Space: blocks for the conditionals.
The value of 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 .
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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag XZ2CJC Edit this page History Report an error Markdown