Algorithm Search⌘K

Algorithmadvanced

Square root smoothing and mapping

Also called square root SAM.

The full SLAM method of Dellaert and Kaess. It factors the sparse measurement Jacobian by QR or Cholesky in a fill-reducing variable order and solves by back substitution.

Solves
Full SLAM
Time
O(k n^2) factor_worstO(k) linearizeO(c) solveO(I k n^2) total_worst
Space
O(c) factorO(k) jacobian
Where
I = the number of Gauss-Newton iterations; c = the number of nonzero entries of R; k = the number of scalar measurement rows; m = the number of landmarks; n = the number of scalar unknowns; p = the number of poses
Properties
batchcost depends on orderingdeterministicnot exact
Origin
Frank Dellaert, Michael Kaess, 2006

Square root smoothing and mapping (square root SAM) solves the full SLAM problem as a sparse least squares problem. At each Gauss-Newton step, it builds the whitened Jacobian AA of all measurements, factors it as A=QRA = Q R by a QR decomposition, or factors A⊤A=R⊤RA^\top A = R^\top R by a Cholesky decomposition, and solves R δ=dR\,\delta = d by back substitution. The factor RR is the square root of the information matrix, hence the name. Dellaert and Kaess (2006) showed that the work and the fill-in of RR depend on the order of the columns, and that a fill-reducing elimination ordering keeps RR sparse. Unlike GraphSLAM, which always removes the landmarks first, square root SAM lets the ordering choose, and it never forms the inverse.

In plain words

All the measurements form one large system of equations with more equations than unknowns. Each equation touches only a pose and a landmark, or two poses. The method rewrites the system into a staircase shape, where the last unknown can be found alone, then the one before it, and so on back to the first. The rewrite keeps all the information. The order in which the unknowns are placed decides how many new entries the staircase gets. A good order keeps the staircase almost as empty as the original system, and so the work stays small. A bad order can fill it almost completely.

The problem

The variables are θ=(x0,…,xT,m1,…,mM)\theta = (x_0, \dots, x_T, m_1, \dots, m_M), with planar poses and point landmarks. Each factor ff has a measurement zfz_f, a model hfh_f and a Gaussian noise with covariance Σf\Sigma_f. The cost is

J(θ)=∑f∥hf(θ)−zf∥Σf2,∥e∥Σ2=e⊤Σ−1e.J(\theta) = \sum_f \|h_f(\theta) - z_f\|^2_{\Sigma_f}, \qquad \|e\|^2_\Sigma = e^\top \Sigma^{-1} e.

Linearize at the estimate θ\theta, with the Jacobian HfH_f of hfh_f, and whiten each factor by Σf−1/2\Sigma_f^{-1/2}. The step δ\delta minimizes

∥Aδ−b∥2,A=[⋮Σf−1/2Hf⋮],b=[⋮−Σf−1/2(hf(θ)−zf)⋮].\|A\delta - b\|^2, \qquad A = \begin{bmatrix} \vdots \\ \Sigma_f^{-1/2} H_f \\ \vdots \end{bmatrix}, \quad b = \begin{bmatrix} \vdots \\ -\Sigma_f^{-1/2}(h_f(\theta) - z_f) \\ \vdots \end{bmatrix}.

The code has a prior on x0x_0, odometry factors that measure the pose xtx_{t} in the frame of xt−1x_{t-1}, and range and bearing factors. The noise is diagonal, so whitening divides each row by its standard deviation. Poses are updated by adding δ\delta to (x,y,θ)(x, y, \theta) and wrapping the angle.

The algorithm

  1. SQRT-SAM(factors, θ)
  2. 1π ← a fill-reducing order of the variables (block minimum degree)
  3. 2repeat
  4. 3A, b ← the whitened Jacobian and right side at θ, with the columns in the order π
  5. 4R, d ← GIVENS-QR(A, b)
  6. 5δ ← the solution of R δ = d by back substitution
  7. 6θ ← θ ⊕ δ
  8. 7until max |δ| < tol
  9. 8return θ, R
  10. GIVENS-QR(A, b)
  11. 9R ← no rows
  12. 10for each row a of [A | b] do
  13. 11while a has a nonzero entry in A; let c be its first column do
  14. 12if R has no row with the pivot c then store a as that row; next row
  15. 13rotate the row of R with the pivot c and a by a Givens rotation that sets a_c to 0
  16. 14return R and its right side column d

Line L13 uses a Givens rotation. A row that becomes zero leaves its right side behind, which is a part of the final residual. Lines L9 to L14 are the row by row form that iSAM also uses to add new rows. A batch code would use a multifrontal QR or a sparse Cholesky of A⊤AA^\top A; the result is the same RR up to the signs of its rows. The code computes the Cholesky form too, as a check.

The ordering. Line L1 orders the variables, not the scalar columns, because the columns of one variable are always dense together. Block minimum degree takes the graph whose vertices are the variables and whose edges join two variables that share a factor. It removes a variable with the fewest scalar neighbors, joins all its neighbors into a clique, and repeats. This is minimum degree ordering on the variable graph. Dellaert and Kaess used COLAMD, an approximate minimum degree order for the columns of AA. Nested dissection is the other common choice. Finding an order with the least fill is NP-hard (Yannakakis 1981), so all of these are heuristics.

Example

The robot drives 12 steps of 1 m with a turn of 30°30° after each, a closed polygon of radius 1.931.93 m, among 6 landmarks, and measures each landmark within 3 m. The noise is 0.020.02 m and 0.010.01 rad on the odometry, and 0.050.05 m and 0.020.02 rad on range and bearing. With the seed 4 there are 1 prior, 12 odometry factors and 40 range and bearing factors. AA has 119 rows, 51 columns (13×3+6×213 \times 3 + 6 \times 2) and 503 nonzero entries. A full upper triangle of size 51 has 1326 entries.

column order nonzero entries of RR Givens rotations
block minimum degree 573 1636
natural: x0,…,x12x_0, \dots, x_{12}, then l0,…,l5l_0, \dots, l_5 653 2729
landmarks first, then the poses 1038 2701

The landmarks-first order is the order of GraphSLAM: after the landmarks, the pose block of RR is almost full. The minimum degree order starts with the poses x9,x10,x0,x1,x12,x11x_9, x_{10}, x_0, x_1, x_{12}, x_{11}, which see few landmarks, and ends with four landmarks. All three orders give the same solution to 10−810^{-8}.

Gauss-Newton from dead reckoning took 7 iterations. The largest step was 0.2280.228, then 7.5×10−37.5 \times 10^{-3}, 1.2×10−41.2 \times 10^{-4}, 2.9×10−62.9 \times 10^{-6} and 2.6×10−82.6 \times 10^{-8}. The cost JJ went from 549.57 to 66.20. The error of the last position went from 0.239 m (dead reckoning) to 0.054 m, and every landmark is within 0.062 m of the truth.

Correctness

The correctness proof shows that the row by row Givens rotations build an upper triangular RR with Q⊤[A∣b]=[Rd0e]Q^\top [A \mid b] = \begin{bmatrix} R & d \\ 0 & e \end{bmatrix} for an orthogonal QQ. Then ∥Aδ−b∥2=∥Rδ−d∥2+∥e∥2\|A\delta - b\|^2 = \|R\delta - d\|^2 + \|e\|^2, so back substitution gives the unique least squares step when AA has full column rank. It also shows that a permutation of the columns permutes the step and changes nothing else, so the order affects only the cost. A fixed point of the loop has a zero gradient. The tests check RR against a Cholesky factor of A⊤AA^\top A, check the step against the normal equations, check three orders against each other, and check that the gradient at the noisy solution is below 10−610^{-6}.

Proof: Row by row Givens QR gives the least squares step of square root SAM, for every column orderfull

Setting. AA is a real M×nM \times n matrix with rank nn, and b∈RMb \in \mathbb{R}^M. The rows of [A∣b][A \mid b] are processed one at a time by lines L9 to L14. A stored row with the pivot cc has zeros in all columns before cc. A Givens rotation of two rows pp and aa that both start at column cc, with h=pc2+ac2h = \sqrt{p_c^2 + a_c^2}, cos⁡=pc/h\cos = p_c / h and sin⁡=ac/h\sin = a_c / h, replaces them by cos⁡ p+sin⁡ a\cos\, p + \sin\, a and −sin⁡ p+cos⁡ a-\sin\, p + \cos\, a. The column bb is rotated with the rest of the row.

Assumptions.

  • (A1) Exact arithmetic. (The code drops entries below 10−14h10^{-14} h after a rotation, which is rounding noise.)
  • (A2) AA has full column rank, which the prior on the first pose ensures in the tests.

Claim 1. When line L14 is reached, the stored rows form an upper triangular n×nn \times n matrix RR with a nonzero diagonal, a vector dd, and a vector ee of the right sides of the rows that became zero, such that there is an orthogonal QQ with

Q⊤[A∣b]=[Rd0e].Q^\top [A \mid b] = \begin{bmatrix} R & d \\ 0 & e \end{bmatrix}.

Proof. Keep the invariant: the stored rows, the zero rows found so far and the rows not yet processed together equal Qk⊤[A∣b]Q_k^\top [A \mid b] for an orthogonal QkQ_k, up to the order of the rows. At the start Q0=IQ_0 = I. Installing a row at line L12 does not change the set of rows. A Givens rotation acts on two rows with an orthogonal 2×22 \times 2 matrix, so the invariant holds with Qk+1⊤=GQk⊤Q_{k+1}^\top = G Q_k^\top. A rotation sets the entry of the new row at column cc to −sin⁡pc+cos⁡ac=(−acpc+pcac)/h=0-\sin p_c + \cos a_c = (-a_c p_c + p_c a_c)/h = 0, and the rows have no entry before cc, so the leading column of the new row moves strictly to the right. Hence each row is rotated at most nn times and is then installed or becomes zero, and the algorithm ends. Each stored row has its pivot cc as its first nonzero entry, and there is at most one stored row per pivot, so the stored rows sorted by pivot form an upper triangular matrix with nonzero diagonal entries. By (A2) the rank of AA is nn, and orthogonal transforms keep the rank, so all nn pivots are present. □\square

Claim 2. The solution δ\delta of Rδ=dR \delta = d by back substitution is the unique minimizer of ∥Aδ−b∥2\|A\delta - b\|^2.

Proof. Orthogonal matrices keep the norm, so by Claim 1,

∥Aδ−b∥2=∥Q⊤(Aδ−b)∥2=∥Rδ−d∥2+∥e∥2.\|A\delta - b\|^2 = \|Q^\top (A\delta - b)\|^2 = \|R\delta - d\|^2 + \|e\|^2.

The second term does not depend on δ\delta, and the first is zero exactly when Rδ=dR\delta = d. RR is triangular with a nonzero diagonal, so back substitution finds this unique δ\delta. □\square

It also follows that R⊤R=A⊤AR^\top R = A^\top A, so RR is the Cholesky factor of A⊤AA^\top A up to the signs of its rows. The test checks this against a separate Cholesky decomposition.

Claim 3 (the column order). Let PP be a permutation matrix of the columns. The step computed with the columns in the order PP is PP applied to the step computed in the natural order.

Proof. With the permuted columns the matrix is APA P. The minimizer of ∥APγ−b∥2\|A P \gamma - b\|^2 is γ=P⊤δ\gamma = P^\top \delta, because δ↦P⊤δ\delta \mapsto P^\top \delta is a bijection and ∥AP(P⊤δ)−b∥=∥Aδ−b∥\|A P (P^\top \delta) - b\| = \|A\delta - b\|. By Claim 2 the code finds this unique minimizer, so the variables get the same values. □\square

The column order therefore changes only the number of nonzero entries of RR and the number of rotations, never the result. The test runs three orders and gets the same solution within 10−810^{-8}.

Claim 4 (the Gauss-Newton loop). If lines L2 to L7 reach a step δ=0\delta = 0, the gradient of the cost ∑∥ef/σf∥2\sum \|e_f / \sigma_f\|^2 at the estimate is zero.

Proof. AA is the whitened Jacobian and bb is minus the whitened error, so the gradient of the cost is −2A⊤b-2 A^\top b. By Claim 2, δ\delta solves the normal equations A⊤Aδ=A⊤bA^\top A \delta = A^\top b. If δ=0\delta = 0, then A⊤b=0A^\top b = 0. □\square

What this does not show. The loop is Gauss-Newton. It converges only near a minimum, the cost is not convex, and the minimum it reaches can be local. The claims say nothing about how much fill-in an order causes; minimum degree is a heuristic.

Complexity

Let kk be the number of scalar rows, nn the number of scalar unknowns (3p+2m3p + 2m in the plane) and cc the number of nonzero entries of RR.

  • Linearize: O(k)O(k), because each row has a bounded number of entries.
  • Factor: the cost depends on the variable ordering and the fill-in. A dense QR would cost O(kn2)O(k n^2), which is the worst case. With a good ordering on typical SLAM graphs, the cost is far smaller; in the example, minimum degree used 1636 rotations instead of 2701 for the landmarks-first order.
  • Solve: O(c)O(c) for the back substitution.
  • Memory: O(k)O(k) for AA and O(c)O(c) for RR.

No useful bound on cc holds for all graphs. For planar graphs, nested dissection gives c=O(nlog⁡n)c = O(n \log n) for the Cholesky factor (Lipton, Rose and Tarjan); a SLAM graph with long loops and landmarks seen from far is not planar in general. The number of iterations is measured, not bounded.

Properties

  • No inverse. It never forms Σ\Sigma or Ω−1\Omega^{-1}. Marginal covariances, if needed, come from RR by a separate recursion.
  • Numerically stable. QR works on AA, not on A⊤AA^\top A, so the condition number is not squared. The Cholesky form is faster and works well when the problem is well conditioned.
  • Batch. Each iteration factors from the start. iSAM adds rows to RR instead, and iSAM2 keeps RR as a Bayes tree.
  • The same graph as a factor graph. AA is the matrix of the factor graph, and the factorization is variable elimination in the chosen order.

Variants and improvements

  • Cholesky instead of QR. Factor A⊤AA^\top A with a sparse Cholesky. It does less work than QR, because it does not touch the rows of AA twice, but it squares the condition number. Dellaert and Kaess compare both forms.
  • Levenberg-Marquardt or dogleg. Replace the plain Gauss-Newton step by Levenberg-Marquardt or Powell's dogleg when the start is poor.
  • Incremental. iSAM updates RR with Givens rotations as new rows arrive, and iSAM2 updates only a part of a Bayes tree.
  • Constrained orders. For an online system, put the newest variables last, so that new rows touch only the end of RR.

When to use it

Use square root SAM for batch full SLAM when the problem fits in memory, the data association is fixed, and a good initial guess exists. For a robot that must keep its estimate current as it drives, use iSAM2. For a certificate of global optimality on pose graphs, use SE-Sync.

Pitfalls

  • A missing prior. Without a prior or an anchor, AA does not have full column rank, and the factorization meets a zero pivot. The code raises an error.
  • A bad ordering. A natural or landmarks-first order can fill RR. In larger problems the difference becomes orders of magnitude.
  • Unwrapped angle residuals. Wrap every angle error to [−π,π)[-\pi, \pi) before whitening.
  • Rank loss by geometry. A landmark seen once by a bearing only sensor, or seen along one line, makes AA rank deficient in that direction.

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.

square_root_sam.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/square-root-sam/. The authors are listed in prov/ZY48RG.jsonl.

"""Square root SAM (Dellaert and Kaess 2006) 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:
  prior(v, mean, sigmas)            the pose v is near mean
  odometry(i, j, z, sigmas)         the pose j seen from the pose i is z
  bearing_range(i, j, z, sigmas)    the landmark j is at (range, bearing) z from i
The noise of each factor is Gaussian with a diagonal covariance, given by
the standard deviations "sigmas". Each row of the Jacobian is divided by
its sigma (whitened), so the problem is min ||A delta - b||^2.

Each Gauss-Newton step:
  1. builds the whitened Jacobian A and the right side b at the estimate,
     with the columns in a fixed variable order,
  2. factors A = Q R by Givens rotations, one row at a time, and applies the
     same rotations to b, which gives d = Q^T b,
  3. solves R delta = d by back substitution, and
  4. adds delta to the estimate.

The column order matters only for the speed and the fill-in of R, not for
the solution. block_minimum_degree() gives a fill-reducing order on the
graph of the variables. cholesky_factor() gives the same R from A^T A, as a
second method.

R is stored sparse: a dict from the pivot column to the row, and each row
is a dict from the column to the value. The right side is 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


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


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_k for each key]) with e the unwhitened error h(theta) - z."""
        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 prior(v, mean, sigmas):
    return Factor("prior", [v], mean, sigmas)


def odometry(i, j, z, sigmas):
    return Factor("odometry", [i, j], z, sigmas)


def bearing_range(i, j, z, sigmas):
    return Factor("bearing_range", [i, j], z, sigmas)


# ---------------------------------------------------------------- ordering


def variable_graph(factors):
    adj = {}
    for f in factors:
        for u in f.keys:
            adj.setdefault(u, set())
            for v in f.keys:
                if v != u:
                    adj[u].add(v)
    return adj


def block_minimum_degree(factors):
    """Return a variable order: repeatedly eliminate a variable of least degree.

    The degree counts scalar columns, so a pose weighs 3 and a landmark 2.
    Ties go to the smallest variable in sort order, so the order is fixed.
    """
    adj = {u: set(n) for u, n in variable_graph(factors).items()}
    order = []
    while adj:
        u = min(adj, key=lambda v: (sum(dim(w) for w in adj[v]), v))
        nb = adj.pop(u)
        for a in nb:
            adj[a].discard(u)
            adj[a] |= nb - {a}
        order.append(u)
    return order


def columns(order):
    """Return (start column of each variable, total number of columns)."""
    start, n = {}, 0
    for v in order:
        start[v] = n
        n += dim(v)
    return start, n


# ---------------------------------------------------------------- the linear system


def linearize(factors, theta, order):
    """Return the whitened rows of [A | b] as sparse dicts, with b = -e / sigma."""
    start, _ = columns(order)
    rows = []
    for f in factors:
        e, js = f.error_and_jacobians(theta)
        for r in range(len(e)):
            row = {}
            for v, jv in zip(f.keys, js):
                for c in range(dim(v)):
                    if jv[r][c] != 0.0:
                        row[start[v] + c] = jv[r][c] / f.sigmas[r]
            row[RHS] = -e[r] / f.sigmas[r]
            rows.append(row)
    return rows


def givens_qr(rows, n):
    """Return R (dict pivot -> row) by Givens rotations applied row by row.

    Each new row is rotated against the rows of R with the same leading
    column until it has a new leading column or becomes zero. The count of
    rotations is returned as well.
    """
    r = {}  # @line L9
    count = 0
    for row in rows:  # @line L10
        a = {k: v for k, v in row.items() if k == RHS or v != 0.0}
        while True:
            cols = [k for k in a if k != RHS]
            if not cols:
                break
            c = min(cols)  # @line L11
            if c not in r:
                r[c] = a  # @line L12
                break
            p = r[c]
            x, y = p[c], a[c]
            h = math.hypot(x, y)
            cs, sn = x / h, y / h
            new_p, new_a = {}, {}
            for k in set(p) | set(a):
                u, w = p.get(k, 0.0), a.get(k, 0.0)
                new_p[k] = cs * u + sn * w  # @line L13
                new_a[k] = -sn * u + cs * w
            new_p[c] = h
            new_a.pop(c, None)
            r[c] = {k: v for k, v in new_p.items() if k == RHS or abs(v) > 1e-300}
            a = {k: v for k, v in new_a.items() if k == RHS or abs(v) > 1e-14 * h}
            count += 1
    if len(r) != n:
        raise ValueError("the system is rank deficient: add a prior")
    return r, count  # @line L14


def back_substitute(r, n):
    """Solve R delta = d, with d in the column RHS of R."""
    delta = [0.0] * n
    for c in range(n - 1, -1, -1):
        row = r[c]
        s = row.get(RHS, 0.0) - sum(v * delta[k] for k, v in row.items() if k != RHS and k > c)
        delta[c] = s / row[c]
    return delta


def nnz(r):
    return sum(1 for row in r.values() for k, v in row.items() if k != RHS and v != 0.0)


def dense(rows, n):
    """Return (A, b) as dense lists."""
    a = [[row.get(c, 0.0) for c in range(n)] for row in rows]
    return a, [row.get(RHS, 0.0) for row in rows]


def cholesky_factor(rows, n):
    """Return the upper triangular R with R^T R = A^T A, by the Cholesky method (dense)."""
    a, _ = dense(rows, n)
    m = [[sum(a[k][i] * a[k][j] for k in range(len(a))) for j in range(n)] for i in range(n)]
    r = [[0.0] * n for _ in range(n)]
    for i in range(n):
        s = m[i][i] - sum(r[k][i] ** 2 for k in range(i))
        if s <= 0.0:
            raise ValueError("A^T A is not positive definite")
        r[i][i] = math.sqrt(s)
        for j in range(i + 1, n):
            r[i][j] = (m[i][j] - sum(r[k][i] * r[k][j] for k in range(i))) / r[i][i]
    return r


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


def total_error(factors, theta):
    """Return the sum of the squared whitened errors."""
    tot = 0.0
    for f in factors:
        e, _ = f.error_and_jacobians(theta)
        tot += sum((ei / si) ** 2 for ei, si in zip(e, f.sigmas))
    return tot


def square_root_sam(factors, theta, order=None, iterations=20, tol=1e-10):
    """Return (theta, R, number of iterations) by Gauss-Newton with QR."""
    if order is None:
        order = block_minimum_degree(factors)  # @line L1
    _, n = columns(order)
    r = None
    it = 0
    for it in range(1, iterations + 1):  # @line L2
        rows = linearize(factors, theta, order)  # @line L3
        r, _ = givens_qr(rows, n)  # @line L4
        delta = back_substitute(r, n)  # @line L5
        theta = retract(theta, order, delta)  # @line L6
        if max(abs(d) for d in delta) < tol:  # @line L7
            break
    return theta, r, it  # @line L8
test_square_root_sam.py 166 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/square-root-sam/. The authors are listed in prov/ZY48RG.jsonl.

import math
import random

import pytest

from square_root_sam import (
    RHS,
    back_substitute,
    bearing_range,
    block_minimum_degree,
    cholesky_factor,
    columns,
    dense,
    givens_qr,
    linearize,
    nnz,
    odometry,
    prior,
    square_root_sam,
    total_error,
    wrap,
)

LANDMARKS = [(2.0, 0.5), (3.5, 2.5), (1.5, 4.0), (-0.5, 2.5), (0.5, -1.0), (2.5, 3.5)]
OD_S = [0.02, 0.02, 0.01]
BR_S = [0.05, 0.02]


def step(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 build(seed, steps=12, noise=True, max_range=3.0):
    """Return (factors, true values, initial guess by dead reckoning)."""
    rng = random.Random(seed)
    u = [1.0, 0.0, 2.0 * math.pi / steps]
    truth = {("x", 0): [0.0, 0.0, 0.0]}
    for t in range(1, steps + 1):
        truth[("x", t)] = step(truth[("x", t - 1)], u)
    for j, m in enumerate(LANDMARKS):
        truth[("l", j)] = list(m)
    fs = [prior(("x", 0), [0.0, 0.0, 0.0], [1e-3, 1e-3, 1e-3])]
    guess = {("x", 0): [0.0, 0.0, 0.0]}
    for t in range(1, steps + 1):
        z = [v + (rng.gauss(0, s) if noise else 0.0) for v, s in zip(u, OD_S)]
        fs.append(odometry(("x", t - 1), ("x", t), z, OD_S))
        guess[("x", t)] = step(guess[("x", t - 1)], z)
    seen = set()
    for t in range(steps + 1):
        x = truth[("x", t)]
        for j, m in enumerate(LANDMARKS):
            dx, dy = m[0] - x[0], m[1] - x[1]
            r = math.hypot(dx, dy)
            if r > max_range:
                continue
            z = [r, wrap(math.atan2(dy, dx) - x[2])]
            if noise:
                z = [z[0] + rng.gauss(0, BR_S[0]), wrap(z[1] + rng.gauss(0, BR_S[1]))]
            fs.append(bearing_range(("x", t), ("l", j), z, BR_S))
            if j not in seen:
                g = guess[("x", t)]
                guess[("l", j)] = [g[0] + z[0] * math.cos(g[2] + z[1]), g[1] + z[0] * math.sin(g[2] + z[1])]
                seen.add(j)
    return fs, truth, guess


def dense_lstsq(rows, n):
    """Solve the normal equations A^T A x = A^T b by Gaussian elimination."""
    a, b = dense(rows, n)
    m = [[sum(r[i] * r[j] for r in a) for j in range(n)] + [sum(r[i] * bb for r, bb in zip(a, b))] for i 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 test_noise_free_problem_converges_to_the_truth_with_zero_residual():
    fs, truth, guess = build(1, noise=False)
    theta, _, it = square_root_sam(fs, guess)
    assert it <= 3
    assert total_error(fs, theta) < 1e-18
    for v, x in truth.items():
        assert max(abs(wrap(a - b)) if k == 2 else abs(a - b) for k, (a, b) in enumerate(zip(theta[v], x))) < 1e-9


def test_givens_r_matches_cholesky_r_and_gives_the_least_squares_step():
    fs, _, guess = build(2)
    order = block_minimum_degree(fs)
    _, n = columns(order)
    rows = linearize(fs, guess, order)
    r, count = givens_qr(rows, n)
    assert count > 0
    rc = cholesky_factor(rows, n)
    for i in range(n):
        sign = 1.0 if r[i][i] > 0 else -1.0
        for j in range(n):
            assert abs(sign * r[i].get(j, 0.0) - rc[i][j]) < 1e-8 * max(1.0, abs(rc[i][i]))
    delta = back_substitute(r, n)
    ref = dense_lstsq(rows, n)
    assert max(abs(a - b) for a, b in zip(delta, ref)) < 1e-8


def test_r_has_no_entry_below_the_diagonal():
    fs, _, guess = build(3)
    order = block_minimum_degree(fs)
    _, n = columns(order)
    r, _ = givens_qr(linearize(fs, guess, order), n)
    assert all(k >= c for c, row in r.items() for k in row if k != RHS)


def test_the_ordering_changes_the_fill_but_not_the_solution():
    fs, _, guess = build(4)
    md = block_minimum_degree(fs)
    natural = sorted(md, key=lambda v: (v[0] == "l", v[1]))  # x_0, ..., x_T, then l_0, ...
    landmarks_first = sorted(md, key=lambda v: (v[0] == "x", v[1]))  # l_0, ..., then x_0, ...
    sizes = {}
    sols = []
    for name, order in (("md", md), ("natural", natural), ("landmarks_first", landmarks_first)):
        _, n = columns(order)
        r, _ = givens_qr(linearize(fs, guess, order), n)
        sizes[name] = nnz(r)
        theta, _, _ = square_root_sam(fs, guess, order)
        sols.append(theta)
    # Minimum degree is a heuristic; on this problem it beats both simple orders.
    assert sizes["md"] < sizes["natural"] < sizes["landmarks_first"]
    for t in sols[1:]:
        for v in t:
            assert max(abs(a - b) for a, b in zip(t[v], sols[0][v])) < 1e-8


def test_noisy_solution_has_zero_gradient():
    fs, truth, guess = build(5)
    theta, _, it = square_root_sam(fs, guess)
    assert it < 20
    order = block_minimum_degree(fs)
    _, n = columns(order)
    a, b = dense(linearize(fs, theta, order), n)
    grad = [sum(row[c] * bb for row, bb in zip(a, b)) for c in range(n)]
    assert max(abs(g) for g in grad) < 1e-6
    assert total_error(fs, theta) < total_error(fs, guess)


def test_ordering_is_a_permutation_of_the_variables():
    fs, truth, _ = build(6)
    order = block_minimum_degree(fs)
    assert sorted(order) == sorted(truth)


def test_missing_prior_is_rank_deficient():
    fs, _, guess = build(7)
    fs = fs[1:]
    order = block_minimum_degree(fs)
    _, n = columns(order)
    with pytest.raises(ValueError):
        givens_qr(linearize(fs, guess, order), n)

History

Dellaert (2005) and Dellaert and Kaess (2006) introduced square root SAM. They noted that smoothing over the whole path keeps the information matrix sparse, while filtering makes it dense. They used sparse QR and Cholesky with the COLAMD ordering. The work led to iSAM (2008), the Bayes tree and iSAM2 (2012), and the GTSAM library.

References

  1. 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 linearized least squares problem, its QR and Cholesky factorizations, and the effect of the variable ordering on the fill-in
  2. Frank Dellaert and Michael Kaess, Factor graphs for robot perception, Foundations and Trends in Robotics 6(1-2), 2017, the factor graph view of SLAM, elimination, and the link between the variable order and the sparsity of the square root information matrix
  3. Timothy A. Davis, Direct Methods for Sparse Linear Systems, SIAM, 2006, the chapters on sparse orthogonal methods and on 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.factor_worst
  • a full proof of time.linearize
  • a full proof of time.solve
  • a full proof of time.total_worst
  • a full proof of space.factor
  • a full proof of space.jacobian
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