Algorithm Search⌘K

Algorithmresearch

Incremental smoothing and mapping

Also called iSAM.

Incremental SLAM back end of Kaess, Ranganathan and Dellaert. It updates the square root information matrix by Givens rotations as measurements arrive, with periodic reordering and relinearization.

Solves
Full SLAM
Time
O(g (p + m) + z + (p + m)^3 / k) amortizedO((p + m)^3) batch_stepO(g (p + m) + z) incremental_update
Space
O(z) factor
Where
g = the number of Givens rotations in one update; k = the period of the batch step; m = the number of landmarks; p = the number of poses; z = the number of nonzero entries of R
Properties
cost depends on orderingdeterministicnot exactincremental
Origin
Michael Kaess, Ananth Ranganathan, Frank Dellaert, 2008

iSAM solves the full SLAM problem online. It keeps the upper triangular factor RR of the whitened measurement Jacobian, as in square root SAM, and changes it as measurements arrive instead of computing it again. A new measurement adds rows to the Jacobian. Each new row enters RR by Givens rotations, one rotation for each nonzero entry that must be cleared. A new variable adds columns at the end of the column order. After each update, one back substitution gives the new estimate. Two things go stale over time: the column order, which was chosen for the old graph, and the linearization point. So every kk updates iSAM does a batch step. It relinearizes all factors at the current estimate, finds a new fill-reducing elimination order, and factors again. The cost of each update depends on the order and the fill-in. iSAM2 later replaced the matrix by a Bayes tree and the periodic batch step by local edits.

In plain words

The robot keeps its map as a triangle of numbers that makes the answer quick to read out. When a new measurement arrives, it does not rebuild the triangle. It slides the new line of numbers into the triangle, one small turn at a time, until the line is used up or finds an empty slot. Then it reads out the new answer from the bottom up. Over time the triangle gets crowded, because the order of the unknowns was chosen for an older and smaller map. So, every so often, the robot picks a better order, redoes the straight-line view of all measurements at the current answer, and builds the triangle again.

The problem

The input is a stream of updates. Each update brings new variables with initial values and new factors, each with a measurement function hfh_f, a measurement zfz_f and a diagonal noise σf\sigma_f. After each update, the output is an estimate that minimizes, approximately, the nonlinear least squares cost ∑f∥(hf(X)−zf)/σf∥2\sum_f \|(h_f(X) - z_f) / \sigma_f\|^2 over all factors so far.

iSAM keeps the linearization point θ\theta, a column order, and the sparse upper triangular RR with the right side dd. These satisfy R⊤R=A⊤AR^\top R = A^\top A and R⊤d=A⊤bR^\top d = A^\top b, where Aδ=bA\delta = b is the whitened linear system of all factors at θ\theta. The estimate is θ⊕δ\theta \oplus \delta with Rδ=dR\delta = d. The code works with planar poses (x,y,θ)(x, y, \theta), point landmarks, a prior, odometry, and range and bearing measurements.

The algorithm

  1. UPDATE(new values Θ', new factors F')
  2. 1append the variables of Θ' to the end of the column order; θ ← θ ∪ Θ'
  3. 2for each whitened row [a | β] of the factors F' at θ do
  4. 3ROTATE-IN(a, β):
  5. 4while a has a nonzero entry do
  6. 5c ← the first column where a is not zero
  7. 6if R has no row with the pivot c then R_c ← [a | β]; stop
  8. 7apply the Givens rotation that sets a_c to 0 to the pair (R_c, [a | β])
  9. 8if the number of updates is a multiple of k then
  10. 9θ ← θ ⊕ δ; find a fill-reducing order of all variables
  11. 10R ← empty; ROTATE-IN every whitened row of every factor at θ, in the new order
  12. 11δ ← the solution of R δ = d by back substitution
  13. 12return θ ⊕ δ

The rotation (line L7). With h=(Rc)c2+ac2h = \sqrt{(R_c)_c^2 + a_c^2}, cos⁡ϕ=(Rc)c/h\cos\phi = (R_c)_c / h and sin⁡ϕ=ac/h\sin\phi = a_c / h, the pair becomes (cos⁡ϕ Rc+sin⁡ϕ a, −sin⁡ϕ Rc+cos⁡ϕ a)(\cos\phi\, R_c + \sin\phi\, a,\ -\sin\phi\, R_c + \cos\phi\, a). The first row keeps its place in RR with the pivot hh. The second row has a zero at cc, and its next nonzero entry is further right. The rotation is orthogonal, so R⊤R+a⊤aR^\top R + a^\top a does not change. A row that becomes zero except for β\beta leaves only its β\beta in the residual and is dropped.

New variables (line L1). The new columns go last. Old rows are zero there, so RR stays upper triangular. A new pose is linearized at its initial value, which is usually the estimate of the previous pose composed with the odometry.

Fill-in. A Givens rotation writes the nonzero entries of the new row into RcR_c. An odometry row from the newest pose touches only the last columns and costs a few rotations. A measurement of a landmark seen long ago starts at the old column of the landmark, rotates through every row between it and the end, and fills them. That is the fill-in that the batch step removes.

The batch step (lines L9 and L10). Kaess et al. use COLAMD for the order. The code uses minimum degree on the graph of the variables, with the degree counted in scalar columns. The batch step is also the only place where iSAM relinearizes.

Example

The robot drives two laps of a 12-sided polygon with sides of 1 m, so there are 25 poses. Six landmarks lie around the path, and the robot measures range and bearing to every landmark within 3 m. The noise is 0.05 m, 0.05 m and 0.02 rad for odometry, and 0.05 m and 0.02 rad for range and bearing. The seed is 4. In total there are 136 factors, 297 rows and 87 columns. A full upper triangle of size 87 has 3828 entries. Dead reckoning drifts to a position error of 0.714 m.

batch period kk rotations in total rotations per update in steps 20 to 23 nonzeros of the final RR final cost distance to the optimum
none 9213 750 to 832 3534 230.124 0.019
10 8659 166 to 229 1295 214.746 0.0035
5 14190 166 to 229 1193 214.141 0.00074

The optimum of the cost is 214.132. Without batch steps, the rotations per update grow from 71 at the first odometry step to about 800 in the second lap, and RR ends at 92% of a full triangle. Each landmark that comes back into view starts at an early column and fills the rows after it. With k=5k = 5, the batch steps at updates 5, 10, 15, 20 and 25 cost 517, 1415, 2368, 3200 and 3869 rotations, and the updates between them cost 78 to 242. On this small problem, the batch steps with k=5k = 5 cost more rotations in total than they save. The gains are a sparser RR, a cheaper back substitution, and an estimate close to the optimum because of the relinearization. With k=10k = 10, the total is lower than without batch steps. The largest position error against the truth is 0.081 m without batch steps and 0.073 m with k=5k = 5.

These are measurements on one small run. On long runs with many loops, the fill without reordering grows much more, and Kaess et al. report that periodic reordering keeps the update time low.

Correctness

The correctness proof shows by induction over the rows that RR stays upper triangular with nonzero pivots and that R⊤R=A⊤AR^\top R = A^\top A and R⊤d=A⊤bR^\top d = A^\top b hold for the whitened system of all factors at θ\theta. The key facts are that a Givens rotation is orthogonal, that each rotation moves the leading column of the new row to the right, and that appended columns are zero in all old rows. So the back substitution gives the exact least squares solution of the linear system at θ\theta, which is one Gauss-Newton step from θ\theta. The tests check these equations against dense products after the updates, with and without batch steps, and check a noise-free stream against the truth.

The estimate between batch steps is not a stationary point of the nonlinear cost, because the linearization point is old. It is an approximation, and the period kk controls it.

Proof: After each iSAM update, R is the triangular factor of the whitened system of all factors, and delta is its least squares solutionfull

Setting. The variables have a column order. At the linearization point θ\theta, each factor gives whitened rows [a∣β][a \mid \beta], where aa is a row of the Jacobian divided by the standard deviation and β=−e/σ\beta = -e / \sigma. Stack the rows of all factors so far into [A∣b][A \mid b]. The solver keeps a map from a pivot column cc to a row RcR_c with the right side dcd_c. Let RR be the matrix with the rows RcR_c in the order of cc, and dd the vector of the dcd_c.

The invariant is:

  • (I1) every row RcR_c is zero in the columns before cc, and (Rc)c≠0(R_c)_c \neq 0;
  • (I2) R⊤R=A⊤AR^\top R = A^\top A and R⊤d=A⊤bR^\top d = A^\top b.

Assumptions.

  • (A1) Exact arithmetic. The code drops entries below 10−1410^{-14} times the pivot, which is a rounding of zero.
  • (A2) After each update, every column has a pivot row. If not, the code raises an error, because AA then has a column that no measurement constrains in the current order and A⊤AA^\top A is singular.

Lemma 1 (one row). Let (I1) hold, and let S=R⊤RS = R^\top R, s=R⊤ds = R^\top d before ROTATE-IN of the row [a∣β][a \mid \beta]. After it, (I1) holds, and R⊤R=S+a⊤aR^\top R = S + a^\top a and R⊤d=s+a⊤βR^\top d = s + a^\top \beta.

Proof. Consider the augmented rows [Rc∣dc][R_c \mid d_c] and [a∣β][a \mid \beta]. The sum of the outer products ∑c[Rc∣dc]⊤[Rc∣dc]+[a∣β]⊤[a∣β]\sum_c [R_c \mid d_c]^\top [R_c \mid d_c] + [a \mid \beta]^\top [a \mid \beta] has S+a⊤aS + a^\top a in the top left block and s+a⊤βs + a^\top \beta in the top right block. Line L7 replaces the two rows u=[Rc∣dc]u = [R_c \mid d_c] and w=[a∣β]w = [a \mid \beta] by G(u,w)G (u, w) with G=[cos⁡ϕsin⁡ϕ−sin⁡ϕcos⁡ϕ]G = \begin{bmatrix} \cos\phi & \sin\phi \\ -\sin\phi & \cos\phi \end{bmatrix}, and G⊤G=IG^\top G = I, so u⊤u+w⊤wu^\top u + w^\top w does not change. With cos⁡ϕ=(Rc)c/h\cos\phi = (R_c)_c / h, sin⁡ϕ=ac/h\sin\phi = a_c / h and h=(Rc)c2+ac2h = \sqrt{(R_c)_c^2 + a_c^2}, the new (Rc)c(R_c)_c is h≠0h \neq 0 and the new aca_c is 00. Both rows were zero before column cc (the row aa because cc is its leading column, line L5), so they stay zero there, and the leading column of aa moves strictly to the right. So the loop of line L4 ends. It ends in one of two ways. At line L6, aa becomes the row of a column cc with no pivot; its leading column is cc and ac≠0a_c \neq 0, so (I1) holds, and the sum of outer products now counts aa in RR. Or aa has no nonzero entry left except β\beta; then [0∣β]⊤[0∣β][0 \mid \beta]^\top [0 \mid \beta] is zero outside the bottom right corner, so dropping the row does not change the two blocks. In both cases, the top left and top right blocks of the sum over the rows of RR are S+a⊤aS + a^\top a and s+a⊤βs + a^\top \beta. □\square

Claim 1 (the incremental step keeps the invariant). If (I1) and (I2) hold before an update without a batch step, they hold after it for the system with the new factors.

Proof. Line L1 appends the columns of the new variables at the end of the order. The old rows of AA and of RR are zero in the new columns, because no old factor involves a new variable, so (I1) and (I2) still hold for the extended matrices. The old variables keep their linearization point, and the new variables are linearized at their initial values, so the rows of the new factors at line L2 are exactly the new rows of AA and bb. By Lemma 1, applied once per new row at line L3, R⊤R=A⊤A+∑a⊤aR^\top R = A^\top A + \sum a^\top a and R⊤d=A⊤b+∑a⊤βR^\top d = A^\top b + \sum a^\top \beta, which are the blocks of the new system. □\square

Claim 2 (the batch step keeps the invariant). After lines L9 and L10, (I1) and (I2) hold for the system of all factors at the new linearization point and in the new order.

Proof. Line L9 sets θ\theta to the current estimate and fixes the new order. Line L10 starts with an empty RR, for which (I1) and (I2) hold for an empty system, and rotates in every row of every factor at the new θ\theta in the new order. By Lemma 1 and induction over the rows, the invariant holds for all of them. □\square

Claim 3 (the solution). After line L11, δ\delta is the unique minimizer of ∥Aδ−b∥2\|A\delta - b\|^2, the Gauss-Newton step from θ\theta for all factors.

Proof. By (A2) and (I1), RR is square and upper triangular with nonzero diagonal entries, so it is invertible and line L11 finds the unique δ\delta with Rδ=dR\delta = d. Then A⊤Aδ=R⊤Rδ=R⊤d=A⊤bA^\top A \delta = R^\top R \delta = R^\top d = A^\top b by (I2). These are the normal equations, and A⊤A=R⊤RA^\top A = R^\top R is positive definite, so δ\delta is the unique minimizer. □\square

Corollary. With the batch period k=1k = 1, each update is one Gauss-Newton step on all factors, from the current estimate. Without batch steps, the estimate θ+δ\theta + \delta is the minimizer of the linear system at the first linearization point of each variable. The tests check (I1) and (I2) and the normal equations against dense products, with and without batch steps.

What this does not show. Between batch steps, iSAM does not relinearize, so the estimate is a Gauss-Newton step from a point that can be old. It is not a stationary point of the nonlinear cost in general. The number of Givens rotations and the fill-in of RR depend on the column order; nothing here bounds them. Appending new variables at the end of an order that was chosen earlier can make RR dense, which the periodic reordering is there to undo.

Complexity

Let pp be the number of poses, mm the number of landmarks, gg the number of rotations of one update, zz the number of nonzero entries of RR, and kk the batch period.

  • One rotation touches the union of two rows, at most O(p+m)O(p + m) entries, so the rotations of one update cost O(g(p+m))O(g (p + m)).
  • The back substitution costs O(z)O(z).
  • A batch step is a sparse QR factorization of all rows. Its cost depends on the order and the fill-in, and is O((p+m)3)O((p + m)^3) in the worst case of a dense factor.
  • Memory is O(z)O(z).

The numbers gg and zz depend on the column order and the fill-in; see elimination ordering. For exploration with odometry only, gg is bounded and zz grows linearly. A loop closure to an old variable makes gg grow with the number of columns after it.

Properties

  • Exact for a fixed linearization. Between batch steps, δ\delta is the exact solution of the linear system at θ\theta.
  • Incremental. An update touches only the rows of RR from the first column of the new rows to the end.
  • Periodic batch steps. The update time has spikes at the batch steps.
  • Square root form. It never forms A⊤AA^\top A, so it avoids squaring the condition number.

Variants and improvements

  • Marginal covariances. Kaess et al. recover the needed entries of the covariance from RR by a recursion, and use them for data association.
  • Cholesky updates. A new row aa adds a⊤aa^\top a to A⊤AA^\top A. A rank one update of the Cholesky factor gives the same RR up to the signs of its rows.
  • Fixed lag. Marginalize old variables to bound the size of RR.
  • The Bayes tree. iSAM2 stores RR as a Bayes tree, reorders only the affected cliques, and relinearizes only the variables that moved. It has no periodic batch step.

When to use it

Use iSAM for online SLAM with an estimate after every measurement when the loops are rare or the batch period can be tuned. When loops are frequent or the spikes of the batch steps matter, iSAM2 is the better choice. For a one-time problem, use square root SAM or a batch Gauss-Newton solver.

Pitfalls

  • New variables in the middle. If a new variable is not put at the end of the order, the old rows of RR are no longer triangular in the new order. Append new columns.
  • Old linearization. Between batch steps, a large correction from a loop closure is computed on an old linearization. A small period kk helps, at the cost of more batch steps.
  • Poor initial values. A new pose must be initialized from the current estimate and the odometry, not from dead reckoning. Otherwise its linearization point is far from the solution.
  • Rank deficiency. A variable that no factor constrains enough has no pivot row. The graph needs a prior and enough measurements for each landmark.
  • Dropped rows. A row that becomes zero still carries its right side. Keep it in the residual if the cost is needed, but it does not change δ\delta.

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.

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

"""iSAM (Kaess, Ranganathan and Dellaert 2008) on a small planar SLAM problem.

The variables are poses ("x", t) = (x, y, theta) and point landmarks
("l", j) = (x, y). The factors are a prior on a pose, odometry between two
poses, and a range and bearing measurement of a landmark from a pose. The
noise is Gaussian with diagonal standard deviations, and each row of the
Jacobian is divided by its standard deviation.

iSAM keeps the linearization point theta, a column order of the variables,
and the upper triangular factor R with the right side d, such that
R^T R = A^T A and R^T d = A^T b, where A delta = b is the whitened linear
system of all factors so far at theta. The estimate is theta + delta with
R delta = d.

UPDATE(new values, new factors):
  1. append the new variables to the end of the column order,
  2. linearize the new factors at theta and rotate each new row into R by
     Givens rotations, one leading entry at a time,
  3. every k updates: move theta to the estimate, find a new minimum degree
     order, and factor all rows again (the batch step),
  4. solve R delta = d by back substitution.

R is sparse: a dict from the pivot column to the row, and a row is a dict
from the column to the value, with the right side under the key "rhs".
"""

import math

RHS = "rhs"


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


def dim(v):
    return 3 if v[0] == "x" else 2


class Factor:
    def __init__(self, kind, keys, z, sigmas):
        self.kind = kind
        self.keys = keys
        self.z = list(z)
        self.sigmas = list(sigmas)

    def error_and_jacobians(self, theta):
        """Return (e, [J for each key]) with e = h(theta) - z, not whitened."""
        if self.kind == "prior":
            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]]]
        if self.kind == "odometry":
            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]
        if self.kind == "bearing_range":
            x, m = theta[self.keys[0]], theta[self.keys[1]]
            dx, dy = m[0] - x[0], m[1] - x[1]
            q = dx * dx + dy * dy
            r = math.sqrt(q)
            e = [r - self.z[0], wrap(math.atan2(dy, dx) - x[2] - self.z[1])]
            jx = [[-dx / r, -dy / r, 0.0], [dy / q, -dx / q, -1.0]]
            jm = [[dx / r, dy / r], [-dy / q, dx / q]]
            return e, [jx, jm]
        raise ValueError("unknown factor kind")


def squared_error(factors, theta):
    tot = 0.0
    for f in factors:
        e, _ = f.error_and_jacobians(theta)
        tot += sum((a / s) ** 2 for a, s in zip(e, f.sigmas))
    return tot


def fill_reducing_order(factors, variables):
    """Minimum degree on the variable graph, with the degree in scalar columns."""
    nb = {v: set() for v in variables}
    for f in factors:
        for u in f.keys:
            nb[u] |= set(f.keys) - {u}
    order = []
    while nb:
        u = min(nb, key=lambda v: (sum(dim(w) for w in nb[v]), v))
        around = nb.pop(u)
        for a in around:
            nb[a].discard(u)
            nb[a] |= around - {a}
        order.append(u)
    return order


class ISAM:
    def __init__(self, k=10):
        self.k = k  # the period of the batch step
        self.theta = {}  # the linearization point
        self.order = []
        self.start = {}
        self.n = 0
        self.r = {}
        self.factors = []
        self.delta = []
        self.updates = 0
        self.last_givens = 0
        self.total_givens = 0
        self.batch_steps = 0

    # ---------------------------------------------------------- helpers

    def _append(self, v):
        self.order.append(v)
        self.start[v] = self.n
        self.n += dim(v)
        self.delta.extend([0.0] * dim(v))

    def rows(self, factors):
        """The whitened rows of [A | b] of the factors at theta, as sparse dicts."""
        out = []
        for f in factors:
            e, js = f.error_and_jacobians(self.theta)
            for i in range(len(e)):
                row = {}
                for v, jv in zip(f.keys, js):
                    for c in range(dim(v)):
                        if jv[i][c] != 0.0:
                            row[self.start[v] + c] = jv[i][c] / f.sigmas[i]
                row[RHS] = -e[i] / f.sigmas[i]
                out.append(row)
        return out

    def _rotate_in(self, row):
        """Eliminate one row into R by Givens rotations; return the rotation count."""
        count = 0
        a = dict(row)
        while True:  # @line L4
            cols = [c for c in a if c != RHS]
            if not cols:
                return count
            c = min(cols)  # @line L5
            if c not in self.r:
                self.r[c] = a  # @line L6
                return count
            p = self.r[c]
            h = math.hypot(p[c], a[c])
            cs, sn = p[c] / h, a[c] / h
            new_p, new_a = {}, {}
            for j in set(p) | set(a):
                u, w = p.get(j, 0.0), a.get(j, 0.0)
                new_p[j] = cs * u + sn * w  # @line L7
                new_a[j] = -sn * u + cs * w
            new_p[c] = h
            new_a.pop(c, None)
            self.r[c] = {j: x for j, x in new_p.items() if j == RHS or x != 0.0}
            a = {j: x for j, x in new_a.items() if j == RHS or abs(x) > 1e-14 * h}
            count += 1

    def _solve(self):
        delta = [0.0] * self.n
        for c in range(self.n - 1, -1, -1):
            row = self.r[c]
            s = row.get(RHS, 0.0) - sum(x * delta[j] for j, x in row.items() if j != RHS and j > c)
            delta[c] = s / row[c]
        return delta

    def estimate(self):
        out = {}
        for v in self.order:
            s = self.start[v]
            x = [a + b for a, b in zip(self.theta[v], self.delta[s:s + dim(v)])]
            if v[0] == "x":
                x[2] = wrap(x[2])
            out[v] = x
        return out

    def nnz(self):
        return sum(1 for row in self.r.values() for j in row if j != RHS)

    # ---------------------------------------------------------- the update

    def update(self, new_values, new_factors):
        for v in sorted(new_values):
            self.theta[v] = list(new_values[v])
            self._append(v)  # @line L1
        self.factors.extend(new_factors)
        count = 0
        for row in self.rows(new_factors):  # @line L2
            count += self._rotate_in(row)  # @line L3
        self.updates += 1
        if self.updates % self.k == 0:  # @line L8
            self.theta = self.estimate()  # @line L9
            self.order = fill_reducing_order(self.factors, list(self.theta))
            self.start, self.n = {}, 0
            for v in list(self.order):
                self.start[v] = self.n
                self.n += dim(v)
            self.r = {}
            for row in self.rows(self.factors):  # @line L10
                count += self._rotate_in(row)
            self.batch_steps += 1
        if len(self.r) != self.n:
            raise ValueError("the system is rank deficient: a variable is not constrained")
        self.delta = self._solve()  # @line L11
        self.last_givens = count
        self.total_givens += count
        return self.estimate()  # @line L12
test_isam.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/isam/. The authors are listed in prov/CYW7G6.jsonl.

import math
import random

import pytest

from isam import ISAM, RHS, Factor, squared_error, wrap

OD = [0.05, 0.05, 0.02]
BR = [0.05, 0.02]
STEPS = 12
RANGE = 3.0


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, n_landmarks=6):
    """Per step t: (odometry from t - 1 or None, [(landmark, range and bearing)]).

    The robot drives laps of a 12-sided polygon with sides of 1 m.
    """
    rng = random.Random(seed)
    radius = 0.5 / math.sin(math.pi / STEPS)
    marks = []
    for j in range(n_landmarks):
        a = 2.0 * math.pi * j / n_landmarks + rng.uniform(-0.3, 0.3)
        d = radius + rng.uniform(-1.2, 1.2)
        marks.append([d * math.cos(a), radius + d * math.sin(a)])
    u = [1.0, 0.0, 2.0 * math.pi / STEPS]
    truth = [[0.0, 0.0, 0.0]]
    steps = []
    for t in range(laps * STEPS + 1):
        odo = None
        if t > 0:
            truth.append(compose(truth[-1], u))
            odo = between(truth[t - 1], truth[t])
            if noise:
                odo = [odo[0] + rng.gauss(0, OD[0]), odo[1] + rng.gauss(0, OD[1]), wrap(odo[2] + rng.gauss(0, OD[2]))]
        seen = []
        x = truth[t]
        for j, m in enumerate(marks):
            dx, dy = m[0] - x[0], m[1] - x[1]
            r = math.hypot(dx, dy)
            if r <= RANGE:
                z = [r, wrap(math.atan2(dy, dx) - x[2])]
                if noise:
                    z = [z[0] + rng.gauss(0, BR[0]), wrap(z[1] + rng.gauss(0, BR[1]))]
                seen.append((j, z))
        steps.append((odo, seen))
    truth_map = {("x", t): p for t, p in enumerate(truth)}
    truth_map.update({("l", j): m for j, m in enumerate(marks)})
    return steps, truth_map


def new_values_and_factors(t, step, est):
    """Build the factors of step t and initial values from the current estimate est."""
    odo, seen = step
    if odo is None:
        pose = [0.0, 0.0, 0.0]
        factors = [Factor("prior", [("x", 0)], pose, [1e-3, 1e-3, 1e-3])]
    else:
        pose = compose(est[("x", t - 1)], odo)
        factors = [Factor("odometry", [("x", t - 1), ("x", t)], odo, OD)]
    values = {("x", t): pose}
    for j, z in seen:
        factors.append(Factor("bearing_range", [("x", t), ("l", j)], z, BR))
        if ("l", j) not in est and ("l", j) not in values:
            values[("l", j)] = [pose[0] + z[0] * math.cos(pose[2] + z[1]), pose[1] + z[0] * math.sin(pose[2] + z[1])]
    return values, factors


def run(isam, steps, check=None):
    est = {}
    for t, step in enumerate(steps):
        values, factors = new_values_and_factors(t, step, est)
        est = isam.update(values, factors)
        if check:
            check(t, isam)
    return est


def dense_check(isam, tol=1e-7):
    """R^T R = A^T A, R^T d = A^T b, and delta solves the normal equations."""
    n = isam.n
    rows = isam.rows(isam.factors)
    ata = [[0.0] * n for _ in range(n)]
    atb = [0.0] * n
    for row in rows:
        items = [(c, x) for c, x in row.items() if c != RHS]
        for c1, x1 in items:
            atb[c1] += x1 * row[RHS]
            for c2, x2 in items:
                ata[c1][c2] += x1 * x2
    rtr = [[0.0] * n for _ in range(n)]
    rtd = [0.0] * n
    for c, row in isam.r.items():
        assert all(j == RHS or j >= c for j in row)  # upper triangular
        items = [(j, x) for j, x in row.items() if j != RHS]
        for c1, x1 in items:
            rtd[c1] += x1 * row.get(RHS, 0.0)
            for c2, x2 in items:
                rtr[c1][c2] += x1 * x2
    scale = max(abs(x) for r in ata for x in r)
    assert max(abs(a - b) for r1, r2 in zip(ata, rtr) for a, b in zip(r1, r2)) < tol * scale
    assert max(abs(a - b) for a, b in zip(atb, rtd)) < tol * scale
    res = [sum(ata[i][j] * isam.delta[j] for j in range(n)) - atb[i] for i in range(n)]
    assert max(abs(x) for x in res) < tol * scale


def batch_optimum(factors, start, iters=3):
    """Gauss-Newton on all factors from start, by batch steps of a fresh solver."""
    values = dict(start)
    for _ in range(iters):
        values = ISAM(k=1).update(values, factors)
    return values


def test_factor_matches_the_normal_equations_after_every_update_without_batch_steps():
    steps, _ = stream(1)
    isam = ISAM(k=10 ** 9)
    run(isam, steps, lambda t, s: dense_check(s) if t % 6 == 0 or t == len(steps) - 1 else None)
    assert isam.batch_steps == 0


def test_factor_matches_the_normal_equations_across_batch_steps():
    steps, _ = stream(2)
    isam = ISAM(k=4)
    run(isam, steps, lambda t, s: dense_check(s) if t % 5 == 0 or t == len(steps) - 1 else None)
    assert isam.batch_steps == len(steps) // 4


def test_noise_free_stream_gives_the_true_map_and_path():
    steps, truth = stream(3, noise=False)
    est = run(ISAM(k=7), steps)
    for key, x in truth.items():
        assert max(abs(wrap(a - b)) for a, b in zip(est[key], x)) < 1e-9


def test_estimate_is_close_to_the_batch_optimum():
    steps, _ = stream(4)
    isam = ISAM(k=5)
    est = run(isam, steps)
    ref = batch_optimum(isam.factors, est)
    c_isam, c_ref = squared_error(isam.factors, est), squared_error(isam.factors, ref)
    assert c_ref <= c_isam < 1.2 * c_ref


def test_reordering_keeps_the_factor_sparse():
    steps, _ = stream(4)
    plain, reordered = ISAM(k=10 ** 9), ISAM(k=5)
    g_plain, g_reordered = [], []
    run(plain, steps, lambda t, s: g_plain.append(s.last_givens))
    run(reordered, steps, lambda t, s: g_reordered.append(s.last_givens))
    assert reordered.nnz() < plain.nnz()
    # updates right after a batch step need fewer rotations than without reordering
    for t in (20, 21, 22, 23):
        assert g_reordered[t] < g_plain[t]


def test_an_unconstrained_variable_is_an_error():
    isam = ISAM()
    with pytest.raises(ValueError):
        isam.update({("x", 0): [0.0, 0.0, 0.0]}, [])

History

Dellaert and Kaess (2006) solved full SLAM in batch with sparse QR or Cholesky in square root SAM. Kaess, Ranganathan and Dellaert (2008) made it incremental with Givens rotations and periodic reordering and relinearization, and called it iSAM. Kaess and colleagues later replaced the matrix by the Bayes tree, first at WAFR 2010 and then in iSAM2 (2012).

References

  1. Michael Kaess, Ananth Ranganathan and Frank Dellaert, iSAM: incremental smoothing and mapping, IEEE Transactions on Robotics 24(6), 2008, pages 1365 to 1378, the update of the square root information matrix by Givens rotations, the periodic variable reordering and relinearization, and the recovery of marginal covariances for data association
  2. Frank Dellaert and Michael Kaess, Square root SAM: simultaneous localization and mapping via square root information smoothing, International Journal of Robotics Research 25(12), 2006, pages 1181 to 1203, the batch factorization of the measurement Jacobian that iSAM updates
  3. Timothy A. Davis, Direct Methods for Sparse Linear Systems, SIAM, 2006, sparse QR factorization, fill-in and fill-reducing orderings

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.amortized
  • a full proof of time.batch_step
  • a full proof of time.incremental_update
  • a full proof of space.factor
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