# The Kalman filter: from two Gaussians to the error-state filter inside LiDAR-inertial SLAM

> Satyajit Ghana — Head of Engineering @ Inkers Technology
> canonical: https://ai.satyajit.si/articles/kalman-filter
> date: 2026-06-28
> tags: state-estimation, kalman-filter, slam, robotics

I spend a lot of time on odometry and SLAM, and underneath almost all of it is one idea. You
have a noisy sensor and a model of how the thing you track moves, and you want a single best
estimate that also says how much to trust itself. That is the Kalman filter. It is the optimal
recursive estimator for a linear system with Gaussian noise, and every LiDAR-inertial system on
this site ([FAST-LIO2](/articles/fast-lio2-lidar-inertial-odometry),
[FAR-LIO](/articles/far-lio), the [iPhone port](/articles/mobile-slam-iphone)) runs a
descendant of it.

The first version of this page stopped at "and then you linearise". This one goes the rest of
the way. It derives the linear filter, then follows the four nonlinear filters a working
roboticist meets: the EKF, the UKF, the error-state filter that keeps rotations honest, and the
iterated EKF that FAST-LIO uses. It covers how to check that a filter's covariance means
anything, and when to drop filtering for a [factor graph](/articles/gtsam-4-3). Then I wrote
all four in NumPy and ran them on 288 seconds of a real KITTI drive.

<Video
  src="https://ai.satyajit.si/articles/kalman-filter/kalman-film"
  poster="https://media.thesatyajit.com/ai/articles/kalman-filter/kalman-film-poster.jpg?v=7e78331b81ca0110"
  narrated
  captions="/articles/kalman-filter/kalman-film.vtt"
  alt="A narrated, captioned hand-drawn film, 66 seconds, in eleven beats. A blue ellipse is drawn onto cream paper around a single dot, with construction lines and its two axes marked: a belief is a guess plus a shape. An arrow then pushes that ellipse to the right along a motion model and it grows as it travels, shedding specks. Three more predict steps leave a chain of pale ghosts behind a ballooning ellipse. A dotted sensor ray drops from the top of the frame, a red dot lands, and a tall narrow red ellipse blooms around it, overlapping the blue one. A small, densely hatched blue ellipse appears in the overlap; the two input ellipses fade and slide onto its centre, where the small one is visibly inside both of them. An ink blot opens onto a chalk-on-navy blueprint: two broad bell curves, pale blue and red, and between them a tall narrow white curve whose peak clears a dashed rule drawn above both. Back on paper, a bead slides along a rail between a blue ellipse at one end and a red dot at the other. With the bead at the red end the estimate jumps onto every scattered red measurement; with it at the blue end the estimate sails on in a straight line past them; settled in between, it follows a smooth path near the measurements without chasing them. A left-to-right sweep then shows a filter running: a faint true curve, red measurements, and a blue uncertainty band that widens between them and pinches at each one, sawtoothing across the frame. It closes on the hand-lettered words 'predict / then update'."
  caption="The loop as geometry, in 66 seconds. Press play: it is narrated and captioned. Every frame is drawn by JavaScript on a 2D canvas at 12fps and voiced with Kokoro-82M on CPU, a drawn explanation and not a recording. The scatter, the gain lever and the sizes of the ellipses are illustrative and measure nothing. The small ellipse in the update shot is the real normalised product of the two on screen, so when all three are slid onto one centre it lands inside both; that containment is the covariance inequality, and exact. The sawtooth band at the end is a real scalar filter run, its width the actual square root of P. The arithmetic you can check is below. (Drawn with the vendored hand-drawn-canvas-animation skill, MIT, Alexey Fateev.)"
/>

## Two sources of information

You are tracking a state $\mathbf{x}$, say the position and velocity of something. You have
two sources:

1. A **process model**: how the state evolves on its own. For constant velocity,
   $p_{t} = p_{t-1} + v\,\Delta t$. You can *predict* forward, but the prediction drifts and
   accumulates uncertainty.
2. A **measurement model**: a sensor that observes some function of the state, noisily. A
   position sensor gives $z = p + \text{noise}$.

Neither is enough alone. The prediction drifts and the sensor jitters. The Kalman filter
combines them, and the key fact is that **combining two Gaussian estimates yields a third
Gaussian that is sharper than either input**.

<KalmanFuse />

That is the whole update step. If the prediction is $\mathcal{N}(\mu_1, \sigma_1^2)$ and the
measurement is $\mathcal{N}(\mu_2, \sigma_2^2)$, their normalised product has

$$
\mu = \mu_1 + K(\mu_2 - \mu_1), \qquad \sigma^2 = (1-K)\,\sigma_1^2,
\qquad K = \frac{\sigma_1^2}{\sigma_1^2 + \sigma_2^2}.
$$

$K$ is the **Kalman gain**: the fraction of the way you move from the prediction toward the
measurement, set by which one is more certain. Trust the sensor ($\sigma_2 \to 0$) and
$K \to 1$; trust the prediction ($\sigma_1 \to 0$) and $K \to 0$. The rest of this page is that
formula generalised to vectors, then bent to fit the parts of the world that are not linear.

## Deriving the filter properly

The scalar picture is a good intuition and a weak derivation. Here is the one I actually
trust, because every later filter on this page is a variation of it.

### The model

The state at step $k$ is a vector $\mathbf{x}_k$. It evolves linearly with additive Gaussian
noise, and a sensor sees a linear function of it:

$$
\mathbf{x}_k = \mathbf{F}\mathbf{x}_{k-1} + \mathbf{B}\mathbf{u}_k + \mathbf{w}_k,
\quad \mathbf{w}_k\sim\mathcal{N}(0,\mathbf{Q});
\qquad
\mathbf{z}_k = \mathbf{H}\mathbf{x}_k + \mathbf{v}_k, \quad \mathbf{v}_k\sim\mathcal{N}(0,\mathbf{R}).
$$

$\mathbf{F}$ is the state transition, $\mathbf{B}\mathbf{u}$ a known input (an IMU reading, a
motor command), $\mathbf{H}$ maps state to measurement, $\mathbf{Q}$ is process noise (how much
the model is wrong per step) and $\mathbf{R}$ is measurement noise. The noises are white,
independent of each other and of the initial state $\mathbf{x}_0 \sim \mathcal{N}(\hat{\mathbf{x}}_0, \mathbf{P}_0)$.

### Predict: push a Gaussian through a linear map

If $\mathbf{x}_{k-1} \sim \mathcal{N}(\hat{\mathbf{x}}, \mathbf{P})$, then
$\mathbf{F}\mathbf{x}_{k-1}$ is Gaussian with mean $\mathbf{F}\hat{\mathbf{x}}$ and covariance
$\mathbb{E}[\mathbf{F}\mathbf{e}\mathbf{e}^{\top}\mathbf{F}^{\top}] = \mathbf{F}\mathbf{P}\mathbf{F}^{\top}$,
where $\mathbf{e}$ is the error. Adding independent noise adds covariances. So:

$$
\hat{\mathbf{x}}^- = \mathbf{F}\hat{\mathbf{x}} + \mathbf{B}\mathbf{u}, \qquad
\mathbf{P}^- = \mathbf{F}\mathbf{P}\mathbf{F}^{\!\top} + \mathbf{Q}.
$$

Nothing is approximated. A Gaussian stays Gaussian under a linear map, and these two lines are
its exact mean and covariance. Every nonlinear filter below breaks exactly this step and
differs only in how it patches it.

### Update: condition a joint Gaussian

Before the measurement arrives, state and measurement are jointly Gaussian:

$$
\begin{bmatrix}\mathbf{x}\\ \mathbf{z}\end{bmatrix} \sim
\mathcal{N}\!\left(
\begin{bmatrix}\hat{\mathbf{x}}^-\\ \mathbf{H}\hat{\mathbf{x}}^-\end{bmatrix},
\begin{bmatrix}\mathbf{P}^- & \mathbf{P}^-\mathbf{H}^{\top}\\ \mathbf{H}\mathbf{P}^- & \mathbf{H}\mathbf{P}^-\mathbf{H}^{\top}+\mathbf{R}\end{bmatrix}
\right).
$$

The off-diagonal block is $\mathrm{Cov}(\mathbf{x}, \mathbf{H}\mathbf{x}+\mathbf{v}) = \mathbf{P}^-\mathbf{H}^{\top}$.
Conditioning a joint Gaussian on one block is a standard identity (complete the square in the
exponent): for $\begin{bmatrix}\mathbf{a}\\ \mathbf{b}\end{bmatrix}$ with blocks
$\boldsymbol{\Sigma}_{aa}, \boldsymbol{\Sigma}_{ab}, \boldsymbol{\Sigma}_{bb}$,

$$
\mathbf{a}\mid\mathbf{b} \sim \mathcal{N}\big(\boldsymbol{\mu}_a + \boldsymbol{\Sigma}_{ab}\boldsymbol{\Sigma}_{bb}^{-1}(\mathbf{b}-\boldsymbol{\mu}_b),\;
\boldsymbol{\Sigma}_{aa} - \boldsymbol{\Sigma}_{ab}\boldsymbol{\Sigma}_{bb}^{-1}\boldsymbol{\Sigma}_{ba}\big).
$$

Read the filter straight off it. Name the pieces:

$$
\mathbf{y} = \mathbf{z} - \mathbf{H}\hat{\mathbf{x}}^-
\;(\text{innovation}), \qquad
\mathbf{S} = \mathbf{H}\mathbf{P}^-\mathbf{H}^{\!\top} + \mathbf{R}
\;(\text{its covariance}), \qquad
\mathbf{K} = \mathbf{P}^-\mathbf{H}^{\!\top}\mathbf{S}^{-1},
$$
$$
\hat{\mathbf{x}} = \hat{\mathbf{x}}^- + \mathbf{K}\mathbf{y}, \qquad
\mathbf{P} = (\mathbf{I} - \mathbf{K}\mathbf{H})\mathbf{P}^-.
$$

Each consequence below gets used later.

**The posterior is exact.** For a linear-Gaussian system the filter's $\hat{\mathbf{x}}$ and
$\mathbf{P}$ are the true conditional mean and covariance given every measurement so far. That
is why it is "optimal": no estimator, linear or not, has a lower mean squared error here.

**The update is a least-squares problem.** The same posterior mean minimises

$$
J(\mathbf{x}) = \lVert \mathbf{x} - \hat{\mathbf{x}}^- \rVert^2_{\mathbf{P}^{-}} + \lVert \mathbf{z} - \mathbf{H}\mathbf{x} \rVert^2_{\mathbf{R}},
\qquad \lVert \mathbf{e}\rVert^2_{\boldsymbol{\Sigma}} = \mathbf{e}^{\top}\boldsymbol{\Sigma}^{-1}\mathbf{e}.
$$

Set the gradient to zero and you get
$\hat{\mathbf{x}} = \hat{\mathbf{x}}^- + (\mathbf{P}^{-\,-1} + \mathbf{H}^{\top}\mathbf{R}^{-1}\mathbf{H})^{-1}\mathbf{H}^{\top}\mathbf{R}^{-1}\mathbf{y}$,
which equals the gain form above by the matrix inversion lemma. This is the maximum a
posteriori (MAP) view: a prior factor and a measurement factor, solved jointly. The iterated EKF
and the factor graph are both this cost with the linearity assumption removed.

**The gain has two forms with different costs.** $\mathbf{P}^-\mathbf{H}^{\top}\mathbf{S}^{-1}$
inverts an $m \times m$ matrix ($m$ measurements). The information form
$(\mathbf{P}^{-\,-1} + \mathbf{H}^{\top}\mathbf{R}^{-1}\mathbf{H})^{-1}\mathbf{H}^{\top}\mathbf{R}^{-1}$
inverts an $n \times n$ one ($n$ states). With 18 states and a few thousand LiDAR residuals per
scan, FAST-LIO uses the second, and that rewrite is most of its speed.

<Diagram caption="The Kalman loop: predict pushes the estimate and its covariance forward through the motion model (uncertainty grows by Q); update pulls it back toward the measurement by the gain K (uncertainty shrinks). The two steps alternate for every timestep.">
  <svg viewBox="0 0 620 170" role="img" aria-label="The predict-update cycle: predict grows covariance via the motion model, update shrinks it via the measurement and Kalman gain." style={{ width: "100%", height: "auto" }}>
    <rect x="40" y="56" width="170" height="58" rx="10" fill="oklch(0.72 0.13 60)" opacity="0.25" stroke="var(--border)" />
    <text x="125" y="80" textAnchor="middle" fontFamily="monospace" fontSize="12" fill="var(--foreground)">predict</text>
    <text x="125" y="98" textAnchor="middle" fontFamily="monospace" fontSize="9" fill="var(--muted-foreground)">x̂=Fx · P̂=FPFᵀ+Q</text>
    <rect x="410" y="56" width="170" height="58" rx="10" fill="oklch(0.72 0.13 195)" opacity="0.25" stroke="var(--border)" />
    <text x="495" y="80" textAnchor="middle" fontFamily="monospace" fontSize="12" fill="var(--foreground)">update</text>
    <text x="495" y="98" textAnchor="middle" fontFamily="monospace" fontSize="9" fill="var(--muted-foreground)">x=x̂+K(z−Hx̂)</text>
    {/* arrows */}
    <path d="M 210 70 q 100 -34 200 0" fill="none" stroke="var(--muted-foreground)" strokeWidth="1.3" markerEnd="url(#ka)" />
    <text x="310" y="36" textAnchor="middle" fontFamily="monospace" fontSize="9" fill="var(--muted-foreground)">prior x̂, P̂</text>
    <path d="M 410 100 q -100 34 -200 0" fill="none" stroke="var(--muted-foreground)" strokeWidth="1.3" markerEnd="url(#ka)" />
    <text x="310" y="146" textAnchor="middle" fontFamily="monospace" fontSize="9" fill="var(--muted-foreground)">posterior x, P → next step</text>
    <text x="495" y="34" textAnchor="middle" fontFamily="monospace" fontSize="9" fill="var(--muted-foreground)">measurement z</text>
    <line x1="495" y1="38" x2="495" y2="54" stroke="var(--muted-foreground)" strokeWidth="1.3" markerEnd="url(#ka)" />
    <defs><marker id="ka" markerWidth="7" markerHeight="7" refX="6" refY="3.5" orient="auto"><path d="M0,0 L7,3.5 L0,7 Z" fill="var(--muted-foreground)" /></marker></defs>
  </svg>
</Diagram>

Watch it run on a constant-velocity tracker. The state is $[\text{position}, \text{velocity}]$,
the sensor sees only position, and the filter has to infer velocity and smooth the noise. Drag
$R$ and $Q$ to feel the trade-off the gain encodes:

<KalmanTrack />

## In code

The whole thing is a few lines of linear algebra. Here is the constant-velocity tracker above,
in NumPy, runnable as-is:

```python
import numpy as np

dt = 1.0
F = np.array([[1, dt],      # constant-velocity transition
              [0, 1]])
H = np.array([[1.0, 0.0]])  # observe position only
Q = 0.5 * np.array([[dt**3/3, dt**2/2],   # process noise (drift)
                    [dt**2/2, dt]])
R = np.array([[49.0]])      # measurement noise (sensor variance)

x = np.array([[0.0], [0.0]])      # initial state
P = np.eye(2) * 50.0              # initial uncertainty

def step(x, P, z):
    # predict
    x = F @ x
    P = F @ P @ F.T + Q
    # update
    y = z - H @ x                 # innovation
    S = H @ P @ H.T + R           # innovation covariance
    K = P @ H.T @ np.linalg.inv(S)   # Kalman gain
    x = x + K @ y
    P = (np.eye(2) - K @ H) @ P
    return x, P

for z in measurements:            # stream of noisy position readings
    x, P = step(x, P, np.array([[z]]))
    # x[0] is the smoothed position estimate, P[0,0] its variance
```

That `Q` is not arbitrary. For a state of position and velocity driven by white acceleration
of intensity $q$, integrating the noise over one step gives exactly
$q\begin{bmatrix}\Delta t^3/3 & \Delta t^2/2\\ \Delta t^2/2 & \Delta t\end{bmatrix}$.
It is the most common $\mathbf{Q}$ in tracking, and the off-diagonal terms matter: drop them
and the filter thinks position and velocity errors are unrelated, which they are not.

<Callout type="note">
For numerical robustness, use the **Joseph form** of the covariance update,
$\mathbf{P} = (\mathbf{I}-\mathbf{KH})\mathbf{P}^-(\mathbf{I}-\mathbf{KH})^{\!\top} +
\mathbf{KRK}^{\!\top}$. It is a sum of two symmetric positive semi-definite terms, so it stays
valid under rounding and even under a slightly wrong $\mathbf{K}$. The compact
$(\mathbf{I}-\mathbf{KH})\mathbf{P}^-$ is only correct for the optimal gain and can drift
non-symmetric. The EKF, ESKF and IEKF in my experiments below all use Joseph; the UKF uses the
standard $\mathbf{P} - \mathbf{K}\mathbf{S}\mathbf{K}^{\top}$, symmetrised.
</Callout>

## Is the filter telling the truth?

A filter returns an estimate and a covariance that claims how wrong the estimate
is. The estimate gets all the attention. The covariance is the part that breaks silently, and
downstream code (a gating test, a loop-closure check, a planner) trusts it.

### NEES: errors measured in the filter's own units

When you know the truth (in simulation, or with a reference system), take the error
$\mathbf{e}_k = \mathbf{x}_k - \hat{\mathbf{x}}_k$ and weight it by the claimed covariance:

$$
\epsilon_k = \mathbf{e}_k^{\top}\mathbf{P}_k^{-1}\mathbf{e}_k .
$$

This is the **normalised estimation error squared**. If the filter is right,
$\mathbf{e}_k \sim \mathcal{N}(0, \mathbf{P}_k)$, so $\epsilon_k$ is a sum of $n$ squared
standard normals: chi-square with $n$ degrees of freedom, mean $n$. A filter whose NEES averages
well above $n$ is **overconfident**: its errors are bigger than it admits. Below $n$, it is
**underconfident** and is throwing information away.

One run gives a noisy, time-correlated NEES, and putting a chi-square band around it with
"degrees of freedom = number of steps" is a common mistake that makes the band far too tight.
The standard test (Bar-Shalom, Li and Kirubarajan, *Estimation with Applications to Tracking
and Navigation*) runs $N$ independent Monte Carlo trials and averages per step:

$$
\bar{\epsilon}_k = \frac{1}{N}\sum_{i=1}^{N}\epsilon_k^{(i)}, \qquad
N\bar{\epsilon}_k \sim \chi^2_{Nn}.
$$

For $N = 20$ runs of a 9-dimensional error, the two-sided 95% band on $\bar{\epsilon}_k$ is
$[\chi^2_{180}(0.025)/20,\ \chi^2_{180}(0.975)/20] = [7.24,\ 10.95]$ (scipy's quantiles). For
16 runs of a 2-D position it is $[1.143,\ 3.093]$.

### NIS: the test you can run without the truth

On a real robot you rarely have the truth. You always have the innovations. If the filter is
consistent, $\mathbf{y}_k \sim \mathcal{N}(0, \mathbf{S}_k)$, so the **normalised innovation
squared** $\mathbf{y}_k^{\top}\mathbf{S}_k^{-1}\mathbf{y}_k$ is chi-square with $m$ degrees of
freedom. NIS is what you log in production. It cannot see everything (an error in a direction
the sensor never observes does not show in the innovation), but a NIS that sits at three
times its mean is a filter in trouble, and you can see it live.

Here is a filter you can break. The truth is drawn from the filter's own model (white
acceleration of intensity $0.04$, position noise of variance $4$), and 16 seeded runs feed the
two strips. The plot shows run one.

<FilterTuner />

In that widget's code, matched settings average a NEES of 2.07 over 16 runs: two degrees of
freedom, as the chi-square says. Cut $Q$ a hundredfold and the average NEES goes to 47.6 while
the position error goes from 1.78 to 4.81 units. That is what an overconfident filter looks like
in practice: it lags every turn, and its ellipses stay small enough to exclude the truth. Make
$R$ ten times too small and NEES goes to 17.4 with the error barely changed, because a filter
that over-trusts its sensor chases noise but stays near the data. Inflating $Q$ is the subtle
one: NEES stays inside the band (1.78) because the filter collapses into following the fixes,
and only NIS (1.32, under its band) gives it away.

## Tuning Q and R without guessing

Two knobs do all the tuning. `R` says how noisy the sensor is; `Q` says how wrong the model is
per step. In practice:

- **Start `R` from the sensor.** A datasheet, or better, a recording with the sensor still:
  the sample covariance of a static log is $\mathbf{R}$. Check whether the noise is white (its
  autocorrelation dies after one lag); GPS position noise is not, and a filter that assumes it
  is will be overconfident.
- **Derive `Q` from physics, then scale it.** For an IMU, the datasheet's noise densities (or
  an Allan-variance plot) give accelerometer and gyro white noise and bias random walk. Solà's
  notes, cited below, give the discrete form: velocity noise $\sigma_a^2\Delta t^2$ and angle
  noise $\sigma_\omega^2\Delta t^2$ per step, bias noise $\sigma_{b}^2\Delta t$. Then remember
  that $\mathbf{Q}$ is also your budget for everything the model gets wrong: vibration,
  unmodelled scale factors, timing jitter. It is almost always larger than the datasheet.
- **Read NIS on a real log, NEES where you have a reference.** Too high: raise $\mathbf{Q}$ (or
  $\mathbf{R}$, if the innovations are large right at the start of an update stream).
  Too low: lower them.
- **Err toward too much `Q`.** The two mistakes are not symmetric. Too little process noise
  gives a filter that ignores data it should trust and reports confidence it does not have; it
  can diverge and never recover. Too much costs some accuracy.

I ran that last point on the real drive described below, scaling the whole of $\mathbf{Q}$ in
the error-state filter. At the tuned value the averaged NEES is 7.67 and the 3-D position error
1.315 m. Divide $\mathbf{Q}$ by 100 and NEES jumps to 164.34 while the error almost doubles to
2.358 m. Multiply it by 100 and NEES drops to 4.63 (underconfident) and the error rises to
1.763 m. Both directions cost accuracy. Only one of them lies about it.

## When the world isn't linear: the EKF

The linear filter's predict step was exact because a Gaussian through a linear map stays
Gaussian. Robotics is full of maps that are not linear: rotations, projections, ranges,
anything with a sine in it. Write the model as

$$
\mathbf{x}_k = f(\mathbf{x}_{k-1}, \mathbf{u}_k) + \mathbf{w}_k, \qquad \mathbf{z}_k = h(\mathbf{x}_k) + \mathbf{v}_k .
$$

The **extended Kalman filter** replaces each function by its first-order Taylor expansion at
the current estimate. Propagate the mean through the real $f$, and the covariance through the
Jacobian:

$$
\hat{\mathbf{x}}^- = f(\hat{\mathbf{x}}, \mathbf{u}), \quad
\mathbf{F} = \left.\frac{\partial f}{\partial \mathbf{x}}\right|_{\hat{\mathbf{x}}}, \quad
\mathbf{P}^- = \mathbf{F}\mathbf{P}\mathbf{F}^{\top} + \mathbf{Q};
\qquad
\mathbf{y} = \mathbf{z} - h(\hat{\mathbf{x}}^-), \quad
\mathbf{H} = \left.\frac{\partial h}{\partial \mathbf{x}}\right|_{\hat{\mathbf{x}}^-}.
$$

The update equations are then the linear ones. What goes wrong has names.

**Linearisation error.** The Jacobian is the slope at one point. When the uncertainty is wide
compared with the scale over which $f$ or $h$ curves, the tangent is a bad model of the
function across the region the state could be in. The mean is biased (a Gaussian pushed
through a curve has a shifted mean, and the EKF ignores the shift) and the covariance is
usually too small.

**Linearising at the wrong point.** The Jacobian is evaluated at the estimate, which is wrong
by exactly the error you are trying to correct. A good estimate gives a good Jacobian; a bad
one gives a bad Jacobian, which gives a worse estimate. This is the EKF's characteristic
failure: fine while it is fine, and then it diverges from a bad start and does not come back.
The covariance has no idea, because the Jacobian that produced it assumed the estimate was
right. EKF-SLAM's famous inconsistency (the filter growing confident about headings it cannot
observe) is this effect. Huang, Mourikis and Roumeliotis traced it to Jacobians evaluated at
changing estimates; their fix, the first-estimates Jacobian, is now standard in
visual-inertial filters.

## The unscented filter: push points, not Jacobians

The **unscented Kalman filter** (Julier and Uhlmann) skips the Jacobians. It picks
$2n+1$ **sigma points** that have exactly the estimate's mean and covariance, pushes each one
through the real nonlinear function, and fits a Gaussian to where they land:

$$
\boldsymbol{\chi}_0 = \hat{\mathbf{x}}, \quad
\boldsymbol{\chi}_{\pm i} = \hat{\mathbf{x}} \pm \big[\sqrt{(n+\lambda)\mathbf{P}}\big]_i, \qquad
\hat{\mathbf{x}}^- = \sum_i w_i\, f(\boldsymbol{\chi}_i), \quad
\mathbf{P}^- = \sum_i w_i\,(f(\boldsymbol{\chi}_i)-\hat{\mathbf{x}}^-)(\cdots)^{\top} + \mathbf{Q}.
$$

The update builds the innovation covariance and the state-measurement cross-covariance the
same way, then uses the usual gain, $\mathbf{K} = \mathbf{P}_{xz}\mathbf{S}^{-1}$. The sigma
points sample the function across the spread of the uncertainty instead of at one point, so
the transformed mean is right to second order and the covariance accounts for curvature the EKF
cannot see. No Jacobians to derive, which is a real saving when $h$ is ugly.

The cost is $2n+1$ evaluations of $f$ and $h$ per step and a Cholesky factorisation of
$\mathbf{P}$. In my NumPy runs below, with 15 error states (31 sigma points) at 100 Hz, the UKF
took 10.2 s per 288 s run against 1.3 s for the error-state filter. For a rotation the naive
version also breaks: you cannot average quaternions by adding them. My UKF draws its sigma
points in the tangent space of the rotation and maps them back with the exponential map, the
UKF-M construction of Brossard, Barrau and Bonnabel
([arXiv:2002.00878](https://arxiv.org/abs/2002.00878)).

## Rotations don't add: the error-state filter

Every robot that moves in 3-D has an orientation in its state, and orientation is where the
textbook EKF goes wrong in code. A rotation has three degrees of freedom, but every
representation of it is either singular somewhere (Euler angles) or redundant (a unit quaternion
is four numbers with one constraint; a rotation matrix is nine with six). The group of
rotations, $SO(3)$, is a curved manifold, not a vector space. "Add a correction" has no meaning
on it.

The classic quaternion EKF puts the four numbers $q_w, q_x, q_y, q_z$ in the state and treats
them as free. Its update adds $\mathbf{K}\mathbf{y}$ to them, which leaves the unit sphere,
so the code renormalises afterwards. Its covariance is $4 \times 4$ for three degrees of
freedom, so it is singular in the ideal case and wrong in the radial direction in practice.
Nothing in the math knows about the constraint; it is patched on after each step.

<Figure
  src="https://media.thesatyajit.com/ai/articles/kalman-filter/fig1.png?v=1219d2b8fe53ecec"
  alt="Two diagrams of a unit circle standing for the unit-quaternion sphere S3. Left: a quaternion q drawn as a radius, and a red tangent line at the identity carrying a vector theta whose length matches the blue arc to q; labelled q = Exp(theta), theta = Log(q). Right: two quaternions p and q on the circle, with the tangent line at p carrying theta; labelled q = p oplus theta, theta = q ominus p."
  caption="The quaternion sphere drawn as a circle. Left: Exp and Log map a vector in the 3-D tangent space to a rotation and back. Right: the ⊕ and ⊖ operators that replace + and − on a manifold; the error-state filter lives in the tangent line at its current estimate (Solà, Quaternion kinematics for the error-state Kalman filter, Figure 11)."
/>

The **error-state Kalman filter** (ESKF) makes the constraint structural. It keeps a pair:

- a **nominal state** $\bar{\mathbf{x}}$ that lives on the manifold: position, velocity, a
  rotation $\mathbf{R} \in SO(3)$, and IMU biases. It is propagated with the full nonlinear
  IMU equations and never touched by the filter's linear algebra.
- an **error state** $\delta\mathbf{x}$ in the tangent space, a plain 15-vector
  $[\delta\mathbf{p}, \delta\mathbf{v}, \delta\boldsymbol{\theta}, \delta\mathbf{b}_a, \delta\mathbf{b}_\omega]$,
  with a 15 × 15 covariance. The true state is $\mathbf{x} = \bar{\mathbf{x}} \boxplus \delta\mathbf{x}$,
  and for the rotation that means $\mathbf{R}_{\text{true}} = \mathbf{R}\,\mathrm{Exp}(\delta\boldsymbol{\theta})$.

This works better than it sounds. The error is always small (it is reset to zero
after every update), so its dynamics are close to linear and the first-order Jacobians are
good. The rotation error has exactly three numbers, so the covariance is minimal and
non-singular. And the error dynamics are slow, so the heavy covariance step can run at a
lower rate than the IMU if needed. This is the filter Solà's notes
([arXiv:1711.02508](https://arxiv.org/abs/1711.02508)) derive in full, and they are the best
single reference on the subject I know.

<Figure
  src="https://media.thesatyajit.com/ai/articles/kalman-filter/fig2.png?v=b8a81ec923f6d220"
  alt="A curved blue surface labelled M with a point X on it, and a flat red grid tangent to the surface at X labelled T_X M. A red ellipse is drawn in the tangent plane around X and a thick blue closed curve on the surface shows where that ellipse lands when wrapped onto the manifold."
  caption="Uncertainty on a manifold is a Gaussian in the tangent space at the estimate (red), wrapped onto the manifold by ⊕ (blue). The ESKF's 15 × 15 covariance is exactly this red ellipse (Solà, Deray and Atchuthan, A micro Lie theory for state estimation in robotics, Figure 10)."
/>

### The ESKF in equations

With accelerometer reading $\mathbf{a}_m$ (specific force in the body frame), gyro reading
$\boldsymbol{\omega}_m$, and gravity $\mathbf{g}$, the nominal state propagates as

$$
\mathbf{p} \leftarrow \mathbf{p} + \mathbf{v}\Delta t + \tfrac12\big(\mathbf{R}(\mathbf{a}_m-\mathbf{b}_a)+\mathbf{g}\big)\Delta t^2, \quad
\mathbf{v} \leftarrow \mathbf{v} + \big(\mathbf{R}(\mathbf{a}_m-\mathbf{b}_a)+\mathbf{g}\big)\Delta t, \quad
\mathbf{R} \leftarrow \mathbf{R}\,\mathrm{Exp}\big((\boldsymbol{\omega}_m-\mathbf{b}_\omega)\Delta t\big).
$$

The error state propagates through a 15 × 15 Jacobian whose only non-trivial blocks are

$$
\frac{\partial\delta\mathbf{v}}{\partial\delta\boldsymbol{\theta}} = -\mathbf{R}\,[\mathbf{a}_m-\mathbf{b}_a]_\times\Delta t, \quad
\frac{\partial\delta\mathbf{v}}{\partial\delta\mathbf{b}_a} = -\mathbf{R}\,\Delta t, \quad
\frac{\partial\delta\boldsymbol{\theta}}{\partial\delta\boldsymbol{\theta}} = \mathrm{Exp}\big((\boldsymbol{\omega}_m-\mathbf{b}_\omega)\Delta t\big)^{\!\top}, \quad
\frac{\partial\delta\boldsymbol{\theta}}{\partial\delta\mathbf{b}_\omega} = -\mathbf{I}\,\Delta t,
$$

plus $\partial\delta\mathbf{p}/\partial\delta\mathbf{v} = \mathbf{I}\Delta t$ and identity on
the diagonal. The first block is the one that couples attitude to position: a tilt error rotates
the measured specific force, so gravity leaks into the horizontal acceleration. That coupling is
why a GPS position fix can correct roll and pitch at all. In NumPy it is ten lines:

```python
F = np.eye(15)
F[0:3, 3:6] = I3 * dt
F[3:6, 6:9] = -R @ skew(am - ba) * dt
F[3:6, 9:12] = -R * dt
F[6:9, 6:9] = Exp((wm - bg) * dt).T
F[6:9, 12:15] = -I3 * dt
x = propagate(x, am, wm, dt)          # nominal state, full nonlinear
P = F @ P @ F.T + Qd(dt)
```

An update computes $\mathbf{H}$ with respect to the error state, solves for
$\delta\mathbf{x} = \mathbf{K}\mathbf{y}$ as usual, **injects** it into the nominal state with
$\boxplus$ (so the rotation is updated by $\mathbf{R}\,\mathrm{Exp}(\delta\boldsymbol{\theta})$
and stays a rotation), and **resets** the error to zero. The reset moves the tangent space the
covariance lives in, so the covariance is transported with the reset Jacobian
$\mathbf{G} \approx \mathbf{I} - [\tfrac12\delta\boldsymbol{\theta}]_\times$ on the rotation
block. Most implementations skip it. For small corrections the difference is negligible.

Here is one update done three ways on a body that turns in the plane, where the rotation is a
unit complex number $(\cos\theta, \sin\theta)$: two numbers, one constraint, the 2-D cousin of
the quaternion. Step through it, then drag the prior error up.

<EskfStep />

At the default 70° error the noise-free sensor says the body points at 130°. The classic EKF
adds its correction in the plane, lands at $|q| = 1.166$, renormalises, and reports 112.2° with
a σ of 3.9°: 17.8° wrong and claiming better than 4°. The error-state update moves along the
circle and lands at 112.8°. Same linearisation point, almost the same answer here. The
difference is that one is a rotation by construction and the other only after a patch. The
iterated filter in the last step gets to 128.6° in five passes.

## Iterating the update: the IEKF inside FAST-LIO

The EKF linearises $h$ at the predicted state. If the prediction is far from the truth, the
measurement Jacobian is evaluated in the wrong place. The fix follows from the MAP view above.
The update is the minimiser of

$$
J(\delta\mathbf{x}) = \lVert (\mathbf{x}_j \boxminus \hat{\mathbf{x}}^-) + \mathbf{J}_j\delta\mathbf{x} \rVert^2_{\mathbf{P}^-}
+ \lVert \mathbf{z} - h(\mathbf{x}_j \boxplus \delta\mathbf{x}) \rVert^2_{\mathbf{R}},
$$

a nonlinear least-squares problem. The EKF takes one Gauss-Newton step on it from
$\mathbf{x}_0 = \hat{\mathbf{x}}^-$. The **iterated EKF** keeps going: relinearise $h$ at the
new estimate $\mathbf{x}_j$, solve the linear problem again (with the prior term still
anchored at the prediction, which is the $\mathbf{x}_j \boxminus \hat{\mathbf{x}}^-$ term
people forget), and repeat until the step is small. Each pass is

$$
\delta\mathbf{x}_j = -\mathbf{J}_j^{-1}(\mathbf{x}_j \boxminus \hat{\mathbf{x}}^-)
+ \mathbf{K}_j\big(\mathbf{r}_j + \mathbf{H}_j\mathbf{J}_j^{-1}(\mathbf{x}_j \boxminus \hat{\mathbf{x}}^-)\big),
\qquad \mathbf{x}_{j+1} = \mathbf{x}_j \boxplus \delta\mathbf{x}_j,
$$

with $\mathbf{r}_j = \mathbf{z} - h(\mathbf{x}_j)$ and $\mathbf{K}_j$ computed from
$\mathbf{J}_j^{-1}\mathbf{P}^-\mathbf{J}_j^{-\top}$, where $\mathbf{J}_j = \mathbf{J}_r^{-1}(\mathbf{x}_j \boxminus \hat{\mathbf{x}}^-)$ is, on its rotation block, the inverse right Jacobian
of $SO(3)$ that carries the prior covariance onto the tangent space at $\mathbf{x}_j$. When the
measurement is linear in the state, the second pass changes nothing and it stops.

[FAST-LIO](https://arxiv.org/abs/2010.08196) and
[FAST-LIO2](https://arxiv.org/abs/2107.06829) run exactly this, on an error state over a
manifold, with the IMU predicting between LiDAR scans and thousands of point-to-plane residuals
in each update. The point-to-plane residual is strongly nonlinear in the pose (a small rotation
error moves a point 30 m away by a lot), which is why iterating pays there. The loop in the
middle of the overview is the iterated update, and the "converged?" test is the one above.

<Figure
  src="https://media.thesatyajit.com/ai/articles/fastlio2/x1.png?v=a74caf0d4debf0c2"
  alt="FAST-LIO2 system overview: IMU and LiDAR inputs feed forward propagation, points accumulation, backward propagation, residual computation, and an iterated state update that loops until converged; on the right an ikd-Tree map handles point-wise insert, box-wise delete, and kNN search."
  caption="FAST-LIO2's state estimation is an iterated error-state Kalman filter: forward propagation on the IMU, then residual computation and state update repeated until the 'Converged?' test passes, once per scan (FAST-LIO2 paper, Figure 1)."
/>

<Figure
  src="https://media.thesatyajit.com/ai/articles/fastlio2/x2.png?v=b7f7d01da5d96fa4"
  alt="The point-to-plane measurement model: a scan point (red) and the corresponding plane fit from nearby map points (blue), with the plane normal u_j; the residual is the signed distance from the point to the plane."
  caption="The measurement each iteration relinearises: the distance from a scan point to the plane through its nearest map points. Its dependence on the pose is what makes iterating worth it (FAST-LIO2 paper, Figure 2)."
/>

Each iteration costs one more residual computation and one more gain. FAST-LIO keeps that cheap
with the information-form gain from the derivation, which inverts an 18 × 18 matrix however many
points there are. The iterated filter is also where filtering and optimisation meet: run it to
convergence and the update *is* a MAP estimate, solved by Gauss-Newton, over one step's worth of
variables.

## Four filters on a real drive

Derivations are cheap. I wanted to see how much these differences matter on a real vehicle
with a real IMU, so I wrote all four nonlinear filters in NumPy (about 380 lines with the runner, no
estimation library) and ran them on a KITTI drive.

**The data.** KITTI raw drive `2011_09_30_drive_0018`, a residential loop in Karlsruhe. The
"extract" archive of that drive is 16.8 GB, almost all of it images and LiDAR; I read the zip's
central directory over HTTP range requests and pulled only the OXTS files, 28 MB in all. The
OXTS RT3003 is a GPS/IMU unit with RTK corrections, logging at 100 Hz. After dropping 12
out-of-order timestamps there are 28,658 samples over 288 s and 2.21 km, top speed
11.7 m/s, with one 1.62 s gap in the log that the filters simply integrate across.

**The setup**, stated plainly because it decides what the numbers mean:

- **The IMU is real**: the unit's own accelerometer and gyro readings at 100 Hz, specific force
  with gravity included. I checked the frames before filtering: dead-reckoning five seconds
  from the logged attitude reproduces the logged velocity to within about 0.1 m/s.
- **The truth is the unit's fused RTK solution** (median position accuracy 0.02 m in the log).
  It comes from the same box as the IMU, so it is not independent; it is far better than
  anything the filters produce, which is all a reference needs to be.
- **The fixes are synthetic**: the true position subsampled to 1 Hz with Gaussian noise of σ
  1 m east and north and 2 m up, like an ordinary GNSS receiver. Raw, that is 2.45 m of 3-D RMS
  error. Each of 20 seeds draws new fix noise and a new initial error; the IMU stream is the
  same in every seed, so the seeds average out fix noise but not IMU noise.
- **Four filters on identical inputs**: a classic EKF with the quaternion as four additive
  numbers (Jacobians by central differences, renormalised after each update); the UKF-M with
  31 sigma points; the ESKF from Solà's notes; and the iterated ESKF (up to 8 passes, FAST-LIO's
  update). All use the same noise model and the same initial covariance. Errors are scored
  the same way for all four: position, velocity, and the rotation error
  $\mathrm{Log}(\hat{\mathbf{R}}^{\top}\mathbf{R}_{\text{true}})$, with each filter's covariance
  mapped into that tangent space, so NEES has 9 degrees of freedom for every filter.

**A gate first.** Before touching the real log, I simulated 60 s of IMU and fixes from each
filter's own model with known noise. A filter that fails NEES there has a bug. All four passed:
averaged NEES between 8.06 and 8.11 against the band of 7.24 to 10.95, and NIS 3.13 for
3-dimensional fixes.

### Tuning on the log

The IMU's real noise is unknown, so I tuned the gyro noise density on the error-state filter
with accelerometer noise fixed at 0.05 m/s² per sample:

| gyro σ per sample | avg NEES (band 7.24–10.95) | 3-D position RMSE | yaw RMSE |
|---|---|---|---|
| 0.002 rad/s | 22.40 | 1.454 m | 3.795° |
| 0.005 rad/s | 10.78 | 1.344 m | 2.548° |
| 0.01 rad/s | 7.67 | 1.315 m | 2.148° |
| 0.02 rad/s | 6.32 | 1.337 m | 2.142° |

Too little gyro noise and the filter believes its heading too much: NEES of 22.40, and the
worst heading. At 0.005 rad/s the average is inside the band but near its top (10.78); at
0.01 rad/s it sits near the bottom (7.67) with a lower heading error, and doubling again buys
nothing. I took 0.01 rad/s: slightly underconfident, which is the side I want a navigation filter
on. Only 34% of the time steps fall inside the band even so. Split by what the car is doing, the
averaged NEES is below the band for 64% of the samples on straights and 95% of the few while
stopped, and climbs in turns (mean 8.22, above the band 12% of the time, against 8% on
straights). That reads as a noise model a little too generous for steady driving and about right
when the attitude is being excited. A filter that passes on average and fails in stretches is
normal on real data, and seeing where it fails is the useful part.

### A good start: they all agree

With a small initial error, 1 Hz fixes and no outages:

| filter | 3-D position RMSE | velocity RMSE | yaw RMSE | avg NEES | avg NIS (expect 3) | time per run |
|---|---|---|---|---|---|---|
| EKF (quaternion) | 1.315 m | 0.378 m/s | 2.155° | 7.67 | 2.85 | 3.2 s |
| UKF-M | 1.315 m | 0.378 m/s | 2.181° | 7.70 | 2.85 | 10.2 s |
| ESKF | 1.315 m | 0.378 m/s | 2.148° | 7.67 | 2.85 | 1.3 s |
| IEKF | 1.315 m | 0.378 m/s | 2.148° | 7.67 | 2.85 | 1.3 s |
| linear KF, no IMU | 2.595 m | 1.925 m/s | n/a | 4.76 (6 dof) | 3.07 | 0.1 s |

Four filters, one answer, to three decimals on position. When the errors are small, the
linearisation is good and every method is the same estimator. The IEKF averages two passes per
update and stops, because a position fix is linear in the state. The useful comparison in this
table is the last row: a linear constant-velocity filter on the same fixes, with no IMU, has
twice the position error and five times the velocity error. That gap is what the IMU buys.
(The KF row uses the best of the three acceleration intensities I tried; at the other two its
NEES was 35.6 and 2.76, outside its 6-dof band of 4.58 to 7.61.)

<Figure
  src="https://media.thesatyajit.com/ai/articles/kalman-filter/fig3.png?v=4ccb330ee5460ee2"
  alt="A map of the KITTI drive in metres east and north: a grey loop for the OXTS truth, dark dots for the noisy 1 Hz fixes scattered around it, a blue line for the error-state filter's estimate following the loop. Over a red highlighted stretch where fixes were withheld for 30 seconds, the blue line drifts off the road into the middle of a block, then jumps back onto the road at the first fix after the gap."
  caption="The drive, one seed: OXTS truth, the synthetic 1 Hz fixes, and the error-state filter riding the IMU between them. In red, the 30 s window from t = 120 s with no fixes, as in the stress test below: the estimate dead-reckons off the road and snaps back on the first fix after it. My plot, from my runs on KITTI raw drive 2011_09_30_drive_0018."
/>

### A bad start: the differences appear

Then I made it hard. Each filter starts with its heading 60° wrong (and is told so: the prior
yaw σ is 60°), and fixes are withheld for 30 s from t = 120 s.

| filter | yaw error at 10 s | avg NEES, first 30 s | avg NEES after 10 s | 3-D position RMSE | yaw RMSE |
|---|---|---|---|---|---|
| EKF (quaternion) | 19.0° | 36.9 | 10.46 | 6.453 m | 8.730° |
| UKF-M | 10.8° | 10.9 | 7.55 | 6.417 m | 7.818° |
| ESKF | 20.8° | 44.2 | 11.47 | 6.699 m | 8.903° |
| IEKF | 20.5° | 40.3 | 11.05 | 6.725 m | 8.823° |

<Figure
  src="https://media.thesatyajit.com/ai/articles/kalman-filter/fig4.png?v=36abc81cbf3d64f1"
  alt="A log-scale plot of averaged NEES against time over 288 seconds for four filters, with a shaded green band between about 7 and 11 and a shaded red window from 120 to 150 seconds where fixes are withheld. The lines start high while the heading error is large and settle at different levels; the outage drives some of them up."
  caption="Averaged NEES over 20 seeds for the 60° heading error with the 30 s outage, against the 95% band. A line above the band is a filter claiming more certainty than it has. My plot, from my runs."
/>

The position errors are close and large for all four, because the 30 s outage dominates them:
with no fixes the filters dead-reckon on the IMU and drift about 40 m (RMS over the seeds, at
the moment the fixes return) whichever one you run. They all knew it. Averaged NEES during the
outage sits between 4.67 and 5.63, below the band: the covariance grew faster than the error, the
honest direction to be wrong in.

The heading is where they part. A 60° error is far outside the region where a first-order
Jacobian describes the rotation, and in the first 30 s the EKF and ESKF report NEES of 36.9 and
44.2: four to five times overconfident while they swing the heading back. The UKF-M, whose sigma
points sample the rotation at ±1.9σ instead of at one point, gets its heading to 10.8° by the
10 s mark (against 19.0° and 20.8°) and stays near its band throughout (NEES 10.9). The IEKF tracks the ESKF, as it should with linear
fixes: its second pass confirms the first.

Push the start to 120° wrong (prior σ 120°, no outage) and only one of them comes back. The
EKF, ESKF and IEKF end the run with heading errors of 50.0°, 50.4° and 45.7° RMS and NEES in the
thousands; a Jacobian taken at a heading that far off points the correction the wrong way, and
the covariance shrinks anyway. The UKF-M gets to 18.0° RMS (17.3° at the 30 s mark) with NEES of
36.96: still overconfident, but recovering. If your system can start with no idea which way it
faces, initialise the heading some other way (a magnetometer, a short drive, a coarse search)
before you hand it to an EKF of any flavour.

### A nonlinear measurement: where iterating pays

A position fix is linear in the state, so it cannot show what the IEKF is for. To give it a
measurement that is not, I replaced the fixes with ranges to four fixed anchors 50 m from the
start in each diagonal direction (two at 2 m height, two at 15 m), like UWB beacons, with
σ 0.5 m at 1 Hz. The ranges are computed from the true positions plus noise; they are as
synthetic as the fixes were. Each seed draws the start from a prior with σ 30 m on each
horizontal axis and σ 30° in heading (34.2 m from the truth at the median, 34.6° RMS in heading).

After the first update, the EKF and the ESKF are 18.63 m from the truth (RMS over 20 seeds) and
report NEES of 663 averaged over the first 10 s: they took one linearised step from a point 30 m
off and believe it. The IEKF, iterating the same update (5.81 passes on average), lands
1.13 m from the truth on the first update and its averaged NEES over the first 10 s is 9.6,
inside the band. Over the whole run its position RMSE is 2.285 m against 6.499 m for the EKF and
6.237 m for the ESKF, and it is the only filter of the four whose run-long NEES (10.16) is in
the band; the EKF's is 120.82 and the ESKF's 248.20.

The UKF was the worst: 41.12 m RMS after the first update and 22.524 m over the run, with NEES
in the thousands. That RMS is driven by a few seeds. Per seed, the UKF's first-update error has
a median of 11.87 m and a worst case of 95.3 m (the ESKF's: 6.87 m and 51.6 m; the IEKF's:
1.03 m and 2.1 m). The likely cause is its spread: the sigma points sit ±1.9σ, about 58 m, from a
start already some 34 m off, while the anchors are 50 m away on each diagonal, so some sigma
points land near or past an anchor, where range is as nonlinear as it gets. Narrowing the spread
(α from 0.5 to 0.1) brings the first-update RMS down to 8.08 m and the median to 5.0 m, which
supports that reading without making the UKF competitive here. A UKF's sampling is a strength when its spread matches the function's scale and a
liability when it does not. The IEKF's answer to a bad prior is different in kind: keep
relinearising at the best estimate so far until the update converges, which is what FAST-LIO's
loop does on every scan.

<Figure
  src="https://media.thesatyajit.com/ai/articles/kalman-filter/fig5.png?v=298c976600c3ec6a"
  alt="A log-scale plot of position error in metres against time for the first 30 seconds of the range-only experiment, one line per filter. The iterated filter's error is lowest from the first update; the EKF and ESKF lines start highest and overlap; the UKF sits between them."
  caption="Position error, RMS over 20 seeds, for the first 30 s with range-only measurements and a 30 m initial error. My plot, from my runs."
/>

## Filters versus factor graphs

Every filter on this page **marginalises**: after each step it folds the past into one
Gaussian and forgets it. Once a linearisation error is baked into $\mathbf{P}$, it stays there.
A factor graph, the model [GTSAM](/articles/gtsam-4-3) solves, keeps the past as variables and
factors (the prior, each IMU step, each measurement) and solves for all of it jointly by
nonlinear least squares. It is the same cost as the IEKF's, over the whole trajectory instead of
one step, so it can relinearise old states when new information arrives.

In the linear-Gaussian case the batch solution over a whole log equals the
Rauch-Tung-Striebel smoother: a Kalman filter forward and one backward pass. So I can measure
the value of looking back without leaving NumPy. An error-state RTS pass over the same 20 seeds
of the good-start run:

| | 3-D position RMSE | velocity RMSE | yaw RMSE | avg NEES |
|---|---|---|---|---|
| ESKF, filtering | 1.315 m | 0.378 m/s | 2.148° | 7.67 |
| ESKF + RTS, smoothing | 0.540 m | 0.079 m/s | 0.981° | 9.90 |

Using future fixes to correct past states cuts position error by 59% and heading error by more
than half, and the smoothed covariance stays consistent. The backward pass took 1.4 s against
2.2 s for the forward filter with storage. That is the factor graph's case in two rows, and it
is a strong one: whenever the answer can wait (mapping, offline trajectories, anything with
loop closures), a smoother or a graph wins on accuracy. This is not GTSAM itself. I did not
run it here; the RTS pass is the linearised special case, and a real graph with IMU
preintegration and relinearisation would do at least as well.

Filters keep their place anyway:

- **Latency and fixed cost.** A filter's work per step is constant and small. FAST-LIO2 runs
  its full update in milliseconds per scan on a laptop CPU and an ARM board. A graph's cost
  grows unless you bound it with a fixed-lag window or iSAM2's incremental updates, and then
  you are marginalising again, with the same linearisation questions.
- **Control.** A controller needs the state now, not a better estimate of where you were.
- **Simplicity.** A 15-state ESKF is a few hundred lines with no dependencies. It fits on a
  microcontroller.

The modern systems split the difference: a filter or a short sliding window for the real-time
state (FAST-LIO2, VINS-Mono's local window), and a pose graph in the background for loop
closures. That split is what I would build.

## Which filter I'd use

- **Linear model, linear sensor**: the plain Kalman filter, Joseph-form update, and you are
  done. It is optimal, and nothing else is.
- **Anything with a 3-D orientation**: the error-state filter. On the drive it matched the
  others' accuracy at the lowest cost, and its rotation stays a rotation without patches. I see
  no reason to write a full-state quaternion EKF in 2026.
- **Strongly nonlinear measurements** (LiDAR point-to-plane, ranges, camera reprojection) or a
  poor prior: iterate the ESKF update. On the range test it was the only filter whose
  covariance meant something in the first seconds, and it costs little extra when the
  measurement is linear, because it stops after one confirming pass.
- **Uncertain start and no time pressure**: the UKF-M was the most robust to a wrong heading in
  my runs. It costs about 8x the ESKF in my code, and it needs the manifold version; a naive UKF
  on quaternions is worse than the EKF.
- **The answer can wait**: smooth, or build a factor graph.

And whichever you pick, log NIS from day one. It costs one line, it needs no ground truth, and
it is the only way you will find out your filter has started lying before something downstream
does.

## What I ran and what I read

What I ran, all on a MacBook CPU: the four filters, the linear KF and the RTS smoother, in my
own NumPy code; the simulation gate; the gyro sweep, the Q scaling, the good-start, 60° and 120°
heading and range-anchor runs, 20 seeds each; and the three result plots. The two widgets'
numbers come from their own code, which I also ran under Node to check them. What I read: the
filter derivations follow Solà's
[quaternion notes](https://arxiv.org/abs/1711.02508) and
[micro Lie theory](https://arxiv.org/abs/1812.01537) (both figures are from the arXiv sources,
rendered from the authors' PDFs), the FAST-LIO and FAST-LIO2 papers for the iterated update and
its figures, Brossard et al. for the UKF-M, and Bar-Shalom, Li and Kirubarajan for the NEES and
NIS tests. The data is KITTI raw (Geiger et al.), CC BY-NC-SA 3.0. Not verified: whether the
OXTS accelerations carry any internal bias compensation (they dead-reckon cleanly, which suggests
they are close), and how the filters compare against GTSAM itself, which I did not run.
