Algorithm Search⌘K

Algorithmresearch

iSAM2

Also called incremental smoothing and mapping with the Bayes tree.

Incremental SLAM on a Bayes tree. Each update re-eliminates only the top of the tree above the new factors and the relinearized variables, with fluid relinearization by a threshold.

Solves
Full SLAM
Time
O(v s^2) back_substitutionO(w s^2) eliminate_topO((p + m)^3) worst_update
Space
O((p + m) s) tree
Where
m = the number of landmarks; p = the number of poses; s = the number of variables in the largest clique; v = the number of cliques that the back substitution visits; w = the number of variables in the removed top
Properties
cost depends on orderingdeterministicnot exactincremental
Origin
Michael Kaess, Hordur Johannsson, Richard Roberts, Viorela Ila, John J. Leonard, Frank Dellaert, 2012

iSAM2 keeps the solution of a SLAM problem current as new measurements arrive, without a full refactorization and without the periodic batch steps of iSAM. It stores the square root information matrix as a Bayes tree: a tree of cliques, each with Gaussian conditionals of its frontal variables given its separator. A new factor changes only the cliques that contain its variables and their ancestors up to the root. iSAM2 removes this top of the tree, turns it back into factors, adds the new factors, eliminates them again in a fresh local order, and puts the untouched subtrees back. Fluid relinearization moves the linearization point of a variable only when its step exceeds a threshold β\beta, and partial back substitution stops at cliques whose inputs changed by less than α\alpha. Both thresholds make it an approximation of batch Gauss-Newton; with no relinearization and α=0\alpha = 0, the linear solution is exact. The cost of an update depends on the variable ordering and the fill-in.

In plain words

The robot keeps its map as a family tree of small groups of unknowns. Each group knows how its members depend on the group above it. When a new measurement arrives, only the groups that hold the measured unknowns, and the chain of groups above them, can change. iSAM2 takes off that part of the tree, redoes it with the new measurement, and hangs the rest back where it fits. It also redoes the straight-line view of a measurement only when an unknown has moved a lot since the last time. When it computes the answer, it walks down from the top and stops where nothing above has changed.

The problem

The input is a stream of updates. Each update brings new nonlinear factors ff with Gaussian noise and initial values for new variables. After each update, the output is an estimate of all variables that minimizes, approximately, the nonlinear least squares cost ∑f∥hf(X)−zf∥Σf2\sum_f \|h_f(X) - z_f\|^2_{\Sigma_f} of all factors so far.

iSAM2 keeps the linearization point θ\theta, the current step Δ\Delta, the estimate θ⊕Δ\theta \oplus \Delta, and the Bayes tree of the linear system at θ\theta. A clique has frontal variables FF and separator variables SS, the conditionals Rvδv+∑sSvsδs=dvR_v \delta_v + \sum_s S_{vs} \delta_s = d_v of its frontal variables, and the cached factor on SS that its elimination passed to its parent. The code works on planar pose graphs with a prior and between factors. ⊕\oplus adds the step to (x,y,θ)(x, y, \theta) and wraps the angle.

The algorithm

  1. UPDATE(new factors F', new values Θ')
  2. 1J ← {j : |Δ_j| ≥ β} ▷ fluid relinearization
  3. 2θ_J ← θ_J ⊕ Δ_J; Δ_J ← 0
  4. 3for each clique C with a variable of J in F_C ∪ S_C, or a variable of F' in F_C do
  5. 4mark C and all its ancestors ▷ the top
  6. 5orphans ← the unmarked children of the marked cliques
  7. 6G ← the factors whose variables all lie in the top, linearized at θ (again only if new or touching J)
  8. 7add the cached factors of the orphans to G
  9. 8π ← a minimum degree order of the top variables, with the variables of F' last
  10. 9eliminate G in the order π into conditionals
  11. 10build cliques from the conditionals and replace the top by them
  12. 11for each orphan o do attach o under the clique of the first variable of S_o in π
  13. 12BACK-SUBSTITUTE from the roots:
  14. 13skip a clique (and its subtree) if it is not new and no variable of S changed by more than α
  15. 14solve its frontal variables from the last eliminated to the first: δ_v ← R_v⁻¹ (d_v - Σ_s S_vs δ_s)
  16. 15record the variables that changed by more than α

Building cliques (line L10). Go through the conditionals in the reverse of the elimination order. A conditional with no parents starts a root clique. Otherwise, let pp be the clique of the first eliminated parent. If the parents are exactly all the variables Fp∪SpF_p \cup S_p of pp, add the variable to pp as a frontal variable. If not, start a new child clique of pp with the parents as its separator. This is the rule of Kaess et al.

Elimination (line L9). The code keeps each linear factor in information form, 12δ⊤Λδ−η⊤δ\tfrac12 \delta^\top \Lambda \delta - \eta^\top \delta. To eliminate vv, it adds the factors on vv, takes the Cholesky factor RR of Λvv\Lambda_{vv}, and forms Ss=R−⊤ΛvsS_s = R^{-\top}\Lambda_{vs} and d=R−⊤ηvd = R^{-\top}\eta_v. The new factor on the other variables is Λab−Sa⊤Sb\Lambda_{ab} - S_a^\top S_b and ηa−Sa⊤d\eta_a - S_a^\top d. Kaess et al. use QR on the Jacobian rows instead; the conditionals are the same up to the signs of the rows of RR.

Why only the top. A new factor on variables VV becomes a part of the clique of the first eliminated variable of VV, and its effect flows only up to the root. A relinearized variable changes every factor that contains it, and those factors live in cliques that hold the variable as frontal or separator. Everything below the top is unchanged and is summed up by the cached factors of the orphans.

Ordering (line L8). The code uses minimum degree on the top only, with the new variables last; Kaess et al. use constrained COLAMD. Putting the newest variables last keeps them near the root, so the next update, which will likely touch them again, removes a small top.

Example

The robot drives two laps of a 12-sided polygon with sides of 1 m, so there are 25 poses. Each step adds a between factor for the odometry (noise 0.05 m, 0.05 m and 0.02 rad). In the second lap, each pose tt also gets a loop closure to the pose t−12t - 12 at the same place, with the same noise. The seed is 4. Dead reckoning drifts to a largest position error of 0.577 m.

With β=0.1\beta = 0.1 and α=0\alpha = 0:

step relinearized variables cliques eliminated cliques in the tree
1 to 11 0 1 or 2 1 to 11
12 (first loop closure) 0 11 11
13 6 12 12
14 to 24 1 or 2 9 to 16 12 to 22

Over the 25 updates, 183 cliques were eliminated out of 277 cliques present after the updates, and 18 variables were relinearized. The final estimate is within 0.0026 of the batch Gauss-Newton optimum, and its cost is 36.858 against 36.844 for the batch optimum. The largest position error against the truth is 0.153 m. The final tree has 22 cliques of at most 4 variables, with the root clique {x12,x23,x24}\{x_{12}, x_{23}, x_{24}\}.

Without relinearization (β=∞\beta = \infty), the estimate stays at the linearization of dead reckoning and is 0.017 from the batch optimum, with the cost 37.366. With α=10−3\alpha = 10^{-3}, the back substitution solved 229 cliques instead of 267, and the result was the same to the digits above.

These numbers are measurements on a graph with a loop closure at every step of the second lap. There, each loop closure reaches far back, and an update re-eliminates most of the tree. iSAM2 gains much more on large graphs where most updates are local.

Correctness

The correctness proof shows by induction over the updates that the conditionals of the tree always sum to the full linear system of all factors at the current linearization point. The key step is that a factor whose clique stays below the top contains no relinearized variable, so its old linear form is still valid, and the cached factor of each orphan sums up its whole subtree. It also shows that the tree stays valid (each variable is frontal once, and each separator lies in the parent clique), and that with α=0\alpha = 0 the back substitution gives the exact solution of the linear system. The tests check the tree against a dense solve to 10−910^{-9} after the updates without relinearization, check the tree invariants and the full information matrix after every update with relinearization, and check that repeated updates with a tiny β\beta reach the batch optimum to 10−810^{-8}.

Fluid relinearization and partial back substitution are approximations controlled by thresholds. The estimate with 0<β0 < \beta is not a stationary point of the nonlinear cost in general.

Proof: After each iSAM2 update, the Bayes tree encodes the full linearized system, and the back substitution with alpha = 0 solves it exactlyfull

Setting. The nonlinear factors are f1,…,fKf_1, \dots, f_K, each on a set VfV_f of variables. The linearization point is θ\theta. The linear factor of ff at θ\theta is the quadratic qf(δ)=12δ⊤Λfδ−ηf⊤δq_f(\delta) = \tfrac12 \delta^\top \Lambda_f \delta - \eta_f^\top \delta (up to a constant), in the variables VfV_f. The full linear system at θ\theta is Q(δ)=∑fqf(δ)Q(\delta) = \sum_f q_f(\delta). A conditional on vv with the parents PP is c(δ)=12∥Rδv+∑s∈PSsδs−d∥2c(\delta) = \tfrac12 \|R\delta_v + \sum_{s \in P} S_s \delta_s - d\|^2 with RR upper triangular and invertible. The tree encodes QQ if Q(δ)=∑all conditionalsc(δ)+constQ(\delta) = \sum_{\text{all conditionals}} c(\delta) + \text{const} for all δ\delta.

The home of a factor in a tree is the clique in which the first eliminated variable of the factor is frontal. For a clique CC, let T(C)T(C) be the subtree below and including CC, and let F(C)\mathcal{F}(C) be the factors whose home is in T(C)T(C).

Assumptions.

  • (A1) Exact arithmetic.
  • (A2) Every information block Λvv\Lambda_{vv} met during elimination is positive definite. (A prior on the first pose and a connected graph give this.)

Lemma 1 (one elimination step). Let gg be a quadratic in vv and the variables PP, with the blocks Λ\Lambda and η\eta. With R⊤R=ΛvvR^\top R = \Lambda_{vv}, Ss=R−⊤ΛvsS_s = R^{-\top}\Lambda_{vs} and d=R−⊤ηvd = R^{-\top}\eta_v, we have g=c+g′g = c + g' up to a constant, where cc is the conditional (R,S,d)(R, S, d) 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. Expand c=12∥Rδv+∑sSsδs−d∥2c = \tfrac12 \|R\delta_v + \sum_s S_s \delta_s - d\|^2. Its (v,v)(v, v) block 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. Subtracting cc from gg removes every term with vv and leaves g′g'. □\square

By induction over the variables, ELIMINATE turns a set of quadratics into one conditional per variable, and the sum of the conditionals equals the sum of the input quadratics up to a constant.

Lemma 2 (subtrees). In a tree built by ELIMINATE and BUILD-CLIQUES, for every clique CC, ∑f∈F(C)qf=∑conditionals in T(C)c+cached(C)\sum_{f \in \mathcal{F}(C)} q_f = \sum_{\text{conditionals in } T(C)} c + \mathit{cached}(C) up to a constant, where cached(C)\mathit{cached}(C) is the factor on the separator of CC produced by the elimination of its last frontal variable.

Proof. Elimination puts each factor in the bucket of its first variable in the order, and the factor produced by vv lives on the parents PvP_v. Let vv be frontal in a clique DD. The frontal variables of DD are eliminated before its separator variables, which are frontal in ancestors. BUILD-CLIQUES merges vv into DD only if PvP_v is all of the other variables of DD at that moment, so if vv is not the last frontal variable of DD, the first variable of PvP_v is the next frontal variable of DD. If vv is the last one, Pv=sep(D)P_v = \mathrm{sep}(D), and its first variable is frontal in the parent of DD. Hence every factor produced in T(C)T(C) lands in a bucket of T(C)T(C), except the one produced by the last frontal variable of CC, which is cached(C)\mathit{cached}(C). Conversely, no factor from outside T(C)T(C) lands in a bucket of T(C)T(C): an input factor with its home outside T(C)T(C) has its first variable outside T(C)T(C), and a factor produced in a clique EE outside T(C)T(C) lands in EE or in the parent of EE, which is outside T(C)T(C) as well. So the inputs of the eliminations in T(C)T(C) are F(C)\mathcal{F}(C) and the factors produced in T(C)T(C) other than cached(C)\mathit{cached}(C). Summing Lemma 1 over these eliminations, the produced factors appear on both sides and cancel, which leaves the claim. □\square

Claim 1 (the update keeps the encoding). If before an update the tree encodes QQ at θ\theta, then after the update the tree encodes Q′Q', the full system of the old and new factors at the new linearization point θ′\theta'.

Proof. Let JJ be the relinearized variables, so θ′\theta' differs from θ\theta only on JJ. Line L3 marks every clique that has a variable of JJ in its frontal or separator variables, every clique with a frontal variable of a new factor, and all their ancestors. The top is the set of marked cliques. It is closed under taking the parent, so the rest of the tree is a set of whole subtrees, rooted at the orphans.

Take a factor ff whose home HH is in an orphan subtree T(o)T(o). All of VfV_f lies in the frontal and separator variables of HH. If VfV_f met JJ, HH would be marked, so Vf∩J=∅V_f \cap J = \emptyset, and qfq_f at θ′\theta' equals qfq_f at θ\theta. By Lemma 2, the conditionals of T(o)T(o) plus cached(o)\mathit{cached}(o) still represent these factors at θ′\theta'.

Take a factor ff whose home is in the top, or a new factor. Each variable of VfV_f is a frontal variable of the home or of an ancestor of it, so all of VfV_f lies in the top variables; for a new factor, its variables are frontal in marked cliques or are new. Conversely a factor with all variables in the top has its home in the top. So line L6 selects exactly these factors, and it relinearizes those that touch JJ or are new; the others keep their linear factor, which is the same at θ′\theta'.

Line L9 eliminates the selected factors and the cached factors of the orphans. By Lemma 1, the new conditionals sum to these quadratics. Together with the conditionals of the orphan subtrees, and by Lemma 2 for each orphan, the sum of all conditionals is ∑fqf\sum_f q_f at θ′\theta' over all factors, which is Q′Q'. □\square

Claim 2 (the tree is valid). After an update, every variable is frontal in exactly one clique, and the separator of every clique lies in the frontal and separator variables of its parent.

Proof. The variables of the top are eliminated once each at line L9 and placed in one new clique each by BUILD-CLIQUES; the orphan subtrees keep their frontal variables, which are disjoint from the top. Inside the new part, a new clique for vv is a child of the clique pp of the first eliminated variable uu of its parents PvP_v. Variable elimination makes the variables of Pv∖{u}P_v \setminus \{u\} parents of uu (they are all in the factor that vv passed up, which lands in the bucket of uu), so Pv⊆{u}∪Pu⊆P_v \subseteq \{u\} \cup P_u \subseteq the frontal and separator variables of pp. A merged variable joins pp only if PvP_v equals all of the variables of pp, which keeps the property for pp. For an orphan oo, cached(o)\mathit{cached}(o) is a factor on sep(o)\mathrm{sep}(o) in the input of line L9, so the first eliminated variable uu of sep(o)\mathrm{sep}(o) receives it, and sep(o)⊆{u}∪Pu\mathrm{sep}(o) \subseteq \{u\} \cup P_u, which lies in the clique of uu, the new parent from line L11. □\square

Claim 3 (the solution). With α=0\alpha = 0, after line L12 the vector δ\delta satisfies every conditional with zero residual, so it is the unique minimizer of Q′Q'.

Proof. The back substitution visits cliques from the roots down, and inside a clique it solves the frontal variables from the last eliminated to the first, so the parents of each conditional are solved before it. A visited conditional gets zero residual by line L14. A clique that is skipped at line L13 is not new, so its conditionals did not change, and none of its separator variables changed, so its frontal variables, which were solved for the same conditionals and the same parent values, still have zero residual. Its descendants are not visited. They are not new, because the top is closed under the parent. A separator variable uu of a descendant lies in the variables of its parent, by Claim 2, and so, going up, either uu is frontal in the skipped part, where nothing changed, or uu is in the separator of the skipped clique, where nothing changed. So the inputs of every descendant are unchanged, and its old values still give zero residuals. With all conditionals at zero, the sum of the conditionals is at its minimum, and by Claim 1 this sum is Q′Q' up to a constant. Q′Q' is strictly convex because each RR is invertible, so the minimizer is unique. □\square

Corollary (no relinearization). With β=∞\beta = \infty, θ\theta never changes after a variable is added, and by Claims 1 and 3, δ\delta after each update equals the solution of the full linear system at the initial values. The test checks this against a dense solve to 10−910^{-9}.

What this does not show. With 0<β<∞0 < \beta < \infty, a variable whose step stays below β\beta keeps an old linearization point, so the estimate θ+δ\theta + \delta is the minimizer of a mix of linearizations, not a stationary point of the nonlinear cost. This is an approximation, and its error depends on β\beta and on the problem. With α>0\alpha > 0, a clique whose inputs changed by at most α\alpha is not updated, so δ\delta only approximately solves the system. Nothing here bounds the number of cliques that an update touches.

Complexity

Let ww be the number of variables in the removed top, ss the number of variables of the largest clique, and vv the number of cliques that the back substitution visits, with blocks of a fixed size.

  • Removing the top and finding the orphans: proportional to the size of the top.
  • Elimination of the top: O(ws2)O(w s^2) block operations.
  • Back substitution: O(vs2)O(v s^2).
  • Memory: O((p+m)s)O((p + m) s) for the conditionals.

The size of the top and of the cliques depends on the variable ordering and the fill-in; see elimination ordering. An update that touches the oldest pose of a long loop can remove the whole tree, which costs as much as a batch step, O((p+m)3)O((p + m)^3) in the worst case. Kaess et al. report on data sets that most updates touch a small top. That is a measurement, not a bound. The code also scans all factors at line L6 to find those in the top; an index from variables to factors removes this scan.

Properties

  • Incremental and exact for linear problems. With no relinearization, every update gives the same linear solution as a batch solve.
  • No periodic batch steps. Unlike iSAM, it reorders only the top, so the fill-in does not build up over time in the same way.
  • Approximate for nonlinear problems. The thresholds β\beta and α\alpha trade accuracy for time.
  • Local edits. A new measurement between two recent poses touches only cliques near the root.

Variants and improvements

  • Trust region steps. A step such as Powell's dogleg can replace the Gauss-Newton step, so that a poor initial value does not make the update diverge.
  • Per-variable thresholds. Use a different β\beta for rotations and translations, or for landmarks and poses.
  • Marginal covariances. The Bayes tree gives the marginal covariance of a variable by a recursion from the root, which is useful for data association.
  • Fixed-lag smoothing. Marginalize the oldest variables out of the tree to bound the memory.

When to use it

Use iSAM2 for online SLAM and visual-inertial odometry, where the estimate must be current after every new measurement and the problem grows over time. For a one-time batch problem, square root SAM or a sparse solver is simpler. When the problem is a pose graph and a certificate of global optimality matters, use SE-Sync offline.

Pitfalls

  • A threshold β\beta that is too large. Variables keep a stale linearization, and the estimate stays biased. The example shows this with β=∞\beta = \infty.
  • Mixed units. One threshold on meters and radians treats them alike. Set the thresholds per variable type.
  • Wrong orphan placement. An orphan must go under the clique of the first eliminated variable of its separator. Any other place breaks the running intersection property, and the back substitution then uses values that are not solved yet.
  • New variables first. If the order puts a new pose early, the next update removes most of the tree.
  • Missing priors. Like every Gaussian elimination, the tree needs a positive definite block for each variable, so the graph needs a prior or an anchor.

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.

isam2.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/isam2/. The authors are listed in prov/32NTDV.jsonl.

"""iSAM2 (Kaess et al. 2012) on a planar pose graph.

The variables are poses (x, y, theta). The nonlinear factors are a prior on
one pose and "between" factors that measure the pose j in the frame of i.
The noise is Gaussian with diagonal standard deviations. A pose is updated
by adding a step to (x, y, theta) and wrapping the angle.

iSAM2 keeps:
  theta   the linearization point of each variable,
  delta   the current solution of the linear system at theta,
  a Bayes tree of cliques. Each clique has frontal variables, separator
          variables, one Gaussian conditional per frontal variable, and the
          cached factor on its separator that its elimination passed up.
The estimate is theta + delta.

UPDATE(new factors, new variables) does:
  1. fluid relinearization: the variables J with |delta_j| >= beta move
     their linearization point to theta_j + delta_j;
  2. it removes the top of the tree: the cliques that contain a variable of
     J, or a variable of a new factor as a frontal variable, and all their
     ancestors. The children of the top that are not in it are the orphans;
  3. it eliminates the factors whose variables all lie in the top, linearized
     at theta, together with the cached factors of the orphans, in a
     minimum degree order with the variables of the new factors last;
  4. it builds new cliques from the conditionals and puts each orphan back
     under the clique of the first eliminated variable of its separator;
  5. it updates delta from the root down. A clique is solved if it is new,
     or if a separator variable changed by more than alpha (the wildfire
     threshold). alpha = 0 updates every clique whose input changed.

A Gaussian factor is kept in information form: the matrix blocks
lam[(u, w)] and the vector blocks eta[u] of 1/2 x^T Lambda x - eta^T x.
Eliminating a variable v uses a Cholesky factor R of lam[(v, v)] and gives
the conditional R x_v + sum_s S_s x_s = d, which is one block row of the
square root information matrix, and a new factor on the other variables.
"""

import math

# ------------------------------------------------------------ small dense algebra


def wrap(a):
    return (a + math.pi) % (2.0 * math.pi) - math.pi


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


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


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


def chol_upper(a):
    """Return the upper triangular R with R^T R = a."""
    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 <= 0.0:
            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 solve_rt(r, b):
    """Solve R^T y = b for a vector b, with R upper triangular."""
    n = len(r)
    y = [0.0] * n
    for i in range(n):
        y[i] = (b[i] - sum(r[k][i] * y[k] for k in range(i))) / r[i][i]
    return y


def solve_r(r, b):
    """Solve R x = b for a vector b, with R upper triangular."""
    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


def solve_rt_mat(r, b):
    """Solve R^T Y = B column by column."""
    cols = [solve_rt(r, c) for c in transpose(b)]
    return transpose(cols)


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


class Prior:
    def __init__(self, key, mean, sigmas):
        self.keys = [key]
        self.z = list(mean)
        self.sigmas = list(sigmas)

    def error_and_jacobians(self, theta):
        x = theta[self.keys[0]]
        e = [x[0] - self.z[0], x[1] - self.z[1], wrap(x[2] - self.z[2])]
        return e, [[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]]


class Between:
    def __init__(self, i, j, z, sigmas):
        self.keys = [i, j]
        self.z = list(z)
        self.sigmas = list(sigmas)

    def error_and_jacobians(self, theta):
        a, b = theta[self.keys[0]], theta[self.keys[1]]
        c, s = math.cos(a[2]), math.sin(a[2])
        dx, dy = b[0] - a[0], b[1] - a[1]
        e = [c * dx + s * dy - self.z[0], -s * dx + c * dy - self.z[1], wrap(b[2] - a[2] - self.z[2])]
        ja = [[-c, -s, -s * dx + c * dy], [s, -c, -c * dx - s * dy], [0.0, 0.0, -1.0]]
        jb = [[c, s, 0.0], [-s, c, 0.0], [0.0, 0.0, 1.0]]
        return e, [ja, jb]


def whitened_error(f, theta):
    e, _ = f.error_and_jacobians(theta)
    return sum((v / s) ** 2 for v, s in zip(e, f.sigmas))


class GaussianFactor:
    """1/2 x^T Lambda x - eta^T x on the variables keys."""

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


def linearize(f, theta):
    """Return the Gaussian factor of f at theta, in the step delta."""
    e, js = f.error_and_jacobians(theta)
    e = [v / s for v, s in zip(e, f.sigmas)]
    js = [[[v / s for v in row] for row, s in zip(j, f.sigmas)] for j in js]
    lam, eta = {}, {}
    for u, ju in zip(f.keys, js):
        jut = transpose(ju)
        eta[u] = [-v for v in mat_vec(jut, e)]
        for w, jw in zip(f.keys, js):
            lam[(u, w)] = mul(jut, jw)
    return GaussianFactor(f.keys, lam, eta)


def _add_to(dst, src):
    for i in range(len(dst)):
        if isinstance(dst[i], list):
            for k in range(len(dst[i])):
                dst[i][k] += src[i][k]
        else:
            dst[i] += src[i]


def combine(factors, pos):
    keys = sorted({k for f in factors for k in f.keys}, key=pos.get)
    lam, eta = {}, {}
    for f in factors:
        for kw, blk in f.lam.items():
            if kw in lam:
                _add_to(lam[kw], blk)
            else:
                lam[kw] = [list(r) for r in blk]
        for k, vec in f.eta.items():
            if k in eta:
                _add_to(eta[k], vec)
            else:
                eta[k] = list(vec)
    return GaussianFactor(keys, 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 = parents
        self.r = r
        self.s = s
        self.d = d

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


def eliminate_one(joint, v):
    """Return (conditional on v, the new factor on the other variables)."""
    rest = [k for k in joint.keys if k != v]
    r = chol_upper(joint.lam[(v, v)])
    n = len(r)
    s = {}
    for k in rest:
        blk = joint.lam.get((v, k))
        s[k] = solve_rt_mat(r, blk) if blk is not None else [[0.0] * len(joint.eta[k]) for _ in range(n)]
    d = solve_rt(r, joint.eta.get(v, [0.0] * n))
    lam, eta = {}, {}
    for a in rest:
        sat = transpose(s[a])
        e = joint.eta.get(a, [0.0] * len(sat))
        eta[a] = [x - y for x, y in zip(e, mat_vec(sat, d))]
        for b in rest:
            base = joint.lam.get((a, b))
            corr = mul(sat, s[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), GaussianFactor(rest, lam, eta)


def eliminate(factors, order):
    """Variable elimination; return the conditionals in order and the produced factors."""
    pos = {v: i for i, v in enumerate(order)}
    buckets = {v: [] for v in order}
    for f in factors:
        buckets[min(f.keys, key=pos.get)].append(f)
    conds, produced = [], {}
    for v in order:
        joint = combine(buckets[v], pos)
        cond, newf = eliminate_one(joint, v)
        conds.append(cond)
        produced[v] = newf
        if newf.keys:
            buckets[min(newf.keys, key=pos.get)].append(newf)
    return conds, produced


# --------------------------------------------------------------- the Bayes 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 = {}
        self.cached = None  # the factor on sep from the elimination of this clique


def build_cliques(conds, produced, pos):
    """Return (new cliques, new roots, map from a variable to its clique)."""
    clique_of, cliques, roots = {}, [], []
    for cond in reversed(conds):
        v = cond.var
        if not cond.parents:
            c = Clique([v], [], None)
            cliques.append(c)
            roots.append(c)
        else:
            first = min(cond.parents, key=pos.get)
            p = clique_of[first]
            if set(p.frontals) | set(p.sep) == set(cond.parents):
                p.frontals.insert(0, v)  # merge: v is eliminated before the others
                c = p
            else:
                c = Clique([v], list(cond.parents), p)
                p.children.append(c)
                cliques.append(c)
        c.conds[v] = cond
        clique_of[v] = c
    for c in cliques:
        c.cached = produced[c.frontals[-1]]
    return cliques, roots, clique_of


def constrained_min_degree(variables, factors, last):
    """A minimum degree order of the variables; the variables in last go last."""
    adj = {v: set() for v in variables}
    for f in factors:
        for u in f.keys:
            adj[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(adj[v]), repr(v)))
            left.discard(u)
            nb = adj.pop(u)
            for a in nb:
                adj[a].discard(u)
                adj[a] |= nb - {a}
            order.append(u)
    return order


class ISAM2:
    def __init__(self, beta=0.1, alpha=0.0):
        self.beta = beta  # relinearization threshold
        self.alpha = alpha  # wildfire threshold of the partial back substitution
        self.theta = {}
        self.delta = {}
        self.factors = []
        self.lin = []  # the linearized factors, at the current theta
        self.roots = []
        self.clique_of = {}
        self.last_stats = {}

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

    def estimate(self):
        return {v: [a + b for a, b in zip(self.theta[v], self.delta[v])] for v in self.theta}

    def update(self, new_factors=(), new_values=None):
        new_values = new_values or {}
        for v, x in new_values.items():
            self.theta[v] = list(x)
            self.delta[v] = [0.0] * len(x)
        relin = {v for v in self.clique_of if max(abs(a) for a in self.delta[v]) >= self.beta}  # @line L1
        for v in relin:
            self.theta[v] = [a + b for a, b in zip(self.theta[v], self.delta[v])]  # @line L2
            self.theta[v][2] = wrap(self.theta[v][2])
            self.delta[v] = [0.0] * len(self.delta[v])
        new_keys = {k for f in new_factors for k in f.keys}
        marked = set()
        for c in self.cliques():  # @line L3
            if (set(c.frontals) | set(c.sep)) & relin or set(c.frontals) & new_keys:
                while c is not None and c not in marked:
                    marked.add(c)  # @line L4
                    c = c.parent
        top_vars = {v for c in marked for v in c.frontals} | (set(new_values) - set(self.clique_of))
        top_vars |= new_keys - set(self.clique_of)
        orphans = [ch for c in marked for ch in c.children if ch not in marked]  # @line L5
        for f in new_factors:
            self.factors.append(f)
            self.lin.append(None)
        n_relin = 0
        top_factors = []
        for i, f in enumerate(self.factors):
            if set(f.keys) <= top_vars:  # @line L6
                if self.lin[i] is None or set(f.keys) & relin:
                    self.lin[i] = linearize(f, self.theta)
                    n_relin += 1
                top_factors.append(self.lin[i])
        cached = [o.cached for o in orphans]  # @line L7
        variables = sorted(top_vars, key=repr)
        order = constrained_min_degree(variables, top_factors + cached, new_keys)  # @line L8
        conds, produced = eliminate(top_factors + cached, order)  # @line L9
        pos = {v: i for i, v in enumerate(order)}
        new_cliques, new_roots, cl = build_cliques(conds, produced, pos)  # @line L10
        for o in orphans:  # @line L11
            p = cl[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 marked] + new_roots
        self.clique_of.update(cl)
        visited = self._solve(set(new_cliques))  # @line L12
        self.last_stats = {
            "relinearized_variables": len(relin),
            "relinearized_factors": n_relin,
            "eliminated_cliques": len(new_cliques),
            "total_cliques": len(self.cliques()),
            "solved_cliques": visited,
        }
        return self.estimate()

    def _solve(self, dirty):
        """Partial back substitution from the roots down (wildfire)."""
        visited = 0
        stack = list(self.roots)
        changed = set()
        while stack:
            c = stack.pop()
            if c not in dirty and not (set(c.sep) & changed):
                continue  # @line L13
            visited += 1
            for v in reversed(c.frontals):
                new = c.conds[v].solve(self.delta)  # @line L14
                if max(abs(a - b) for a, b in zip(new, self.delta[v])) > self.alpha:
                    changed.add(v)  # @line L15
                self.delta[v] = new
            stack.extend(c.children)
        return visited
test_isam2.py 212 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/isam2/. The authors are listed in prov/32NTDV.jsonl.

import math
import random

from isam2 import ISAM2, Between, Prior, linearize, whitened_error, wrap

OD = [0.05, 0.05, 0.02]
LC = [0.05, 0.05, 0.02]
STEPS = 12


def compose(p, u):
    c, s = math.cos(p[2]), math.sin(p[2])
    return [p[0] + c * u[0] - s * u[1], p[1] + s * u[0] + c * u[1], wrap(p[2] + u[2])]


def between(a, b):
    c, s = math.cos(a[2]), math.sin(a[2])
    dx, dy = b[0] - a[0], b[1] - a[1]
    return [c * dx + s * dy, -s * dx + c * dy, wrap(b[2] - a[2])]


def stream(seed, laps=2, noise=True):
    """Yield (new factors, new values) per pose: two laps of a 12-sided polygon."""
    rng = random.Random(seed)
    u = [1.0, 0.0, 2.0 * math.pi / STEPS]
    truth = [[0.0, 0.0, 0.0]]
    for _ in range(laps * STEPS):
        truth.append(compose(truth[-1], u))
    guess = {0: [0.0, 0.0, 0.0]}
    out = [([Prior(0, [0.0, 0.0, 0.0], [1e-3, 1e-3, 1e-3])], {0: [0.0, 0.0, 0.0]})]
    for t in range(1, laps * STEPS + 1):
        z = between(truth[t - 1], truth[t])
        if noise:
            z = [z[0] + rng.gauss(0, OD[0]), z[1] + rng.gauss(0, OD[1]), wrap(z[2] + rng.gauss(0, OD[2]))]
        fs = [Between(t - 1, t, z, OD)]
        guess[t] = compose(guess[t - 1], z)
        if t >= STEPS:
            w = between(truth[t - STEPS], truth[t])
            if noise:
                w = [w[0] + rng.gauss(0, LC[0]), w[1] + rng.gauss(0, LC[1]), wrap(w[2] + rng.gauss(0, LC[2]))]
            fs.append(Between(t - STEPS, t, w, LC))
        out.append((fs, {t: list(guess[t])}))
    return out, truth


def dense_system(factors, theta, keys):
    pos = {k: 3 * i for i, k in enumerate(keys)}
    n = 3 * len(keys)
    lam = [[0.0] * n for _ in range(n)]
    eta = [0.0] * n
    for f in factors:
        g = linearize(f, theta)
        for (u, w), blk in g.lam.items():
            for r in range(3):
                for c in range(3):
                    lam[pos[u] + r][pos[w] + c] += blk[r][c]
        for u, vec in g.eta.items():
            for r in range(3):
                eta[pos[u] + r] += vec[r]
    return lam, eta


def dense_solve(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]
            if f:
                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 batch_gauss_newton(factors, theta, iters=20):
    keys = sorted(theta)
    theta = {k: list(v) for k, v in theta.items()}
    for _ in range(iters):
        lam, eta = dense_system(factors, theta, keys)
        dx = dense_solve(lam, eta)
        for i, k in enumerate(keys):
            x = [a + b for a, b in zip(theta[k], dx[3 * i:3 * i + 3])]
            x[2] = wrap(x[2])
            theta[k] = x
        if max(abs(v) for v in dx) < 1e-12:
            break
    return theta


def check_tree(isam):
    cliques = isam.cliques()
    frontal_count = {}
    for c in cliques:
        for v in c.frontals:
            frontal_count[v] = frontal_count.get(v, 0) + 1
        if c.parent is None:
            assert c.sep == [] and c in isam.roots
        else:
            assert c in c.parent.children
            # running intersection: the separator lies in the parent clique
            assert set(c.sep) <= set(c.parent.frontals) | set(c.parent.sep)
        for i, v in enumerate(c.frontals):
            assert set(c.conds[v].parents) <= set(c.frontals[i + 1:]) | set(c.sep)
    assert frontal_count == {v: 1 for v in isam.theta}


def tree_quadratic(isam, keys):
    """Return (Lambda, eta) = sum over the conditionals of [R S]^T [R S] and [R S]^T d."""
    pos = {k: 3 * i for i, k in enumerate(keys)}
    n = 3 * len(keys)
    lam = [[0.0] * n for _ in range(n)]
    eta = [0.0] * n
    for c in isam.cliques():
        for v, cond in c.conds.items():
            blocks = [(v, cond.r)] + [(p, cond.s[p]) for p in cond.parents]
            for u, bu in blocks:
                for w, bw in blocks:
                    for r in range(3):
                        for col in range(3):
                            lam[pos[u] + r][pos[w] + col] += sum(bu[k][r] * bw[k][col] for k in range(3))
                for r in range(3):
                    eta[pos[u] + r] += sum(bu[k][r] * cond.d[k] for k in range(3))
    return lam, eta


def test_without_relinearization_delta_equals_the_dense_solve_after_every_update():
    data, _ = stream(1)
    isam = ISAM2(beta=float("inf"), alpha=0.0)
    for t, (fs, vals) in enumerate(data):
        isam.update(fs, vals)
        if t % 4 == 0 or t == len(data) - 1:
            keys = sorted(isam.theta)
            lam, eta = dense_system(isam.factors, isam.theta, keys)
            ref = dense_solve(lam, eta)
            got = [x for k in keys for x in isam.delta[k]]
            assert max(abs(a - b) for a, b in zip(got, ref)) < 1e-9


def test_tree_invariants_and_square_root_information_hold_with_relinearization():
    data, _ = stream(2)
    isam = ISAM2(beta=0.05, alpha=0.0)
    for t, (fs, vals) in enumerate(data):
        isam.update(fs, vals)
        check_tree(isam)
        if t % 6 == 0 or t == len(data) - 1:
            keys = sorted(isam.theta)
            lam, eta = dense_system(isam.factors, isam.theta, keys)
            tl, te = tree_quadratic(isam, keys)
            assert max(abs(a - b) for r1, r2 in zip(lam, tl) for a, b in zip(r1, r2)) < 1e-6
            assert max(abs(a - b) for a, b in zip(eta, te)) < 1e-6


def test_tiny_threshold_and_empty_updates_reach_the_batch_optimum():
    data, _ = stream(3)
    isam = ISAM2(beta=1e-12, alpha=0.0)
    init = {}
    for fs, vals in data:
        isam.update(fs, vals)
        init.update(vals)
    for _ in range(6):
        isam.update()
    est = isam.estimate()
    ref = batch_gauss_newton(isam.factors, init)
    assert max(abs(wrap(a - b)) for k in ref for a, b in zip(est[k], ref[k])) < 1e-8


def test_default_threshold_is_close_to_batch_and_eliminates_few_cliques():
    data, truth = stream(4)
    isam = ISAM2(beta=0.1, alpha=0.0)
    init, elim, total = {}, 0, 0
    for fs, vals in data:
        isam.update(fs, vals)
        init.update(vals)
        elim += isam.last_stats["eliminated_cliques"]
        total += isam.last_stats["total_cliques"]
    est = isam.estimate()
    ref = batch_gauss_newton(isam.factors, init)
    assert max(abs(wrap(a - b)) for k in ref for a, b in zip(est[k], ref[k])) < 0.05
    cost_isam = sum(whitened_error(f, est) for f in isam.factors)
    cost_ref = sum(whitened_error(f, ref) for f in isam.factors)
    assert cost_ref <= cost_isam < 1.5 * cost_ref
    assert elim < total


def test_wildfire_threshold_skips_cliques_and_stays_close():
    data, _ = stream(5)
    exact = ISAM2(beta=float("inf"), alpha=0.0)
    lazy = ISAM2(beta=float("inf"), alpha=1e-3)
    for fs, vals in data:
        exact.update(fs, vals)
        lazy.update(fs, vals)
    assert max(abs(a - b) for k in exact.delta for a, b in zip(exact.delta[k], lazy.delta[k])) < 0.05
    assert lazy.last_stats["solved_cliques"] <= exact.last_stats["solved_cliques"]


def test_noise_free_stream_has_zero_error():
    data, truth = stream(6, noise=False)
    isam = ISAM2(beta=0.1, alpha=0.0)
    for fs, vals in data:
        isam.update(fs, vals)
    est = isam.estimate()
    for t, x in enumerate(truth):
        assert max(abs(wrap(a - b)) for a, b in zip(est[t], x)) < 1e-9
    assert sum(whitened_error(f, est) for f in isam.factors) < 1e-16

History

Dellaert and Kaess (2006) solved full SLAM by sparse QR in square root SAM. Kaess, Ranganathan and Dellaert (2008) made it incremental with Givens rotations in iSAM, with periodic batch steps for the ordering and the relinearization. Kaess, Ila, Roberts and Dellaert presented the Bayes tree at WAFR 2010, and Kaess et al. (2012) built iSAM2 on it. iSAM2 is the incremental solver of the GTSAM library.

References

  1. 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 creation of the Bayes tree from the eliminated factor graph, the incremental update of the top of the tree with the orphans, fluid relinearization with the threshold beta, partial state updates with the threshold alpha, and the constrained ordering
  2. 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 Bayes tree and its incremental update, the conference version of the data structure
  3. Frank Dellaert and Michael Kaess, Factor graphs for robot perception, Foundations and Trends in Robotics 6(1-2), 2017, the chapter on incremental smoothing with the Bayes tree

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.back_substitution
  • a full proof of time.eliminate_top
  • a full proof of time.worst_update
  • a full proof of space.tree
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)
WritingW2 basic
  • a scene preset for the example