Algorithm Search⌘K

Algorithmadvanced

Extended information filter

Also called EIF.

The extended Kalman filter written with the information matrix and vector. Readings add to a few entries, but the motion step and the mean need a matrix inverse.

Time
O(n^3) mean · predictionO(k^2) update
Space
O(n^2) extra
Where
k = the number of state entries that one reading depends on; n = the size of the state
Properties
deterministicnot exactonlinerecursive
Origin
Sebastian Thrun, Yufeng Liu, Daphne Koller, Andrew Y. Ng, Zoubin Ghahramani, Hugh Durrant Whyte, 2004

The extended information filter (EIF) is the extended Kalman filter with the belief N(μ,Σ)N(\mu, \Sigma) stored as the information matrix Ω=Σ−1\Omega = \Sigma^{-1} and the information vector ξ=Ωμ\xi = \Omega \mu. It linearizes the same way and gives the same estimate, up to rounding. What changes is the cost: a reading adds a small term to a few entries of Ω\Omega, while the motion step and the recovery of the mean need a matrix inverse. In SLAM, the update of a reading of one landmark is local, but each motion step links all landmarks that the robot has seen, so Ω\Omega fills in. The sparse extended information filter (SEIF) removes some of these links by an approximation to keep Ω\Omega sparse; the EIF on this page is exact up to linearization and keeps all of them.

In plain words

A Kalman filter keeps a best guess and a table that says how unsure it is. The information filter keeps the opposite table: how much it knows. Knowledge from independent readings simply adds up, so a reading changes only the few numbers that it is about, and readings can come in any order. A step of the robot destroys some knowledge, and that is hard to write as a sum, so the motion step must convert the table, which takes time. The best guess is not stored directly either, and getting it back also takes a full computation. The filter knows nothing about a new landmark at the start, which it can store as zero, while a Kalman filter cannot store an infinite doubt.

The problem

The input is the information form (ξ,Ω)(\xi, \Omega) of the belief at time t−1t-1, a control utu_t, and the readings zt1,…,ztkz_t^1, \dots, z_t^k of the step. The motion model is xt=g(ut,xt−1)+wx_t = g(u_t, x_{t-1}) + w with w∼N(0,Rt)w \sim N(0, R_t), and reading ii is zi=hi(xt)+viz^i = h_i(x_t) + v_i with vi∼N(0,Qi)v_i \sim N(0, Q_i). The output is the information form of the Gaussian approximation of the belief at time tt. In online SLAM, the state is the robot pose and the landmarks, as in EKF SLAM.

The algorithm

  1. EIF(ξ, Ω, u_t, z_t)
  2. 1μ ← Ω⁻¹ ξ ▷ recover the mean: a linear solve
  3. 2G ← ∂g/∂x at (u_t, μ)
  4. 3Ω̄ ← (G Ω⁻¹ Gᵀ + R_t)⁻¹
  5. 4μ̄ ← g(u_t, μ)
  6. 5ξ̄ ← Ω̄ μ̄
  7. 6for each reading z^i in z_t do
  8. 7H ← ∂h_i/∂x at μ̄
  9. 8Ω̄ ← Ω̄ + Hᵀ Q_i⁻¹ H ▷ only the entries where H is not zero
  10. 9ξ̄ ← ξ̄ + Hᵀ Q_i⁻¹ (z^i - h_i(μ̄) + H μ̄)
  11. 10return ξ̄, Ω̄

Lines L1 to L5 are the EKF prediction, converted to information form and back. Lines L8 and L9 are the EKF update in information form; the correctness proof derives them. The term zi−hi(μˉ)z^i - h_i(\bar\mu) is the innovation, with the angle wrapped for a bearing. All readings of the step are linearized at the same μˉ\bar\mu, so their order does not matter. The sequential EKF relinearizes after each reading, which differs slightly in the nonlinear case.

Line L8 in SLAM. A reading of landmark jj depends on the pose and on mjm_j only, so HH has k=5k = 5 nonzero columns in the plane, and the update changes a 5 by 5 block of Ω\Omega and 5 entries of ξ\xi. The EKF changes all of Σ\Sigma for the same reading.

Line L3 in SLAM. The motion changes only the pose. Write the pose block of Ω\Omega as Ωxx\Omega_{xx}, the links between the pose and the landmarks as Ωxm\Omega_{xm}, and let the pose move as xt=Gxt−1+wx_t = G x_{t-1} + w with w∼N(0,R)w \sim N(0, R). The step adds the new pose and then removes the old one, which is a Schur complement: the landmark block becomes

Ωˉmm=Ωmm−Ωmx(Ωxx+G⊤R−1G)−1Ωxm.\bar\Omega_{mm} = \Omega_{mm} - \Omega_{mx} (\Omega_{xx} + G^\top R^{-1} G)^{-1} \Omega_{xm}.

The second term is nonzero for every pair of landmarks that are both linked to the old pose. So every landmark seen from the old pose becomes linked to every other one, as the example shows.

Example

A robot moves on a line and sees two landmarks A and B. The state is (x,A,B)(x, A, B), and a reading of a landmark is its offset from the robot, z=m−xz = m - x with the variance 0.040.04. The robot starts at x=0x = 0 with variance 0.010.01, and nothing is known about A and B, so

Ω=(10000000000),ξ=(0,0,0).\Omega = \begin{pmatrix} 100 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{pmatrix}, \qquad \xi = (0, 0, 0).

A Kalman filter cannot start like this, because Σ\Sigma would be infinite.

Two readings. The robot reads A at 2.02.0 and B at 5.05.0. Each reading has H=(−1,1,0)H = (-1, 1, 0) or (−1,0,1)(-1, 0, 1), and lines L8 and L9 add 25 H⊤H25\, H^\top H and 25 H⊤z25\, H^\top z:

Ω=(150−25−25−25250−25025),ξ=(−175,50,125).\Omega = \begin{pmatrix} 150 & -25 & -25 \\ -25 & 25 & 0 \\ -25 & 0 & 25 \end{pmatrix}, \qquad \xi = (-175, 50, 125).

The entry between A and B is 0: the two readings link each landmark to the robot, not to each other. Solving Ωμ=ξ\Omega \mu = \xi gives μ=(0,2,5)\mu = (0, 2, 5) and the covariance has the variances (0.01,0.05,0.05)(0.01, 0.05, 0.05), the same as EKF SLAM when it adds each landmark from the reading.

A motion. The robot moves by u=1u = 1 with the variance 0.010.01. Lines L1 to L5 give

Ωˉ=(60−10−10−1022.5−2.5−10−2.522.5),ξˉ=(−10,22.5,97.5).\bar\Omega = \begin{pmatrix} 60 & -10 & -10 \\ -10 & 22.5 & -2.5 \\ -10 & -2.5 & 22.5 \end{pmatrix}, \qquad \bar\xi = (-10, 22.5, 97.5).

Now A and B are linked by −2.5-2.5. They were both linked to the old pose, and removing the old pose moves the link to them. This is the fill-in that makes the EIF for SLAM dense, and that SEIF limits.

A reading of A. The robot reads A at 0.950.95, a little less than the predicted 2−1=12 - 1 = 1. Lines L8 and L9 change only the entries of xx and A: Ωxx=85\Omega_{xx} = 85, ΩxA=−35\Omega_{xA} = -35, ΩAA=47.5\Omega_{AA} = 47.5, and ξ=(−33.75,46.25,97.5)\xi = (-33.75, 46.25, 97.5). The mean is (1.0056,1.9778,5.0)(1.0056, 1.9778, 5.0) with the standard deviations (0.137,0.180,0.224)(0.137, 0.180, 0.224). B does not move: its covariance with xx and with A is the same, 0.010.01, so a reading of the offset A−xA - x tells nothing about it.

Correctness

The correctness proof shows that with the same linearization points, each step of the EIF gives the information form of the EKF belief: line L3 is the inverse of the predicted covariance, and lines L8 and L9 give Ω−1=(I−KH)Σˉ\Omega^{-1} = (I - KH)\bar\Sigma and Ω−1ξ=μˉ+Kν\Omega^{-1} \xi = \bar\mu + K \nu. For linear models with Gaussian noise the EKF is the Kalman filter, so the EIF is exact. The proof also shows that several readings add up in any order and that a reading changes only the entries of the state that it depends on. The tests compare the EIF with a dense EKF on 12 steps of a planar SLAM run and find agreement within 10−810^{-8}; a linear run with a flat prior matches batch least squares within 10−910^{-9}. For nonlinear models, the EIF has the same linearization error as the EKF and no error bound.

Proof: The EIF is the EKF in information formfull

Setting. The belief at time t−1t-1 is N(μ,Σ)N(\mu, \Sigma) with Σ\Sigma positive definite, stored as Ω=Σ−1\Omega = \Sigma^{-1} and ξ=Ωμ\xi = \Omega \mu. The motion is xt=g(ut,xt−1)+wx_t = g(u_t, x_{t-1}) + w with w∼N(0,R)w \sim N(0, R), and the readings are zi=hi(xt)+viz^i = h_i(x_t) + v_i with vi∼N(0,Qi)v_i \sim N(0, Q_i), QiQ_i positive definite, all noises independent. The EKF linearizes gg at μ\mu with G=∂g/∂xG = \partial g / \partial x, and linearizes each hih_i at the predicted mean μˉ\bar\mu with Hi=∂hi/∂xH_i = \partial h_i / \partial x. We compare the EIF with the EKF that processes all readings of a step in one update at μˉ\bar\mu.

Claim. If GΣG⊤+RG \Sigma G^\top + R is invertible, then after lines L1 to L9 the pair (ξ,Ω)(\xi, \Omega) is the information form of the EKF belief: Ω−1\Omega^{-1} is the EKF covariance and Ω−1ξ\Omega^{-1} \xi is the EKF mean. For linear models with Gaussian noise, the EKF is the Kalman filter, so the EIF gives the exact posterior.

Prediction (lines L1 to L5)

Line L1 computes μ=Ω−1ξ\mu = \Omega^{-1} \xi, the mean of the belief. The EKF prediction is μˉ=g(ut,μ)\bar\mu = g(u_t, \mu) and Σˉ=GΣG⊤+R\bar\Sigma = G \Sigma G^\top + R with Σ=Ω−1\Sigma = \Omega^{-1}. Line L3 sets Ωˉ=Σˉ−1\bar\Omega = \bar\Sigma^{-1}, line L4 sets μˉ\bar\mu, and line L5 sets ξˉ=Ωˉμˉ\bar\xi = \bar\Omega \bar\mu. This is the information form of N(μˉ,Σˉ)N(\bar\mu, \bar\Sigma) by definition.

One reading (lines L7 to L9)

Let Σˉ=Ωˉ−1\bar\Sigma = \bar\Omega^{-1}, let HH and QQ be the Jacobian and the noise of the reading, and let ν=z−h(μˉ)\nu = z - h(\bar\mu) (with the angle wrapped, if any). The EKF computes S=HΣˉH⊤+QS = H \bar\Sigma H^\top + Q, K=ΣˉH⊤S−1K = \bar\Sigma H^\top S^{-1}, μ′=μˉ+Kν\mu' = \bar\mu + K \nu and Σ′=(I−KH)Σˉ\Sigma' = (I - K H) \bar\Sigma. Lines L8 and L9 compute

Ω′=Ωˉ+H⊤Q−1H,ξ′=ξˉ+H⊤Q−1(ν+Hμˉ).\Omega' = \bar\Omega + H^\top Q^{-1} H, \qquad \xi' = \bar\xi + H^\top Q^{-1} (\nu + H \bar\mu).

Ω′\Omega' is positive definite, as the sum of a positive definite and a positive semidefinite matrix.

The gain. Ω′ΣˉH⊤=H⊤+H⊤Q−1HΣˉH⊤=H⊤Q−1(Q+HΣˉH⊤)=H⊤Q−1S\Omega' \bar\Sigma H^\top = H^\top + H^\top Q^{-1} H \bar\Sigma H^\top = H^\top Q^{-1} (Q + H \bar\Sigma H^\top) = H^\top Q^{-1} S. Multiply by Ω′−1\Omega'^{-1} on the left and by S−1S^{-1} on the right: K=ΣˉH⊤S−1=Ω′−1H⊤Q−1K = \bar\Sigma H^\top S^{-1} = \Omega'^{-1} H^\top Q^{-1}.

The covariance. Σˉ=Ω′−1Ω′Σˉ=Ω′−1(Ωˉ+H⊤Q−1H)Σˉ=Ω′−1+Ω′−1H⊤Q−1HΣˉ=Ω′−1+KHΣˉ\bar\Sigma = \Omega'^{-1} \Omega' \bar\Sigma = \Omega'^{-1} (\bar\Omega + H^\top Q^{-1} H) \bar\Sigma = \Omega'^{-1} + \Omega'^{-1} H^\top Q^{-1} H \bar\Sigma = \Omega'^{-1} + K H \bar\Sigma. So Ω′−1=(I−KH)Σˉ=Σ′\Omega'^{-1} = (I - K H) \bar\Sigma = \Sigma'.

The mean. Ω′−1ξ′=Ω′−1(Ωˉ+H⊤Q−1H)μˉ+Ω′−1H⊤Q−1ν=μˉ+Kν=μ′\Omega'^{-1} \xi' = \Omega'^{-1} (\bar\Omega + H^\top Q^{-1} H) \bar\mu + \Omega'^{-1} H^\top Q^{-1} \nu = \bar\mu + K \nu = \mu'.

Several readings

Stack the readings of one step: H=(H1;… ;Hk)H = (H_1; \dots; H_k) and Q=diag(Q1,…,Qk)Q = \mathrm{diag}(Q_1, \dots, Q_k), all linearized at μˉ\bar\mu. Then H⊤Q−1H=∑iHi⊤Qi−1HiH^\top Q^{-1} H = \sum_i H_i^\top Q_i^{-1} H_i and H⊤Q−1(ν+Hμˉ)=∑iHi⊤Qi−1(νi+Hiμˉ)H^\top Q^{-1} (\nu + H \bar\mu) = \sum_i H_i^\top Q_i^{-1} (\nu_i + H_i \bar\mu). So the loop of line L6, which adds the terms one by one, gives the stacked update of the previous section. Addition is commutative, so the order of the readings does not change the result, up to rounding.

Locality

If HH is zero outside a set CC of columns, then H⊤Q−1HH^\top Q^{-1} H is zero outside the rows and columns in CC, and H⊤Q−1(ν+Hμˉ)H^\top Q^{-1} (\nu + H \bar\mu) is zero outside the entries in CC. So the update changes only the block C×CC \times C of Ω\Omega and the entries CC of ξ\xi. The code computes only these entries. For a SLAM reading of one landmark, CC holds the pose and that landmark.

A flat prior

Lines L8 and L9 do not need Σˉ\bar\Sigma. They are the product of the prior density exp⁡(−12x⊤Ωˉx+ξˉ⊤x)\exp(-\tfrac12 x^\top \bar\Omega x + \bar\xi^\top x) and the Gaussian likelihood of the linearized reading, written in the exponent. This product is defined also when Ωˉ\bar\Omega is singular, for example with zero information on a landmark that has not been seen. When the result Ω′\Omega' is positive definite, it is the information form of the posterior of the improper prior. The algebra above does not hold in this case, but the claim about the product does, which is all that the later steps use.

Tests

test_extended_information_filter.py runs the EIF and a dense EKF on 12 steps of a planar SLAM problem with range and bearing readings of two landmarks, and checks that the means agree within 10−810^{-8} and the covariances within 10−910^{-9} at every step. It checks locality on a random Ω\Omega (entries outside the block are bit for bit unchanged), the independence of the order, the round trip between the two forms, the numbers of the example of the page, and that a linear run with a flat prior on two landmarks equals the batch least squares solution within 10−910^{-9}.

Complexity

Let nn be the size of the state and kk the number of state entries that one reading depends on. Costs are in the real RAM model, for the dense matrices of the code.

  • Mean recovery (line L1): O(n3)O(n^3) for a dense solve. With a sparse Ω\Omega it is much cheaper, and iterative methods can reuse the last mean.
  • Prediction (lines L2 to L5): O(n3)O(n^3), two inverses. In SLAM, the motion changes only the pose entries, and the Sherman-Morrison-Woodbury formula brings the step to O(n2)O(n^2) for a dense Ω\Omega.
  • Update (lines L7 to L9): O(k2)O(k^2) per reading, after the O(dn)O(dn) scan of the Jacobian that the code does. In SLAM, kk is a constant, so this is O(1)O(1), against O(n2)O(n^2) for the EKF.
  • Memory: O(n2)O(n^2) for Ω\Omega.

So the EIF trades a cheap update for an expensive prediction and an expensive mean. It pays off when there are many readings per motion step, or when Ω\Omega stays sparse.

Properties

  • Same estimate as the EKF. With the same linearization points, a theorem proved on this page. The rounding differs: inverting Ω\Omega loses precision when Ω\Omega is badly conditioned.
  • Additive, local updates. Information from independent readings adds up. This makes the filter useful for fusing many sensors and for merging the results of several robots, where the shared information must be counted only once.
  • Zero information is allowed. A state that nothing has been measured about has a zero row in Ω\Omega. The covariance form needs an infinite variance for it.
  • Fill-in under motion. In SLAM, the motion step links every pair of landmarks that are linked to the pose. Over time Ω\Omega becomes dense, but most of its entries are small after normalization, which Thrun et al. (2004) observed and the SEIF exploits.
  • The full path is sparse. If the old poses are kept in the state instead of being removed, no fill-in happens: Ω\Omega has a block for each motion and each reading, as in GraphSLAM and other factor graph methods.

Variants and improvements

  • Sparse extended information filter. SEIF keeps the number of landmarks linked to the pose bounded, so that Ω\Omega stays sparse and each step costs constant time, at the cost of an approximation that makes the estimate overconfident.
  • Delayed state filters. Keeping the past poses that have readings gives an exactly sparse information matrix without an approximation. This is the step from the online to the full SLAM problem.
  • The linear information filter. For linear models, lines L2 to L9 use the fixed matrices of the model, and the filter is exact.
  • Distributed estimation. Because updates add, nodes of a sensor network can each sum their own terms and exchange them. Gaussian belief propagation passes such terms along the edges of a graph.

When to use it

Use the EIF when readings are many and cheap to add, and motion steps are rare, or when you need a prior with zero information on some states. Use it as a step towards SEIF or GraphSLAM, which are where the information form pays off for SLAM. For a small dense state with one reading per step, the EKF is simpler and does the same work with fewer inverses.

Pitfalls

  • The mean is not stored. Lines L4, L7 and L9 need the mean. Forgetting to recover it, or using an old value, gives wrong linearization points.
  • A singular matrix. Line L1 and line L3 need Ω\Omega to be invertible. With a flat prior, the filter must first get enough readings to make it so; until then, only updates are possible.
  • Angles. Wrap the bearing innovation zi−hi(μˉ)z^i - h_i(\bar\mu), not ziz^i or hi(μˉ)h_i(\bar\mu) alone, before line L9.
  • Double counting. When two filters exchange information, the terms that both have already used must be subtracted once. Otherwise the result is overconfident.
  • Rounding. Two inverses per step lose precision. Symmetrize Ω\Omega, and prefer a Cholesky solve to an explicit inverse.

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.

extended_information_filter.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/extended-information-filter/. The authors are listed in prov/DYEYTV.jsonl.

"""The extended information filter (EIF), after Thrun, Burgard and Fox (2005), Section 3.5.

The belief N(mu, Sigma) is stored as the information matrix Omega = Sigma^(-1)
and the information vector xi = Omega mu. The models are

  x_t = g(u_t, x_{t-1}) + noise N(0, R_t)
  z   = h(x_t) + noise N(0, Q)

The filter linearizes g at the mean of the last belief and h at the
predicted mean, as the EKF does. With the same linearization points the two
filters give the same belief, up to rounding.

Matrices are lists of rows. The functions return new lists and do not change
their arguments.
"""

import rbm


def to_information(mu, sigma):
    """Return (xi, Omega) of the belief N(mu, Sigma)."""
    omega = rbm.inv(sigma)
    return rbm.matvec(omega, mu), omega


def to_moments(xi, omega):
    """Return (mu, Sigma) of the belief with information (xi, Omega)."""
    sigma = rbm.inv(omega)
    return rbm.matvec(sigma, xi), sigma


def recover_mean(xi, omega):
    """Return mu = Omega^(-1) xi by one linear solve."""
    return rbm.solve(omega, xi)


def predict(xi, omega, u, g, gjac, r):
    """Return (xi_bar, Omega_bar, mu_bar) after the motion: lines L1 to L5.

    g(u, x) is the motion model, gjac(u, x) its Jacobian with respect to x,
    and r the covariance of the motion noise in state coordinates. The step
    needs the mean and the inverse of Omega, so it costs O(n^3).
    """
    mu = recover_mean(xi, omega)  # @line L1
    gm = gjac(u, mu)  # @line L2
    sigma = rbm.inv(omega)
    omega_bar = rbm.inv(rbm.add(rbm.mul(rbm.mul(gm, sigma), rbm.transpose(gm)), r))  # @line L3
    omega_bar = symmetrize(omega_bar)
    mu_bar = g(u, mu)  # @line L4
    xi_bar = rbm.matvec(omega_bar, mu_bar)  # @line L5
    return xi_bar, omega_bar, mu_bar


def update(xi, omega, mu_bar, z, h, hjac, q, residual=None):
    """Return (xi, Omega) after one reading z: lines L7 to L9.

    h(x) is the measurement model and hjac(x) its Jacobian, both evaluated
    at the predicted mean mu_bar. residual(z, zhat) gives z - zhat, for
    example with a wrapped angle; by default it is the plain difference.
    Only the columns where the Jacobian is not zero take part, so a reading
    that depends on k state entries changes only a k by k block of Omega
    and k entries of xi.
    """
    n = len(xi)
    d = len(z)
    hm = hjac(mu_bar)  # @line L7
    cols = [c for c in range(n) if any(hm[a][c] != 0.0 for a in range(d))]
    hs = [[hm[a][c] for c in cols] for a in range(d)]
    qinv = rbm.inv(q)
    zhat = h(mu_bar)
    nu = residual(z, zhat) if residual is not None else rbm.sub(z, zhat)
    hmu = [sum(hs[a][k] * mu_bar[c] for k, c in enumerate(cols)) for a in range(d)]
    target = rbm.add(nu, hmu)  # z - h(mu_bar) + H mu_bar
    hq = rbm.mul(rbm.transpose(hs), qinv)  # k by d
    info = rbm.mul(hq, hs)
    vec = rbm.matvec(hq, target)
    omega = [list(row) for row in omega]
    xi = list(xi)
    for a, ca in enumerate(cols):
        for b, cb in enumerate(cols):
            omega[ca][cb] += info[a][b]  # @line L8
        xi[ca] += vec[a]  # @line L9
    return xi, omega


def eif(xi, omega, u, zs, g, gjac, r, h, hjac, q, residual=None):
    """One step of the EIF: lines L1 to L10.

    zs is a list of readings. h(x, i) and hjac(x, i) are the model of
    reading i and its Jacobian. All readings are linearized at the
    predicted mean, so their order does not matter.
    """
    xi, omega, mu_bar = predict(xi, omega, u, g, gjac, r)
    for i, z in enumerate(zs):  # @line L6
        xi, omega = update(xi, omega, mu_bar, z, lambda x, i=i: h(x, i), lambda x, i=i: hjac(x, i), q, residual)
    return xi, omega  # @line L10


def symmetrize(a):
    """Return (A + A^T) / 2, to remove rounding asymmetry."""
    n = len(a)
    return [[(a[i][j] + a[j][i]) / 2.0 for j in range(n)] for i in range(n)]
rbm.py 482 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.

Conventions (Lynch and Park, Modern Robotics, 2017):
- A matrix is a list of rows. A vector is a flat list.
- hat3(w) is the skew-symmetric matrix [w], so that [w] x = w x x.
- A twist or screw is a 6-vector (omega, v), angular part first.
  hat6(V) is the 4x4 matrix [[[omega], v], [0, 0]].
- A pose T is the 4x4 matrix [[R, p], [0, 1]].
- so3_exp and so3_log use exponential coordinates w = omega_hat * theta,
  with theta = |w| in [0, pi] for so3_log.
- se3_exp and se3_log use 6-vectors (w, v) = S * theta.
- Quaternions are Hamilton, scalar first: q = (w, x, y, z), with i j = k.
- Angles are in radians.

The helper holds no algorithm of a robotics page except the four maps
so3_exp, so3_log, se3_exp and se3_log. The pages so3-logarithm-map and
se3-exponential-map hold their own complete versions with comments.
"""

import math

# Below this angle, the coefficient functions of the exponential and the
# logarithm are evaluated by their Taylor series. The first omitted term
# of each series is of order theta^6 and is below 3e-16 for theta < 1e-2;
# it also multiplies [w] or [w]^2, which are small. Above the threshold,
# the closed forms such as (1 - cos(theta)) / theta^2 lose at most about
# 1e-16 / theta^2 to cancellation, which [w] or [w]^2 brings to 1e-14.
SERIES_THETA = 1e-2

# Above pi - NEAR_PI, so3_log takes the axis from the symmetric part of R
# (which is (R + I) / 2 at theta = pi) and not from the skew part.
NEAR_PI = 1e-2

# A pivot whose magnitude is at most PIVOT_TOL times the largest entry of
# the matrix makes solve, inv and pinv_right raise ValueError.
PIVOT_TOL = 1e-12


# ---------------------------------------------------------------- matrices


def zeros(n, m):
    """Return the n by m zero matrix."""
    return [[0.0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, s):
    """Return s * a for a vector or a matrix a and a number s."""
    if _is_matrix(a):
        return [[s * x for x in row] for row in a]
    return [s * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def mul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x, y):
    """Return the dot product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(x):
    """Return the Euclidean norm of a vector."""
    return math.sqrt(dot(x, x))


def cross(a, b):
    """Return the cross product a x b of two 3-vectors."""
    return [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]


def _max_abs(a):
    return max((abs(x) for row in a for x in row), default=0.0)


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    a is a square matrix. b is a vector or a matrix with one column per
    right-hand side; the result has the same shape as b. Raise ValueError
    if a pivot is at most PIVOT_TOL times the largest entry of a.
    """
    n = len(a)
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    m = [list(map(float, row)) + list(map(float, r)) for row, r in zip(a, rhs)]
    k = len(rhs[0]) if rhs else 0
    tol = PIVOT_TOL * _max_abs(a)
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[piv][c]) <= tol or m[piv][c] == 0.0:
            raise ValueError("matrix is singular to working precision")
        m[c], m[piv] = m[piv], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            if f != 0.0:
                row_r, row_c = m[r], m[c]
                for j in range(c, n + k):
                    row_r[j] -= f * row_c[j]
    x = [[0.0] * k for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(k):
            s = m[r][n + j] - sum(m[r][i] * x[i][j] for i in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def inv(a):
    """Return the inverse of the square matrix a (see solve for errors)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a by elimination."""
    n = len(a)
    m = [list(map(float, row)) for row in a]
    d = 1.0
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[piv][c] == 0.0:
            return 0.0
        if piv != c:
            m[c], m[piv] = m[piv], m[c]
            d = -d
        d *= m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for j in range(c, n):
                m[r][j] -= f * m[c][j]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T.

    a must be symmetric positive definite. Raise ValueError if a diagonal
    entry of the factor is not positive.
    """
    n = len(a)
    low = zeros(n, n)
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
            if i == j:
                if s <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = math.sqrt(s)
            else:
                low[i][j] = s / low[j][j]
    return low


def pinv_right(j):
    """Return the right pseudoinverse J^T (J J^T)^(-1) of a J with full row rank."""
    jt = transpose(j)
    return mul(jt, inv(mul(j, jt)))


# ---------------------------------------------------------------- hat and vee


def hat3(w):
    """Return the 3x3 skew-symmetric matrix [w] of a 3-vector w."""
    return [
        [0.0, -w[2], w[1]],
        [w[2], 0.0, -w[0]],
        [-w[1], w[0], 0.0],
    ]


def vee3(m):
    """Return the 3-vector w of a skew-symmetric matrix m = [w]."""
    return [m[2][1], m[0][2], m[1][0]]


def hat6(v):
    """Return the 4x4 matrix [V] = [[[omega], v], [0, 0]] of V = (omega, v)."""
    w = hat3(v[:3])
    return [
        [w[0][0], w[0][1], w[0][2], v[3]],
        [w[1][0], w[1][1], w[1][2], v[4]],
        [w[2][0], w[2][1], w[2][2], v[5]],
        [0.0, 0.0, 0.0, 0.0],
    ]


def vee6(m):
    """Return the 6-vector (omega, v) of a 4x4 matrix [V]."""
    return [m[2][1], m[0][2], m[1][0], m[0][3], m[1][3], m[2][3]]


# ---------------------------------------------------------------- rotations


def rot_x(a):
    """Return the rotation by a radians about the x axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a):
    """Return the rotation by a radians about the y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a):
    """Return the rotation by a radians about the z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def rpy(roll, pitch, yaw):
    """Return R = Rz(yaw) Ry(pitch) Rx(roll)."""
    return mul(rot_z(yaw), mul(rot_y(pitch), rot_x(roll)))


def so3_exp(w):
    """Return exp([w]) for exponential coordinates w = omega_hat * theta.

    Rodrigues' formula in the form I + A [w] + B [w]^2 with
    A = sin(theta) / theta and B = (1 - cos(theta)) / theta^2.
    """
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
    else:
        a = math.sin(t) / t
        b = (1.0 - math.cos(t)) / (t * t)
    k = hat3(w)
    k2 = mul(k, k)
    return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]


def so3_log(r):
    """Return w = omega_hat * theta with exp([w]) = r and theta in [0, pi].

    theta = atan2(|s|, c), where c = (trace(r) - 1) / 2 = cos(theta) and
    s = vee(r - r^T) / 2 = sin(theta) omega_hat. For theta below
    SERIES_THETA, w = s (1 + theta^2 / 6 + 7 theta^4 / 360). For theta
    above pi - NEAR_PI, the axis comes from the symmetric part
    ((r + r^T) / 2 - c I) / (1 - c) = omega_hat omega_hat^T, and its sign
    from s. At theta = pi both signs are valid; the sign is then chosen so
    that the largest component of the axis is positive.
    """
    c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
    c = max(-1.0, min(1.0, c))
    s = [(r[2][1] - r[1][2]) / 2.0, (r[0][2] - r[2][0]) / 2.0, (r[1][0] - r[0][1]) / 2.0]
    sn = norm(s)
    t = math.atan2(sn, c)
    if t < SERIES_THETA:
        t2 = t * t
        f = 1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0
        return [f * x for x in s]
    if t <= math.pi - NEAR_PI:
        return [t / sn * x for x in s]
    b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
    # b = (1 - c) omega_hat omega_hat^T. Its column k with the largest
    # diagonal entry is (1 - c) omega_k omega_hat, with omega_k^2 >= 1/3.
    k = max(range(3), key=lambda i: b[i][i])
    col = [b[i][k] for i in range(3)]
    axis = [x / norm(col) for x in col]
    if dot(axis, s) < 0.0 or (dot(axis, s) == 0.0 and axis[k] < 0.0):
        axis = [-x for x in axis]
    return [t * x for x in axis]


# ---------------------------------------------------------------- poses


def make_T(r, p):
    """Return the 4x4 pose [[r, p], [0, 1]]."""
    return [
        [r[0][0], r[0][1], r[0][2], p[0]],
        [r[1][0], r[1][1], r[1][2], p[1]],
        [r[2][0], r[2][1], r[2][2], p[2]],
        [0.0, 0.0, 0.0, 1.0],
    ]


def _rp(t):
    return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]


def T_inv(t):
    """Return the inverse [[R^T, -R^T p], [0, 1]] of a pose t."""
    r, p = _rp(t)
    rt = transpose(r)
    return make_T(rt, [-x for x in matvec(rt, p)])


def T_apply(t, x):
    """Return R x + p, the image of the point x under the pose t."""
    r, p = _rp(t)
    return add(matvec(r, x), p)


def se3_exp(xi):
    """Return exp([xi]) for a 6-vector xi = (w, v) = S * theta.

    The rotation is so3_exp(w). The translation is G v with
    G = I + B [w] + C [w]^2, B = (1 - cos(theta)) / theta^2 and
    C = (theta - sin(theta)) / theta^3, theta = |w|. For w = 0 this is a
    translation by v.
    """
    w, v = xi[:3], xi[3:]
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
        c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
    else:
        b = (1.0 - math.cos(t)) / (t * t)
        c = (t - math.sin(t)) / (t * t * t)
    k = hat3(w)
    k2 = mul(k, k)
    g = [[(1.0 if i == j else 0.0) + b * k[i][j] + c * k2[i][j] for j in range(3)] for i in range(3)]
    return make_T(so3_exp(w), matvec(g, v))


def se3_log(t):
    """Return the 6-vector xi = (w, v) with se3_exp(xi) = t and |w| in [0, pi].

    w = so3_log(R) and v = G^(-1) p with
    G^(-1) = I - [w] / 2 + D [w]^2, D = (1 - (theta / 2) cot(theta / 2)) / theta^2.
    """
    r, p = _rp(t)
    w = so3_log(r)
    th = norm(w)
    if th < SERIES_THETA:
        t2 = th * th
        d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
    else:
        half = th / 2.0
        d = (1.0 - half * math.cos(half) / math.sin(half)) / (th * th)
    k = hat3(w)
    k2 = mul(k, k)
    gi = [[(1.0 if i == j else 0.0) - 0.5 * k[i][j] + d * k2[i][j] for j in range(3)] for i in range(3)]
    return w + matvec(gi, p)


def adjoint(t):
    """Return the 6x6 adjoint [[R, 0], [[p] R, R]] of a pose t."""
    r, p = _rp(t)
    pr = mul(hat3(p), r)
    out = zeros(6, 6)
    for i in range(3):
        for j in range(3):
            out[i][j] = r[i][j]
            out[i + 3][j + 3] = r[i][j]
            out[i + 3][j] = pr[i][j]
    return out


# ---------------------------------------------------------------- quaternions


def quat_mul(q, r):
    """Return the Hamilton product q r of quaternions (w, x, y, z)."""
    a1, b1, c1, d1 = q
    a2, b2, c2, d2 = r
    return [
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    ]


def quat_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return [q[0], -q[1], -q[2], -q[3]]


def quat_to_rot(q):
    """Return the rotation matrix of the quaternion q, so that (0, R v) = q (0, v) q*.

    q need not be of unit length; the result is the rotation of q / |q|.
    """
    w, x, y, z = q
    n = w * w + x * x + y * y + z * z
    s = 2.0 / n
    return [
        [1.0 - s * (y * y + z * z), s * (x * y - w * z), s * (x * z + w * y)],
        [s * (x * y + w * z), 1.0 - s * (x * x + z * z), s * (y * z - w * x)],
        [s * (x * z - w * y), s * (y * z + w * x), 1.0 - s * (x * x + y * y)],
    ]


def quat_from_axis_angle(axis, angle):
    """Return (cos(angle / 2), sin(angle / 2) axis / |axis|).

    A zero axis is allowed only with angle 0 (the identity); otherwise
    raise ValueError.
    """
    n = norm(axis)
    if n == 0.0:
        if angle == 0.0:
            return [1.0, 0.0, 0.0, 0.0]
        raise ValueError("zero axis with a nonzero angle")
    s = math.sin(angle / 2.0) / n
    return [math.cos(angle / 2.0), s * axis[0], s * axis[1], s * axis[2]]


# ---------------------------------------------------------------- derivatives


def num_jacobian(f, x, h=1e-6):
    """Return the Jacobian of f at x by central differences with step h.

    f maps a list of n numbers to a list of m numbers; the result is m by n.
    """
    cols = []
    for i in range(len(x)):
        xp = list(x)
        xm = list(x)
        xp[i] += h
        xm[i] -= h
        fp, fm = f(xp), f(xm)
        cols.append([(a - b) / (2.0 * h) for a, b in zip(fp, fm)])
    return transpose(cols)


# ---------------------------------------------------------------- self-test


def self_test():
    """Check the area check values; return True or raise AssertionError."""
    r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
    want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
    w = so3_log(want)
    assert abs(norm(w) - 2.0943951) < 1e-7
    assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
    t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
    want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
    assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
    return True
robest.py 149 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small estimation helpers for the localization and SLAM pages.

Vectors are lists of floats and matrices are lists of rows, as in rbm.py.
The notation follows Thrun, Burgard and Fox, Probabilistic Robotics (2005).

  wrap_angle(a)                       a wrapped to [-pi, pi)
  gauss_sample(rng, mean, cov)        one draw of N(mean, cov), by a Cholesky factor
  gauss_pdf(x, mean, cov)             the density of N(mean, cov) at x
  mahalanobis2(x, mean, cov)          (x - mean)^T cov^(-1) (x - mean)
  low_variance_resample(rng, w)       indices of a systematic (low variance) resample
  logodds(p), prob_from_logodds(l)    l = log(p / (1 - p)) and its inverse
  CHI2[(dof, level)]                  chi-square quantiles for gates, dof 1 to 3

gauss_pdf and mahalanobis2 also take plain numbers: then cov is a variance.
This module holds no filter, no SLAM back end and no planner.
"""

import math

import rbm

CHI2 = {
    (1, 0.95): 3.841,
    (1, 0.99): 6.635,
    (2, 0.95): 5.991,
    (2, 0.99): 9.210,
    (3, 0.95): 7.815,
    (3, 0.99): 11.345,
}

_TWO_PI = 2.0 * math.pi


def wrap_angle(a):
    """Return a + 2 pi k in [-pi, pi), with ((a + pi) mod 2 pi) - pi.

    An angle that is already in [-pi, pi) comes back unchanged, so that
    small angles keep all their digits.
    """
    if -math.pi <= a < math.pi:
        return float(a)
    w = math.fmod(a + math.pi, _TWO_PI)
    if w < 0.0:
        w += _TWO_PI
    w -= math.pi
    if w >= math.pi:  # rounding can give exactly pi
        w -= _TWO_PI
    return w


def _as_vector(x):
    if isinstance(x, (int, float)):
        return [float(x)], True
    return [float(v) for v in x], False


def _as_matrix(cov, scalar):
    if scalar:
        if isinstance(cov, (int, float)):
            return [[float(cov)]]
        return [[float(cov[0][0])]]
    return [[float(v) for v in row] for row in cov]


def gauss_sample(rng, mean, cov):
    """Draw x = mean + L z, with cov = L L^T and z standard normal.

    rng is a random.Random. cov must be symmetric positive definite.
    A number for mean (with a variance for cov) gives a number.
    """
    mu, scalar = _as_vector(mean)
    if scalar:
        var = float(cov) if isinstance(cov, (int, float)) else float(cov[0][0])
        if var < 0.0:
            raise ValueError("negative variance")
        return mu[0] + math.sqrt(var) * rng.gauss(0.0, 1.0)
    L = rbm.cholesky(_as_matrix(cov, False))
    z = [rng.gauss(0.0, 1.0) for _ in mu]
    return [mu[i] + sum(L[i][j] * z[j] for j in range(i + 1)) for i in range(len(mu))]


def mahalanobis2(x, mean, cov):
    """Return the squared Mahalanobis distance (x - mean)^T cov^(-1) (x - mean)."""
    xv, scalar = _as_vector(x)
    mv, _ = _as_vector(mean)
    if len(xv) != len(mv):
        raise ValueError("x and mean differ in size")
    d = [a - b for a, b in zip(xv, mv)]
    S = _as_matrix(cov, scalar)
    if len(d) == 1:
        return d[0] * d[0] / S[0][0]
    y = rbm.solve(S, d)
    return sum(a * b for a, b in zip(d, y))


def gauss_pdf(x, mean, cov):
    """Return the density of N(mean, cov) at x."""
    xv, scalar = _as_vector(x)
    S = _as_matrix(cov, scalar)
    k = len(xv)
    det = S[0][0] if k == 1 else rbm.det(S)
    if det <= 0.0:
        raise ValueError("covariance is not positive definite")
    m2 = mahalanobis2(xv, mean if not scalar else [mean], S)
    return math.exp(-0.5 * m2) / math.sqrt((_TWO_PI ** k) * det)


def low_variance_resample(rng, weights):
    """Return len(weights) indices drawn by the low variance sampler.

    This is systematic resampling (Thrun et al. 2005, Table 4.4): one
    uniform offset r in [0, 1/N), and the N points r + m / N select the
    indices through the cumulative weights. The weights need not sum to 1.
    """
    n = len(weights)
    if n == 0:
        return []
    total = float(sum(weights))
    if total <= 0.0 or any(w < 0.0 for w in weights):
        raise ValueError("weights must be nonnegative with a positive sum")
    r = rng.random() / n
    c = weights[0] / total
    i = 0
    out = []
    for m in range(n):
        u = r + m / n
        while u > c and i < n - 1:
            i += 1
            c += weights[i] / total
        out.append(i)
    return out


def logodds(p):
    """Return log(p / (1 - p)) for p in (0, 1)."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    return math.log(p / (1.0 - p))


def prob_from_logodds(l):
    """Return p = 1 - 1 / (1 + exp(l)), the inverse of logodds, without overflow."""
    if l >= 0.0:
        return 1.0 / (1.0 + math.exp(-l))
    e = math.exp(l)
    return e / (1.0 + e)
test_extended_information_filter.py 233 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/extended-information-filter/. The authors are listed in prov/DYEYTV.jsonl.

import math
import random

import rbm
import robest
from extended_information_filter import eif, predict, recover_mean, to_information, to_moments, update

# ---------------------------------------------------------------- a planar SLAM model with two landmarks

N = 7  # (x, y, theta, m1x, m1y, m2x, m2y)
DT = 1.0


def g(u, x):
    v, w = u
    out = list(x)
    out[0] = x[0] + v * DT * math.cos(x[2])
    out[1] = x[1] + v * DT * math.sin(x[2])
    out[2] = x[2] + w * DT
    return out


def gjac(u, x):
    v, _ = u
    a = rbm.eye(N)
    a[0][2] = -v * DT * math.sin(x[2])
    a[1][2] = v * DT * math.cos(x[2])
    return a


def h(x, i):
    j = 3 + 2 * i
    dx, dy = x[j] - x[0], x[j + 1] - x[1]
    return [math.hypot(dx, dy), math.atan2(dy, dx) - x[2]]


def hjac(x, i):
    j = 3 + 2 * i
    dx, dy = x[j] - x[0], x[j + 1] - x[1]
    q = dx * dx + dy * dy
    s = math.sqrt(q)
    out = rbm.zeros(2, N)
    out[0][0], out[0][1] = -dx / s, -dy / s
    out[0][j], out[0][j + 1] = dx / s, dy / s
    out[1][0], out[1][1], out[1][2] = dy / q, -dx / q, -1.0
    out[1][j], out[1][j + 1] = -dy / q, dx / q
    return out


def residual(z, zhat):
    return [z[0] - zhat[0], robest.wrap_angle(z[1] - zhat[1])]


R = [[0.01 if i == j and i < 2 else (0.002 if i == j == 2 else 0.0) for j in range(N)] for i in range(N)]
Q = [[0.01, 0.0], [0.0, 0.0009]]


def ekf_step(mu, sigma, u, zs):
    """The reference: an EKF that linearizes all readings of a step at the predicted mean."""
    gm = gjac(u, mu)
    sigma = rbm.add(rbm.mul(rbm.mul(gm, sigma), rbm.transpose(gm)), R)
    mu = g(u, mu)
    if not zs:
        return mu, sigma
    hs, nus = [], []
    for i, z in enumerate(zs):
        hs.extend(hjac(mu, i))
        nus.extend(residual(z, h(mu, i)))
    k = len(nus)
    qs = rbm.zeros(k, k)
    for a in range(0, k, 2):
        for b in range(2):
            for c in range(2):
                qs[a + b][a + c] = Q[b][c]
    s = rbm.add(rbm.mul(rbm.mul(hs, sigma), rbm.transpose(hs)), qs)
    gain = rbm.mul(rbm.mul(sigma, rbm.transpose(hs)), rbm.inv(s))
    mu = rbm.add(mu, rbm.matvec(gain, nus))
    sigma = rbm.mul(rbm.sub(rbm.eye(N), rbm.mul(gain, hs)), sigma)
    return mu, sigma


def simulate(rng, steps):
    truth = [0.0, 0.0, 0.0, 3.0, 1.0, 2.0, -2.0]
    data = []
    for _ in range(steps):
        u = (0.5, 0.15)
        truth = g(u, truth)
        truth[0] += rng.gauss(0.0, 0.1)
        truth[1] += rng.gauss(0.0, 0.1)
        zs = [rbm.add(h(truth, i), [rng.gauss(0.0, 0.1), rng.gauss(0.0, 0.03)]) for i in range(2)]
        data.append((u, zs))
    return data


def max_abs_diff(a, b):
    if isinstance(a[0], list):
        return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))
    return max(abs(x - y) for x, y in zip(a, b))


def test_eif_equals_ekf_on_a_nonlinear_slam_run():
    rng = random.Random(1)
    mu = [0.0, 0.0, 0.0, 2.8, 1.2, 2.2, -1.8]
    sigma = [[(0.01 if i < 3 else 0.25) if i == j else 0.0 for j in range(N)] for i in range(N)]
    xi, omega = to_information(mu, sigma)
    for u, zs in simulate(rng, 12):
        mu, sigma = ekf_step(mu, sigma, u, zs)
        xi, omega = eif(xi, omega, u, zs, g, gjac, R, h, hjac, Q, residual)
        mu_e, sigma_e = to_moments(xi, omega)
        assert max_abs_diff(mu, mu_e) < 1e-8
        assert max_abs_diff(sigma, sigma_e) < 1e-9


def test_update_changes_only_the_entries_of_the_pose_and_the_landmark():
    rng = random.Random(2)
    a = [[rng.uniform(-1.0, 1.0) for _ in range(N)] for _ in range(N)]
    omega = rbm.add(rbm.mul(a, rbm.transpose(a)), rbm.scale(rbm.eye(N), 0.5))
    xi = [rng.uniform(-1.0, 1.0) for _ in range(N)]
    mu_bar = recover_mean(xi, omega)
    xi2, omega2 = update(xi, omega, mu_bar, [2.0, 0.3], lambda x: h(x, 1), lambda x: hjac(x, 1), Q, residual)
    touched = {0, 1, 2, 5, 6}
    for r in range(N):
        for c in range(N):
            if r not in touched or c not in touched:
                assert omega2[r][c] == omega[r][c]
        if r not in touched:
            assert xi2[r] == xi[r]
    assert any(omega2[r][c] != omega[r][c] for r in touched for c in touched)


def test_the_order_of_the_readings_does_not_matter():
    mu = [0.1, -0.2, 0.05, 3.0, 1.0, 2.0, -2.0]
    sigma = [[0.2 if i == j else 0.0 for j in range(N)] for i in range(N)]
    xi, omega = to_information(mu, sigma)
    zs = [[3.1, 0.3], [2.9, -0.9]]
    a = update(xi, omega, mu, zs[0], lambda x: h(x, 0), lambda x: hjac(x, 0), Q, residual)
    a = update(*a, mu, zs[1], lambda x: h(x, 1), lambda x: hjac(x, 1), Q, residual)
    b = update(xi, omega, mu, zs[1], lambda x: h(x, 1), lambda x: hjac(x, 1), Q, residual)
    b = update(*b, mu, zs[0], lambda x: h(x, 0), lambda x: hjac(x, 0), Q, residual)
    assert max_abs_diff(a[0], b[0]) < 1e-12
    assert max_abs_diff(a[1], b[1]) < 1e-12


def test_round_trip_between_the_two_forms():
    rng = random.Random(4)
    for _ in range(10):
        a = [[rng.uniform(-1.0, 1.0) for _ in range(4)] for _ in range(4)]
        sigma = rbm.add(rbm.mul(a, rbm.transpose(a)), rbm.scale(rbm.eye(4), 0.1))
        mu = [rng.uniform(-5.0, 5.0) for _ in range(4)]
        mu2, sigma2 = to_moments(*to_information(mu, sigma))
        assert max_abs_diff(mu, mu2) < 1e-9
        assert max_abs_diff(sigma, sigma2) < 1e-9


# ---------------------------------------------------------------- the 1-D example of the page


def line_reading(j):
    """z = m_j - x on a line, with the state (x, A, B)."""
    hm = [[-1.0, 0.0, 0.0]]
    hm[0][j] = 1.0
    return (lambda x: [x[j] - x[0]]), (lambda x: hm)


def test_example_of_the_page():
    q = [[0.04]]
    xi = [0.0, 0.0, 0.0]
    omega = [[100.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]  # nothing is known about A and B
    for j, z in ((1, 2.0), (2, 5.0)):
        xi, omega = update(xi, omega, [0.0, 0.0, 0.0], [z], *line_reading(j), q)
    assert omega == [[150.0, -25.0, -25.0], [-25.0, 25.0, 0.0], [-25.0, 0.0, 25.0]]
    mu, sigma = to_moments(xi, omega)
    assert max_abs_diff(mu, [0.0, 2.0, 5.0]) < 1e-12
    # the same as an EKF that adds each landmark through the inverse model
    assert max_abs_diff(sigma, [[0.01, 0.01, 0.01], [0.01, 0.05, 0.01], [0.01, 0.01, 0.05]]) < 1e-12

    r = [[0.01, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
    xi, omega, mu_bar = predict(xi, omega, 1.0, lambda u, x: [x[0] + u, x[1], x[2]], lambda u, x: rbm.eye(3), r)
    assert max_abs_diff(omega, [[60.0, -10.0, -10.0], [-10.0, 22.5, -2.5], [-10.0, -2.5, 22.5]]) < 1e-9
    assert abs(omega[1][2] + 2.5) < 1e-9  # the motion links A and B
    xi, omega = update(xi, omega, mu_bar, [0.95], *line_reading(1), q)
    mu, sigma = to_moments(xi, omega)
    assert max_abs_diff(mu, [1.0055556, 1.9777778, 5.0]) < 1e-6
    sd = [math.sqrt(sigma[i][i]) for i in range(3)]
    assert max_abs_diff(sd, [0.1374, 0.1795, 0.2236]) < 1e-4


def test_linear_filter_with_a_flat_prior_matches_batch_least_squares():
    """A robot on a line reads two landmarks for 6 steps; the EIF equals the batch solution."""
    rng = random.Random(5)
    q, rv = 0.04, 0.01
    steps = 6
    zs_all, us = [], []
    x, a, b = 0.0, 2.0, 5.0
    for t in range(steps):
        if t > 0:
            u = 0.5
            us.append(u)
            x += u + rng.gauss(0.0, math.sqrt(rv))
        zs_all.append([a - x + rng.gauss(0.0, 0.2), b - x + rng.gauss(0.0, 0.2)])
    # EIF
    xi, omega = [0.0, 0.0, 0.0], [[1e4, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
    mu_bar = [0.0, 0.0, 0.0]
    r = [[rv, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
    for t in range(steps):
        if t > 0:
            xi, omega, mu_bar = predict(xi, omega, us[t - 1], lambda u, s: [s[0] + u, s[1], s[2]], lambda u, s: rbm.eye(3), r)
        for j in (1, 2):
            xi, omega = update(xi, omega, mu_bar, [zs_all[t][j - 1]], *line_reading(j), [[q]])
    mu = recover_mean(xi, omega)
    # batch least squares over (x_0 .. x_{T-1}, A, B)
    n = steps + 2
    big = rbm.zeros(n, n)
    vec = [0.0] * n

    def add_row(coef, val, w):
        for i, ci in coef:
            vec[i] += w * ci * val
            for k, ck in coef:
                big[i][k] += w * ci * ck

    add_row([(0, 1.0)], 0.0, 1e4)
    for t in range(steps):
        if t > 0:
            add_row([(t, 1.0), (t - 1, -1.0)], us[t - 1], 1.0 / rv)
        add_row([(steps, 1.0), (t, -1.0)], zs_all[t][0], 1.0 / q)
        add_row([(steps + 1, 1.0), (t, -1.0)], zs_all[t][1], 1.0 / q)
    full = rbm.solve(big, vec)
    want = [full[steps - 1], full[steps], full[steps + 1]]
    assert max_abs_diff(mu, want) < 1e-9

History

The information form of the Kalman filter is a standard rewriting of the filter in estimation theory, and its additive update suits the fusion of data from many sensors. For SLAM, Thrun, Liu, Koller, Ng, Ghahramani and Durrant-Whyte (2004) studied the extended information filter and observed that the normalized information matrix is close to sparse, with strong links only between nearby landmarks. They made it exactly sparse by an approximation, the SEIF. Thrun, Burgard and Fox (2005) present the EIF in Section 3.5 of Probabilistic Robotics and the information form of SLAM in Chapter 12. Keeping the whole path gives an exactly sparse problem, and this is the basis of the smoothing methods for the full SLAM problem.

References

  1. Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Section 3.5 (the information filter and the extended information filter) and Chapter 12 (the information form of SLAM)
  2. Sebastian Thrun, Yufeng Liu, Daphne Koller, Andrew Y. Ng, Zoubin Ghahramani and Hugh Durrant-Whyte, Simultaneous localization and mapping with sparse extended information filters, International Journal of Robotics Research 23(7-8), 2004, pages 693 to 716, the extended information filter for SLAM and the effect of the motion update on the information matrix

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.mean
  • a full proof of time.prediction
  • a full proof of time.update
  • a full proof of space.extra
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
  • at least three sources
  • a scene preset for the example