# FAST-LIO2: the filter derived, rebuilt from scratch, and measured against three successors

> Satyajit Ghana — Head of Engineering @ Inkers Technology
> canonical: https://ai.satyajit.si/articles/fast-lio2-lidar-inertial-odometry
> date: 2026-06-28
> tags: slam, lidar, state-estimation, point-cloud, benchmarks

FAST-LIO2 is the LiDAR-inertial odometry I keep coming back to. It is one tight loop around
an iterated Kalman filter: integrate the IMU, undo the motion inside each sweep, register
raw points to a map of planes, and keep that map in a k-d tree that never has to be rebuilt
from scratch. The paper reports 100 Hz odometry and mapping, rotations up to 1000 deg/s
on a handheld rig, and better accuracy than the LiDAR-inertial systems of 2021 on 19 public
sequences.

The first version of this article derived that loop and rebuilt its core in about 390 lines
of Python. It tracked a real Livox bag. It never said how well. There was no ground truth,
no comparison with the official code, and nothing about the five years of systems built on
top of it. This version adds all three. I ran four systems on two public sequences that have
a reference trajectory measured independently of any of them:

- the Python port from this article, unchanged;
- the official FAST-LIO2 (the `hku-mars/FAST_LIO` ROS 2 branch), plus the same build with
  its deskew switched off;
- [Super-LIO](https://arxiv.org/abs/2509.05723) (RA-L 2026), which keeps FAST-LIO2's filter
  and replaces the ikd-Tree with a hashed voxel map that stores eight points per voxel;
- [FAR-LIO](/articles/far-lio) (IROS 2026), which moves registration to a GPU and the
  filter to a small kinematic EKF.

The two sequences are a basement on Hilti's construction site (Hilti SLAM Challenge 2022,
`exp14_basement_2`) and a walk round a college quad in Oxford (Oxford Spires,
`keble-college-03`). Every system got the same input, the same scoring and the same four
CPU cores. On the Oxford walk FAST-LIO2 and Super-LIO both
track to about 8 cm over 283 m, and Super-LIO does it in 5.6 ms a scan against 12.7. In the
basement only Super-LIO holds together, at 9.3 cm, and FAST-LIO2's shipped settings turn out to be
the wrong ones for a room. Switching deskew off costs FAST-LIO2 a factor of four outdoors. FAR-LIO,
on its CPU build, needs its voxel size changed between the two places, and the article's own
Python port tracks the first 91 m of the Oxford walk at 3.3 cm, at 4.8 s a scan.

The rest is in the order you would build it: the state, the IMU, deskewing, the measurement,
the iterated update, the map, then the port and its bugs, then the numbers.

## The loop

A LiDAR returns tens of thousands of points per sweep, ten times a second. A sweep takes
100 ms, and a handheld sensor turns and walks during it, so the points in one sweep were
measured from many slightly different poses. LiDAR alone also registers slowly and loses
track when the motion is fast. An IMU reports acceleration and angular rate at 200 to
1000 Hz, which describes motion within a sweep well and drifts within seconds. Fused tightly,
each covers the other.

<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 system overview. Left, the state estimation: IMU forward propagation, point accumulation, backward propagation to deskew, the point-to-plane residual, an iterated update repeated until it converges. Right, the ikd-Tree map: insert with on-tree downsampling, box-wise delete as the map window moves, and the kNN search the residual needs (FAST-LIO2 paper, Figure 1)."
/>

Here is the cycle as a sequence, with what each stage does and why it has to be there. It
runs once per LiDAR scan, and the IMU drives the prediction in between:

<LioFlow />

FAST-LIO2 differs from FAST-LIO, its predecessor, in two ways. It registers raw points
directly to the map with point-to-plane residuals, with no edge or plane feature extraction,
so it uses all the geometry and has nothing to tune per sensor. And it keeps the map in the
ikd-Tree, an incremental k-d tree that inserts, deletes, downsamples and re-balances in
place. Under both sits a tightly coupled iterated error-state Kalman filter on a manifold.
I quote C++ from the official [`hku-mars/FAST_LIO`](https://github.com/hku-mars/FAST_LIO)
and from [`zlwang7/S-FAST_LIO`](https://github.com/zlwang7/S-FAST_LIO), a reimplementation
that writes the filter out with plain Eigen and Sophus instead of the IKFoM template library,
with simplified NumPy beside them.

## The state lives on a manifold

An orientation cannot be stored as three numbers and added to. Rotations live on $SO(3)$.
The paper's state is

$$
\mathbf{x} = \big[\ {}^G\mathbf{R}_I,\ {}^G\mathbf{p}_I,\ {}^G\mathbf{v}_I,\ \mathbf{b}_\omega,\
\mathbf{b}_a,\ {}^G\mathbf{g},\ {}^I\mathbf{R}_L,\ {}^I\mathbf{p}_L\ \big]
\in SO(3)\times\mathbb{R}^{15}\times SO(3)\times\mathbb{R}^{3}:
$$

attitude, position and velocity of the IMU in the global frame, gyro and accelerometer
biases, gravity, and the LiDAR-to-IMU extrinsic. Each rotation takes 3 tangent dimensions,
not the 4 of a quaternion. The released code goes one step further and puts gravity on the
sphere $S^2$, because its length is known and only its direction is uncertain. That leaves
23 numbers in the error state and the covariance:

```cpp
// hku-mars/FAST_LIO include/use-ikfom.hpp: the state as an IKFoM manifold
MTK_BUILD_MANIFOLD(state_ikfom,
((vect3, pos))
((SO3, rot))
((SO3, offset_R_L_I))
((vect3, offset_T_L_I))
((vect3, vel))
((vect3, bg))
((vect3, ba))
((S2, grav))
);
```

S-FAST_LIO keeps gravity as a plain 3-vector instead, so its error state is 24-dimensional.
Nothing else in the filter changes.

Two operators do all the work. $\boxplus$ moves a state along a tangent vector and
$\boxminus$ gives the tangent vector between two states. For the rotation block,

$$
\mathbf{R}\boxplus\boldsymbol\delta = \mathbf{R}\,\mathrm{Exp}(\boldsymbol\delta),
\qquad
\mathbf{R}_1\boxminus\mathbf{R}_2 = \mathrm{Log}(\mathbf{R}_2^{\!\top}\mathbf{R}_1),
$$

and every vector block uses ordinary $+$ and $-$. The filter estimates a small error
$\tilde{\mathbf{x}}$ in the tangent space around the current estimate and folds it back in
with $\boxplus$. The error is small, so a linearisation around it is good, and nothing ever
has to be re-normalised.

## Forward propagation: ride the IMU

Between scans the IMU drives the state. The kinematics are the strapdown model: position
integrates velocity, attitude integrates the de-biased rate, velocity integrates the
de-biased, gravity-corrected acceleration,

$$
\dot{\mathbf{p}} = \mathbf{v}, \qquad
\dot{\mathbf{R}} = \mathbf{R}\,(\boldsymbol{\omega}_m - \mathbf{b}_\omega)^\wedge, \qquad
\dot{\mathbf{v}} = \mathbf{R}(\mathbf{a}_m - \mathbf{b}_a) + \mathbf{g},
$$

with the biases on a slow random walk. That is `get_f`:

```cpp
// S-FAST_LIO include/use-ikfom.hpp, get_f (comments mine)
Eigen::Vector3d omega = in.gyro - s.bg;                          // ω = ω_m − b_ω
Eigen::Vector3d a_inertial = s.rot.matrix() * (in.acc - s.ba);   // R(a_m − b_a)
for (int i = 0; i < 3; i++)
{
    res(i) = s.vel[i];                        // ṗ = v
    res(i + 3) = omega[i];                    // attitude rate
    res(i + 12) = a_inertial[i] + s.grav[i];  // v̇ = R(a_m − b_a) + g
}
```

Each IMU sample moves the mean along the manifold and grows the covariance through the
error-state Jacobians $\mathbf{F}_{\tilde{\mathbf{x}}}$ and $\mathbf{F}_{\mathbf{w}}$
(the paper's Eq. 6):

$$
\hat{\mathbf{x}}_{i+1} = \hat{\mathbf{x}}_i\boxplus\big(\Delta t\,\mathbf{f}(\hat{\mathbf{x}}_i,\mathbf{u}_i,\mathbf{0})\big),
\qquad
\hat{\mathbf{P}}_{i+1} = \mathbf{F}_{\tilde{\mathbf{x}}}\hat{\mathbf{P}}_i\mathbf{F}_{\tilde{\mathbf{x}}}^{\!\top}
+ \mathbf{F}_{\mathbf{w}}\mathbf{Q}\,\mathbf{F}_{\mathbf{w}}^{\!\top}.
$$

```cpp
// S-FAST_LIO include/esekfom.hpp, predict (comments mine)
void predict(double &dt, Eigen::Matrix<double, 12, 12> &Q, const input_ikfom &i_in)
{
    Eigen::Matrix<double, 24, 1> f_ = get_f(x_, i_in);     // f
    Eigen::Matrix<double, 24, 24> f_x_ = df_dx(x_, i_in);  // ∂f/∂x
    Eigen::Matrix<double, 24, 12> f_w_ = df_dw(x_, i_in);  // ∂f/∂w
    x_ = boxplus(x_, f_ * dt);                              // x ⊞ (Δt f)
    f_x_ = Matrix<double, 24, 24>::Identity() + f_x_ * dt;  // F_x = I + Δt ∂f/∂x
    P_ = (f_x_)*P_ * (f_x_).transpose() + (dt * f_w_) * Q * (dt * f_w_).transpose();
}
```

In NumPy the shape of it is:

```python
def predict(x, P, imu, dt, Q):
    f      = get_f(x, imu)              # kinematics above
    F_x, F_w = jacobians(x, imu, dt)   # error-state transition + noise maps
    x = boxplus(x, f * dt)             # advance the mean on the manifold
    P = F_x @ P @ F_x.T + F_w @ Q @ F_w.T
    return x, P
```

This runs once per IMU sample, up to the end time of the next scan, and the pose after every
sample is kept. The next step needs them.

## Backward propagation: deskew the scan

Every point in a sweep was measured from the pose the sensor had at that instant. Stack them
in one frame and a flat wall comes out sheared:

<Deskew />

FAST-LIO2's backward propagation walks the cached IMU poses back from the end of the scan and
moves each point from the pose it was sampled at into the scan-end frame. For a point sampled
at time $\rho_j$, with IMU pose $(\mathbf{R}_j,\mathbf{t}_j)$ then and $(\mathbf{R}_e,\mathbf{t}_e)$
at the scan end,

$$
\mathbf{p}^{\text{end}}_j = {}^I\mathbf{R}_L^{\top}\Big(\mathbf{R}_e^{\!\top}\big(\mathbf{R}_j({}^I\mathbf{R}_L\,\mathbf{p}_j + {}^I\mathbf{t}_L) + (\mathbf{t}_j - \mathbf{t}_e)\big) - {}^I\mathbf{t}_L\Big),
$$

which is the compensation in `UndistortPcl`:

```cpp
// FAST_LIO src/IMU_Processing.hpp, UndistortPcl (condensed)
M3D R_i(R_imu * Exp(angvel_avr, dt));        // attitude at this point's sample time
V3D T_ei(pos_imu + vel_imu*dt + 0.5*acc_imu*dt*dt - imu_state.pos);
V3D P_compensate = imu_state.offset_R_L_I.conjugate() *
    (imu_state.rot.conjugate() * (R_i * (imu_state.offset_R_L_I * P_i
     + imu_state.offset_T_L_I) + T_ei) - imu_state.offset_T_L_I);
```

Between two IMU samples the code assumes constant angular rate and constant acceleration,
so a point $dt$ after a sample gets that sample's attitude times $\mathrm{Exp}(\boldsymbol\omega\,dt)$
and a position from the constant-acceleration formula. Rotation is what matters. A sensor
turning at $\omega$ for a sweep of length $T$ moves a return at range $r$ sideways by about
$r\,\omega\,T$, so the error grows with range, while walking speed $v$ adds only $v\,T$ to
every point. On the two sequences I measured how much that is, sweep by sweep, from the IMU
and the point timestamps themselves:

<DeskewBudget />

Rotation dominates on both walks. On Spires the IMU turns at a median 0.38 rad/s during a
sweep and up to 2.36 rad/s; at the median range of 5.6 m that carries a return about 31 cm across a
sweep in the median case, three times the 0.1 m plane-fit tolerance, on every sweep I sampled.
Hilti turns as fast, but its returns are a metre away, and at that range six sweeps in ten stay
under the tolerance. What deskewing buys is measured further down: on Spires, the same FAST-LIO2 build with
the backward-propagation loop skipped goes from 7.2 cm ATE to 30.8 cm, and its rotation error from
0.19 to 1.35 degrees per metre.

## The measurement: point-to-plane

FAST-LIO2 extracts no features. It moves each deskewed point into the world with the current
estimate, finds its five nearest map points in the ikd-Tree, fits a plane to them, and uses
the signed distance from the point to that plane as the residual. The residual is zero when
the point sits on the surface:

<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 model: a scan point (red) is matched to the plane fitted to its nearest map points (blue), and the residual is the signed distance along the normal uⱼ, which is zero when the estimated pose puts the point on the surface (FAST-LIO2 paper, Figure 2)."
/>

With ${}^G\hat{\mathbf{p}}_j = {}^G\hat{\mathbf{T}}_I\,{}^I\hat{\mathbf{T}}_L\,{}^L\mathbf{p}_j$
the point in the world at the current estimate, $\mathbf{u}_j$ the plane normal and
$\mathbf{q}_j$ a point on the plane, the residual is (Eq. 9)

$$
z_j = \mathbf{u}_j^{\top}\big({}^G\hat{\mathbf{p}}_j - {}^G\mathbf{q}_j\big).
$$

The plane fit rejects a neighbourhood when any of the five points is more than 0.1 m off the
fitted plane, and the code keeps a match only if
$s = 1 - 0.9\,|z_j|/\sqrt{\lVert\mathbf{p}_j\rVert} > 0.9$, a gate that allows a larger
residual on a far point. That is `h_share_model`:

```cpp
// condensed from h_share_model (FAST_LIO src/laserMapping.cpp; S-FAST_LIO esekfom.hpp)
V3D p_global(s.rot * (s.offset_R_L_I * p_body + s.offset_T_L_I) + s.pos);  // to world
ikdtree.Nearest_Search(point_world, NUM_MATCH_POINTS, points_near, sqDis); // 5 nearest
if (esti_plane(pabcd, points_near, 0.1f)) {                                 // fit plane (a,b,c,d)
    float pd2 = pabcd(0)*x + pabcd(1)*y + pabcd(2)*z + pabcd(3);            // point-to-plane dist
    ...
}
// Jacobian row (w.r.t. attitude θ and extrinsic), residual = −distance
V3D C(s.rot.conjugate() * norm_vec);          // Rᵀu
V3D A(point_I_crossmat * C);                  // (R_L^I p + t_L^I)^∧ Rᵀu
ekfom_data.h_x.block<1,12>(i,0) << norm_p.x, norm_p.y, norm_p.z, A, ...;   // [ u | A | … ]
ekfom_data.h(i) = -norm_p.intensity;          // the residual
```

The detail that matters later: each row of the measurement Jacobian $\mathbf{H}$ has only 12
non-zero columns, six for the pose and six for the extrinsic. A single scan cannot observe
velocity, biases or gravity directly. Those are corrected through their covariance with the
pose. In NumPy:

```python
def build_H_z(points_body, x, ikdtree, map_pts, R_LI, t_LI):
    H, z = [], []
    for p in points_body:
        pw = x.R @ (R_LI @ p + t_LI) + x.p          # body → world
        nn = ikdtree.nearest(pw, k=5)               # 5 nearest map points
        n, d = fit_plane(map_pts[nn])               # unit normal, offset
        r = n @ pw + d                              # point-to-plane distance
        if abs(r) < 0.1:                            # keep confident matches
            pI = R_LI @ p + t_LI
            A  = skew(pI) @ (x.R.T @ n)             # ∂r/∂θ  (attitude block)
            H.append(np.concatenate([n, A]))        # [ normal | attitude ]
            z.append(-r)
    return np.array(H), np.array(z)                 # H: m×6 (here), z: m
```

## The iterated update is Gauss-Newton on a MAP problem

This is the part most write-ups wave at, so here it is properly.

After propagation, the filter holds a prior: the predicted state $\hat{\mathbf{x}}_k$ and its
covariance $\hat{\mathbf{P}}_k$. The scan gives $m$ residuals, each with noise variance
$\mathbf{R}_j$. Suppose the current guess is $\hat{\mathbf{x}}^\kappa_k$ (at the first iteration,
the prediction itself) and write the unknown true state as that guess plus a small error,
$\mathbf{x}_k = \hat{\mathbf{x}}^\kappa_k\boxplus\tilde{\mathbf{x}}^\kappa$. Linearise each
residual around the guess, $z_j^\kappa + \mathbf{H}_j\tilde{\mathbf{x}}^\kappa$, and the most
probable error is the one that minimises (the paper's Eq. 13)

$$
\min_{\tilde{\mathbf{x}}^\kappa}\;
\big\|\mathbf{x}_k\boxminus\hat{\mathbf{x}}_k\big\|^2_{\hat{\mathbf{P}}_k}
\;+\;\sum_{j=1}^{m}\big\|z_j^\kappa + \mathbf{H}_j\tilde{\mathbf{x}}^\kappa\big\|^2_{\mathbf{R}_j},
\qquad \|\mathbf{e}\|^2_{\mathbf{M}} = \mathbf{e}^\top\mathbf{M}^{-1}\mathbf{e}.
$$

The first term says "don't stray far from what the IMU predicted, in units of how unsure the
prediction is". The second says "put the points on the planes, in units of how noisy a LiDAR
return is". One detail hides in the first term. The prior is a Gaussian on the error *around
the prediction*, but the unknown is now expressed around the current guess. On a manifold
those two errors differ by more than a shift:

$$
\mathbf{x}_k\boxminus\hat{\mathbf{x}}_k
= \big(\hat{\mathbf{x}}^\kappa_k\boxminus\hat{\mathbf{x}}_k\big) + \mathbf{J}^\kappa\tilde{\mathbf{x}}^\kappa ,
$$

where $\mathbf{J}^\kappa$ is the identity except for the two rotation blocks, which carry the
inverse right Jacobian of $SO(3)$ evaluated at how far the guess has rotated from the
prediction. At the first iteration the guess is the prediction and $\mathbf{J}=\mathbf{I}$.

Setting the gradient of that quadratic to zero gives the update (Eq. 14), with
$\mathbf{P} = (\mathbf{J}^\kappa)^{-1}\hat{\mathbf{P}}_k(\mathbf{J}^\kappa)^{-\top}$:

$$
\mathbf{K} = \big(\mathbf{H}^{\top}\mathbf{R}^{-1}\mathbf{H} + \mathbf{P}^{-1}\big)^{-1}\mathbf{H}^{\top}\mathbf{R}^{-1},
\qquad
\hat{\mathbf{x}}^{\kappa+1}_k = \hat{\mathbf{x}}^\kappa_k\boxplus\Big(-\mathbf{K}\mathbf{z}^\kappa
- (\mathbf{I}-\mathbf{K}\mathbf{H})(\mathbf{J}^\kappa)^{-1}\big(\hat{\mathbf{x}}^\kappa_k\boxminus\hat{\mathbf{x}}_k\big)\Big).
$$

The first term pulls the points onto their planes. The second pulls the guess back toward the
prediction by however much the measurements leave unconstrained. Then the filter does what an
ordinary EKF never does: it re-finds every point's five neighbours at the new guess, refits
the planes, rebuilds $\mathbf{H}$ and $\mathbf{z}$, and solves again. That is Gauss-Newton on
the MAP cost above, with the prior as a regulariser. It stops when every component of the
step is under $10^{-3}$, or after a fixed number of iterations (`max_iteration`, 3 in every config
the ROS 2 branch ships). Only then is the covariance updated,
once, $\bar{\mathbf{P}}_k = (\mathbf{I}-\mathbf{K}\mathbf{H})\,\mathbf{P}$.

Why iterate at all? Because the correspondences are the nonlinearity. A plane fitted around
a point that sits 20 cm from where it should is the wrong plane, and one linear step from a
wrong guess lands on another wrong guess. Re-associating at each iterate is what lets the
scan slide onto the map:

<IEKFRegister />

Now the cost. The textbook gain $\hat{\mathbf{P}}\mathbf{H}^\top(\mathbf{H}\hat{\mathbf{P}}\mathbf{H}^\top+\mathbf{R})^{-1}$
inverts an $m\times m$ matrix, and $m$ is the number of matched points, several thousand per
scan. The form above inverts a matrix the size of the state, 23 by 23, whatever $m$ is. Both
are the same matrix by the matrix-inversion lemma, so this costs nothing in accuracy. With a
scalar $\mathbf{R} = \sigma^2\mathbf{I}$ the big product $\mathbf{H}^\top\mathbf{H}$ is a sum
of $m$ outer products of rows that are non-zero in only 12 places. In S-FAST_LIO it is a few
lines inside `update_iterated_dyn_share_modified`:

```cpp
// S-FAST_LIO include/esekfom.hpp (comments mine; R = LASER_POINT_COV = 0.001)
dx_new = boxminus(x_, x_propagated);                     // x^κ ⊟ x̂
auto H = dyn_share.h_x;                                  // m × 12
Eigen::Matrix<double, 24, 24> HTH = Matrix<double, 24, 24>::Zero();
HTH.block<12, 12>(0, 0) = H.transpose() * H;             // only the pose/extrinsic block
auto K_front = (HTH / R + P_.inverse()).inverse();       // (HᵀR⁻¹H + P⁻¹)⁻¹, 24 × 24
K = K_front.block<24, 12>(0, 0) * H.transpose() / R;
Eigen::Matrix<double, 24, 24> KH = Matrix<double, 24, 24>::Zero();
KH.block<24, 12>(0, 0) = K * H;
Matrix<double, 24, 1> dx_ = K * dyn_share.h + (KH - Matrix<double, 24, 24>::Identity()) * dx_new;
x_ = boxplus(x_, dx_);
// converged when every |dx_[j]| < 0.001, then once: P_ = (I − KH) P_
```

`dyn_share.h` holds minus the point-to-plane distance, so `K * h` is the $-\mathbf{K}\mathbf{z}$
of Eq. 14 and `(KH - I) * dx_new` is its second term. S-FAST_LIO leaves out $\mathbf{J}$, which
the official IKFoM code keeps; the difference is second order while the rotation between
iterates is small. The same loop in NumPy,
with the cheap gain spelled out:

```python
def update_iterated(x, P, points_body, ikdtree, map_pts, R=1e-3, max_iter=4, eps=1e-3):
    x_prior = x.copy()
    n = P.shape[0]                                   # 23 (error-state dim)
    for _ in range(max_iter):
        H, z = build_H_z(points_body, x, ikdtree, map_pts, R_LI, t_LI)  # relinearize
        # information-form gain: invert (state × state), independent of len(z)
        S = H.T @ H / R + np.linalg.inv(P)           # n×n
        K = np.linalg.solve(S, H.T) / R              # K = S⁻¹ Hᵀ R⁻¹
        dx = K @ z + (np.eye(n) - K @ H) @ (-boxminus(x, x_prior))
        x  = boxplus(x, dx)
        if np.max(np.abs(dx)) < eps:
            break
    P = (np.eye(n) - K @ H) @ P
    return x, P
```

The converged state is the odometry, published at LiDAR rate, and the
deskewed scan, moved into the world with it, goes into the map.

[GTSAM 4.3](/articles/gtsam-4-3) solves the same kind of problem with a factor graph over many
poses at once and relinearises the whole window. FAST-LIO2 solves it for one pose, every scan,
and throws the past away except through the covariance. That is the trade: no smoothing of
earlier poses, and a fixed cost per scan.

## The map: an incremental k-d tree

The nearest-neighbour search is the hot loop, five neighbours for every downsampled point
at every iteration, and the map it searches grows and moves with the sensor. A static k-d
tree would have to be rebuilt every scan. The ikd-Tree ([Cai, Xu and Zhang, 2021](https://arxiv.org/abs/2102.10808))
avoids that with four ideas.

**Each node knows its subtree.** Besides the point, the split axis and two children, a node
stores the subtree's size, how many of its points are deleted, a bounding box, and three
lazy labels: `deleted`, `tree_deleted` and `pushdown`. The bounding box lets a box query skip
whole subtrees. The labels let a delete touch one node instead of thousands.

**Deletes are lazy.** Deleting a point flips its `deleted` flag. Deleting a box, which is what
happens when the map window slides past a region, walks down from the root: a subtree that
lies wholly inside the box gets `tree_deleted` set on its root and is not visited further,
a subtree that misses the box is skipped, and only the partial overlaps recurse. Dead points
stay in the tree until something rebuilds the subtree they are in.

**Downsampling happens on the tree.** To insert a point at map resolution $L$ (the
`filter_size_map`, 0.5 m in the Velodyne config), the tree box-searches the $L$-cube the point
falls in, keeps whichever point is nearest the cube's centre, and deletes the rest. The map
never holds more than one point per cube.

**Rebalancing is partial.** After every insert or delete, each node on the path back to the
root re-counts itself and checks two rules (`Criterion_Check` in FAST-LIO's copy of the tree):
a subtree is rebuilt if more than half of its points are deleted, or if one child holds more
than 0.6 (or less than 0.4) of the other `size - 1` points. Subtrees of 10 nodes or fewer are
never checked. A rebuild flattens the subtree into an array, dropping deleted points, and builds
a perfectly balanced subtree from the medians:

<Figure
  src="https://media.thesatyajit.com/ai/articles/fastlio2/ikd-rebuild.png?v=861f7e4a169088d0"
  alt="Rebuilding an unbalanced subtree: on the left an orange tree whose right subtree T (blue, boxed) is lopsided with balance 0.75; the subtree is flattened into an array V, and rebuilt into a balanced subtree T-prime with balance 0.5, on the right."
  caption="Rebuild: an unbalanced subtree T is flattened into a point array V and rebuilt balanced as T′, while the rest of the tree is untouched (ikd-Tree paper, Figure 3)."
/>

The balance rule bounds the height at $\log_{1/0.6} n$ instead of $\log_2 n$, about 1.36 times
deeper than a perfect tree at worst, which keeps a point insert and a nearest-neighbour query at
$O(\log n)$. Rebuilding a big subtree would stall the scan, so subtrees of 1,500 points or more
are handed to a second thread. That thread copies the valid points out, builds the new subtree,
and replays any inserts and deletes that arrived meanwhile from an "operation logger" before
swapping it in under a lock that blocks queries for one pointer assignment.

The widget below is a real two-dimensional incremental k-d tree running those rules in the
page. The sensor drives right; insert scans and new points pile into one side of the tree until
a subtree tips and is rebuilt; box-delete behind the sensor and whole subtrees die with one
label, then get swept out once more than half of them is dead:

<IkdOps />

At the scale of the whole map, the effect is a window of points that moves with the sensor:

<IkdMap />

<Figure
  src="https://media.thesatyajit.com/ai/articles/fastlio2/x3.png?v=5167061e910c6b3a"
  alt="2D illustration of ikd-Tree map region management: a local map cube around the sensor that slides as the platform moves, with regions added at the leading edge and removed at the trailing edge."
  caption="Map region management: the ikd-Tree keeps a cube of map around the sensor; when the sensor nears a face of the cube, the cube moves and the regions it leaves are removed with box-wise deletes (FAST-LIO2 paper, Figure 3)."
/>

In code it is a handful of calls:

```cpp
ikdtree.Build(feats_down_world->points);          // first scan
ikdtree.Add_Points(PointToAdd, true);             // incremental insert + on-tree downsample
ikdtree.Delete_Point_Boxes(cub_needrm);           // box-wise delete (window slid)
ikdtree.Nearest_Search(point_world, 5, near, d);  // kNN, inside the measurement step
```

On the authors' benchmarks FAST-LIO2 spends less time per scan than FAST-LIO while holding a
larger map, on both Intel and Arm:

<Figure
  src="https://media.thesatyajit.com/ai/articles/fastlio2/x6.png?v=21e6cb77efe3d0af"
  alt="Processing time per LiDAR scan over time for FAST-LIO and FAST-LIO2 on Intel and Arm CPUs (log scale, top), and the number of map points held over time (bottom); FAST-LIO2 is consistently faster while keeping more map points."
  caption="Per-scan processing time: FAST-LIO2 (cyan and red) stays below FAST-LIO (green and purple) on both Intel and Arm while the bottom panel shows it holding a larger map (FAST-LIO2 paper, Figure 8)."
/>

The README's own recordings show what that buys. On the UrbanLoco sequence, a Velodyne HDL-32E
at 10 Hz, the overlay reads an average of 31 ms per scan on an Intel i7 and 92 ms on an Arm
board; on a Livox Avia at a 100 Hz scan rate, 1.82 ms and 5.23 ms:

<Video
  src="https://ai.satyajit.si/articles/fastlio2/clip1"
  poster="https://media.thesatyajit.com/ai/articles/fastlio2/clip1-poster.jpg?v=93778ba94f376301"
  alt="FAST-LIO2 mapping the UrbanLoco HK20190426-2 sequence at 20x replay: a Velodyne HDL-32E scan in white over the accumulated coloured map of streets and buildings, with the trajectory drawn in cyan and an overlay reading average processing time Intel i7 31 ms, ARM 92 ms."
  caption="FAST-LIO2 on UrbanLoco (Velodyne HDL-32E, 10 Hz; Xsens IMU, 100 Hz), replayed at 20x. The timings in the overlay are the authors' (hku-mars/FAST_LIO README animation, GPL-2.0)."
/>

<Video
  src="https://ai.satyajit.si/articles/fastlio2/clip2"
  poster="https://media.thesatyajit.com/ai/articles/fastlio2/clip2-poster.jpg?v=035a975dddc16ce2"
  alt="FAST-LIO2 running on a Livox Avia scanning at 100 Hz, replayed at 10x: the current scan in white and the historical raw points in colour along a long outdoor structure, with an overlay reading average processing time Intel i7 1.82 ms, ARM 5.23 ms."
  caption="FAST-LIO2 with a Livox Avia at a 100 Hz scan rate, replayed at 10x; white is the current scan, colour all historical raw points. Overlay timings are the authors' (hku-mars/FAST_LIO README animation, GPL-2.0)."
/>

## Dropping ROS

The main loop is shorter than the repository suggests:

```cpp
while (running) {
  if (sync_packages(Measures)) {                  // group IMU + one LiDAR scan by time
    p_imu->Process(Measures, kf, feats_undistort); // forward-propagate + deskew
    downSizeFilterSurf.filter(*feats_down_body);   // voxel-downsample the scan
    kf.update_iterated_dyn_share_modified(         // the iterated point-to-plane EKF
        LASER_POINT_COV, feats_down_body, ikdtree, Nearest_Points,
        NUM_MAX_ITERATIONS, extrinsic_est_en);
    state_point = kf.get_x();                      // odometry output
    map_incremental();                             // ikdtree.Add_Points(...)
  }
}
```

`sync_packages` only aligns two streams in time. The publishers, `tf` and the subscribers are
ROS. None of that is the filter, so reproducing FAST-LIO2 without ROS needs a reader for IMU
samples, a reader for points with per-point times, the propagation and deskew, a k-d tree over
the map, and the iterated update. That is the whole port:

```python
x, P = init_state(), init_cov()
ikdtree = KDMap(voxel=0.5)                 # or scipy cKDTree to begin with
for scan in lidar_scans:                   # each: points + per-point timestamps
    imu_batch = imu_between(prev_t, scan.t_end)
    for imu in imu_batch:                  # 1) forward propagation
        x, P = predict(x, P, imu, imu.dt, Q)
    pts = deskew(scan.points, imu_poses, x)        # 2) backward propagation
    pts = voxel_downsample(pts, 0.5)               # 3) downsample
    x, P = update_iterated(x, P, pts, ikdtree, ikdtree.points)  # 4) iterated EKF
    ikdtree.add(transform_to_world(pts, x))        # 5) grow the map
    yield x.p, x.R                                 # pose = odometry
```

The file-to-concept map for the clean C++ version:

| File | What it owns |
|---|---|
| `use-ikfom.hpp` | the state manifold, `get_f`, `df_dx`, `df_dw` |
| `esekfom.hpp` | the explicit ESEKF: `predict`, `h_share_model`, `update_iterated_dyn_share_modified`, the reformulated gain |
| `IMU_Processing.hpp` | IMU init, forward propagation, `UndistortPcl` (deskew) |
| `ikd_Tree.cpp` | `Build`, `Add_Points`, `Delete_Point_Boxes`, `Nearest_Search` |
| `laserMapping.cpp` | the ROS glue and main loop (the part you replace) |

I wrote the port as one file, [`fastlio2_mini.py`](https://ai.satyajit.si/articles/fastlio2/fastlio2_mini.py)
(about 390 lines; `numpy`, `scipy`, `rosbags`), printed in full at the end. It has the
on-manifold state (15-dimensional: no extrinsic or gravity in the state), forward and backward
propagation, the iterated point-to-plane update with the information-form gain, a LiDAR-to-IMU
extrinsic and per-scan voxel downsampling. Two simplifications matter for what follows. Gravity
is fixed from the first moments of IMU data and never re-estimated. And the map is the last
60,000 points in a `scipy` `cKDTree` rebuilt every scan, not an ikd-Tree: there is no sliding
cube, the oldest points simply fall off. It ships with a synthetic room and passes on it
(3.7 cm ATE in memory, 6.9 cm through a written-and-reread ROS bag). It tracked the HKU Livox
Avia "quick-shack" bag: 491 scans, 47.4 rad of cumulative rotation over 38 m of path, back to
within about 0.6 m of its start.

<Figure
  src="https://media.thesatyajit.com/ai/articles/fastlio2/avia-trajectory.png?v=4dcb0068c0207a25"
  alt="Two plots from running fastlio2_mini on the HKU Livox Avia bag: a top-down view showing the estimated path (colored by time) tracing through a reconstructed room point cloud, and a side x–z view; the path stays bounded within the room rather than collapsing or diverging."
  caption="fastlio2_mini on the HKU Livox Avia bag (491 scans, 49 s). Left, the top-down path coloured by scan time over the reconstructed room; right, the x–z side view. A handful of stray points are cropped from the wide view."
/>

It did not track on the first try. Three fixes got it there, and none of them was the filter
math.

### Bug 1: a sensor-clock mismatch, and the filter never moved

The first run froze within a few centimetres of the origin while the IMU showed the sensor
swinging at about 1 rad/s. I nearly blamed the filter. The scan timestamps were landing at
$t \approx -1.6\times10^9$ relative to the IMU. The Livox `CustomMsg` header stamps each scan on
the sensor's own clock (seconds since the LiDAR booted, about 361 s into this bag), and the
`/livox/imu` messages carry the bag's record clock (Unix time, about 1.6 billion). My
propagate-up-to-scan-end loop compared the two:

```python
while imu_stream[imu_i][0] <= scan['t_end']:   # IMU time vs LiDAR header time
    kf.predict(...)                            # ...never true → never runs
```

Every IMU stamp was larger than every scan stamp, so the IMU never propagated. The update kept
snapping each scan onto an origin-seeded map, and the result looked like a data-association
collapse. The fix was to ignore the Livox header and stamp each scan with the bag record time,
which `rosbags` gives for every message on one clock:

```python
for conn, t, raw in reader.messages(connections=conns):   # t = bag record time (ns)
    ...
    lidar_scans.append({'t_end': t * 1e-9, 'points': pts, 'dts': dts})  # not msg.header!
```

Check the clocks first. An epoch or unit mismatch looks exactly like a modelling failure, and
it can cost a day of tuning covariances that were never the problem. While there I also wired
in the calibration a real run needs: the LiDAR-to-IMU extrinsic from `avia.yaml`, the real IMU
noise (`acc_cov = gyr_cov = 0.1`; my synthetic `Q` was 100 times too small), and per-scan voxel
downsampling.

The benchmark below ran into the same class of bug from the other side. The Hesai bags store each
point's time as an absolute `float64` `timestamp`, while my `read_bag()` assumed per-point offsets
and scales anything over 1 s as nanoseconds or microseconds. Fed a Hesai bag directly, the port
would have treated 1.6 billion seconds as an offset and deskewed every point into nonsense. The
benchmark's converter reads the field type, subtracts the earliest point time, and prints what it
decided before anything runs.

### Bug 2: a stub deskew, and the walls doubled

It moved, but every wall came out twice, slightly rotated. My first `deskew` dropped each point
into the nearest cached IMU pose with no compensation across the sweep. A Livox sweep takes
100 ms, and at about 1 rad/s a point 3 m away moves 30 cm in that time. Interpolating the
propagated trajectory to each point's capture time (rotation on $SO(3)$, position linearly) and
carrying the point to the scan-end frame, which is the backward propagation from earlier,
collapsed the doubled walls into one and brought the per-plane thickness of the map down to
about 4 cm.

### Bug 3: an outlier gate that starved the update

With deskew fixed it tracked for about 150 scans and then ran off in a straight line, which is
what a LIO does when the LiDAR stops correcting it and the IMU dead-reckons. I had copied
FAST-LIO's range-normalised gate (`s = 1 − 0.9|d|/√range`). On FAST-LIO's dense clouds that is
fine. On my sparse, voxel-downsampled scans, the moment the prediction was slightly off it
rejected every correspondence, the update was skipped, and nothing pulled the pose back. A plain
metric gate with a mild range allowance keeps hundreds of inliers per scan. Watch the inlier
count, not only the residual.

## Measured: four systems on two sequences

<Callout type="note">
These runs went through ROS 2 bag playback on an RTX 3090 box. The [LIO shootout](/articles/lio-shootout)
later re-ran FAST-LIO2 and Super-LIO, plus fifteen more systems, without ROS on one 28-core machine and on
four sequences, including a Hilti stair walk where FAST-LIO2 and Super-LIO both diverged.
</Callout>

### What I ran, and how it was scored

Two sequences, chosen because each has a reference trajectory made without any of the systems
under test, and each is small enough to download:

- **Hilti SLAM Challenge 2022, `exp14_basement_2`.** A handheld rig with a Hesai PandarXT-32
  and a 400 Hz Bosch IMU, walked for 74 s through the basement of a construction site, down
  about 3 m and back up. 740 sweeps, about 60,000 points each. The reference is the dataset's dense
  IMU-frame trajectory, ICP against a terrestrial laser scan; I scored that reference against
  the surveyed floor marks in [the Hilti article](/articles/hilti-slam-dataset) and it agreed
  to 6.7 mm on this sequence. The reference path is 37.7 m. The median LiDAR return is only
  1.08 m away.
- **Oxford Spires, `2024-03-12-keble-college-03`.** A backpack rig with a Hesai QT64 and a
  400 Hz IMU, 286 s round a college quad and back. 2,867 sweeps, 282.9 m of reference path,
  median return 5.6 m away. The reference is scan-to-TLS ICP, which the dataset paper puts at
  1 to 2 cm.

(The Hilti 2026 challenge, the newest the site has read about, releases only cameras and IMU,
not the LiDAR, so it cannot be used for this.)

Everything ran on beast2, an Intel i7-6850K (12 threads), from one script. The things that
make a comparison like this meaningless are frames, clocks and inputs, so I fixed those once:

- **One input for everyone.** A converter read each ROS 1 bag and wrote a ROS 2 bag with the
  points already moved into a levelled IMU frame (so every system runs with an identity
  extrinsic) and a per-point `time` field taken from the Hesai `timestamp` of each point,
  never from the message header. It also checked the LiDAR-to-IMU rotation: after levelling,
  the spin axis of the LiDAR points within 1.4 degrees of vertical on Hilti and 8.8 degrees on
  Spires (a backpack that leans), as a rig at rest should.
- **Each system as shipped.** FAST-LIO2 with its Velodyne config (0.5 m scan and map voxels,
  3 iterations), Super-LIO with its Hesai config (0.5 m voxels, 4 iterations), FAR-LIO with its
  `far-lio.yml` (4 m voxels), plus a second FAR-LIO run with 1 m voxels. Matched across all of
  them: the blind radius (0.5 m on Hilti, 1 m on Spires), a 100 m range cap, and the IMU noise.
- **Same machine budget.** Each system pinned to the same four hardware threads, the bag player
  to four others, playback at half speed so nothing drops a scan for lack of time.
- **One scoring script.** Each pose is stamped at the time it is valid, moved into the
  reference's frame (Spires' reference is a `base` frame 4 cm from the IMU, so the lever arm is
  applied rather than left to the alignment), the reference is interpolated at the estimate's
  stamps, and one SE(3) Umeyama fit without scale aligns the two. ATE is the RMS position error
  after that fit; RPE is evo's, over every metre of path. Coverage is how much of the reference
  the matched poses span.
- **Time per scan** is each system's own work for one scan: IMU propagation through map insert
  for FAST-LIO2 and Super-LIO, the registration callback for FAR-LIO, wall time per scan for the
  Python port. Peak RSS is the process's high-water mark.

FAR-LIO ran on its CPU build. Its CUDA build failed on beast2 in all three attempts, so the
FAR-LIO times here are its CPU GICP with the shipped `num_threads: 1`, not the GPU pipeline the
paper measures, and its accuracy is the accuracy of the same algorithm on a CPU.

### The results

<LioBench />

<Figure
  src="https://media.thesatyajit.com/ai/articles/fastlio2/bench-trajectories.png?v=2992b085ffd09ea1"
  alt="Two top-down plots. Left, Hilti 2022 exp14 basement: the grey reference path, with Super-LIO (ATE 9.3 cm) close to it and FAST-LIO2 (ATE 50.1 cm) visibly off around the left end, FAST-LIO2 without deskew at 25.3 cm and FAR-LIO with 1 m voxels at 25.8 cm. Right, Oxford Spires Keble College 03: a loop of about 70 by 70 m where the Python port over its first 39 percent (3.3 cm), FAST-LIO2 (7.2 cm), Super-LIO (8.0 cm), FAR-LIO with 4 m voxels (22.9 cm) and FAST-LIO2 without deskew (30.8 cm) all lie on the reference."
  caption="Aligned trajectories from my runs, one sample per second, against each dataset's reference. Runs whose ATE passed 1 m are left off: FAR-LIO with 4 m voxels and the Python port on Hilti, FAR-LIO with 1 m voxels on Spires."
/>

On **Spires**, FAST-LIO2 does what the paper says it does: 7.2 cm ATE over 283 m, 0.19 degrees
of rotation error per metre, 12.7 ms a scan on four threads with a 95th percentile of 20.9 ms,
and 277 MB of memory. For scale, the Spires paper's own Table 3 gives 0.11 m on this sequence for
Fast-LIO-SLAM (FAST-LIO2 plus loop closure), 0.14 m for VILENS-SLAM and 0.06 m for Fast-LIVO2,
which also uses the cameras. Pure odometry beating the paper's loop-closed variant is not what I
expected. The likely reasons are the lever arm, which their script leaves to the alignment, and
configuration, but I have not reproduced their run, so I would not read more into it than "my
FAST-LIO2 numbers are in the right range".

Super-LIO lands at 8.0 cm on the same walk, within a centimetre of FAST-LIO2, at **5.6 ms a scan**
(2.3 times faster) and **170 MB**. Its map holds 363,371 points against FAST-LIO2's 85,765, because
OctVox keeps up to eight averaged points per 0.5 m voxel where the ikd-Tree keeps one, and it still
uses less memory: a hash of small fixed-size cells costs less than a tree of nodes that carry a
bounding box, counts and labels each.

FAR-LIO on its CPU build reaches 22.9 cm at 45.7 ms a scan. With 1 m voxels it fell apart: per-scan
time rose to 256 ms, past the 100 ms between sweeps and past its own 200 ms registration budget, it
fell behind and processed 2,089 of 2,867 scans, and the trajectory ran off by kilometres. The map
reached 1,851,856 points and the process 1,635 MB.

On **Hilti** the order changes and two results look backwards.

| Hilti exp14 | ATE | RPE per metre | ms per scan | map |
|---|---|---|---|---|
| Super-LIO | **9.3 cm** | 4.8 cm, 0.79° | **1.46** | 17,978 points |
| FAR-LIO, 1 m voxels (CPU) | 25.8 cm | 21.5 cm, 2.79° | 25.1 | 13,631 points |
| FAST-LIO2, deskew off | 25.3 cm | 10.0 cm, 3.28° | 2.90 | 5,646 points |
| FAST-LIO2 | 50.1 cm | 22.0 cm, 2.04° | 3.56 | 5,361 points |
| FAR-LIO, 4 m voxels (CPU) | 2.78 m | 66.0 cm, 4.92° | 8.58 | 809 points |
| Python port | 10.3 m | 97.1 cm, 6.65° | 3,530 | 60,000 points |

### Why FAST-LIO2 loses the basement

The first oddity is FAST-LIO2 at 50 cm, five times Super-LIO, on a 38 m walk, in a
dataset where the 2022 challenge's top LiDAR-inertial entries scored 1 to 2 cm on the open
construction sequences. The map column is
the clue. With the shipped Velodyne settings the ikd-Tree keeps one point per 0.5 m cube, and in a
basement whose walls are a metre away that is 5,361 points for the whole level, 191 of them after
the first scan. A plane fitted to the five nearest neighbours of a point then spans a metre or
more of wall, ceiling and corner, so many fits fail the 0.1 m flatness test and the ones that pass
are coarse. Super-LIO uses the same 0.5 m voxel but keeps eight representatives in each, about
0.25 m spacing, and holds 17,978 points: the same room, sampled finely enough to fit planes to.
The Velodyne config was written for a car-mounted sensor seeing walls tens of metres away. Indoors,
FAST-LIO2 is normally run with 0.2 to 0.3 m voxels, and I expect it to recover most of the gap
there; that run is the next one I would do, and I have not done it.

The second oddity is that switching deskew *off* halves FAST-LIO2's ATE on Hilti (25.3 cm against
50.1 cm), the opposite of Spires. Look at the rotation column: with deskew the rotation error is
2.04 degrees per metre, without it 3.28. Deskew makes each scan more correct, as it should. But
both runs are drifting in an under-resolved map, and ATE after one global fit is a single draw of
how that drift happened to accumulate: the deskewed run's error sits around 30 to 40 cm from the
start and grows to 80 cm in the last 20 s, the other wanders down to 4 cm in the middle and back up
to 34 cm. On a 74 s sequence with a failing map, the ATE difference between the two is noise, and
I would not use this pair to say anything about deskew. Spires, where both runs track, is the
clean test.

FAR-LIO's voxel result flips between the two sequences for a reason that is in its design. Its map
is a hash of large voxels, up to 40 points each, and every scan point's covariance comes from its
10 nearest neighbours in the 27 voxels around it. In a basement with returns a metre away, 4 m
voxels put most of the room in a handful of cells: the map held 809 points at the end, too few for
the covariances GICP needs, and the registration lost track (2.78 m). One-metre voxels fit the room
and it tracked to 25.8 cm. Outdoors the same 1 m voxels on a 100 m range cap multiply the map and the
neighbour search until the CPU build cannot keep up, while 4 m voxels are right for the scene. The
paper's claim of one parameter set from a residential street to a race track is a claim about
vehicle-scale scenes; a basement is not one of them, and neither was its test set.

### The Python port

The article's own port, run unchanged, is the slowest thing here by three orders of magnitude:
3.5 s a scan on Hilti and 4.8 s on Spires, against 12.7 ms for FAST-LIO2. Its deskew is a Python
loop over 60,000 points per scan and its map is a `cKDTree` rebuilt from the last 60,000 points
every scan. Under its 90-minute budget on Spires it got through 1,131 scans, the first 39% of the
walk, 91.5 m, at **3.3 cm ATE** under its own alignment, with a rotation error of 0.21 degrees
per metre against FAST-LIO2's 0.19. On Hilti it diverged early and never recovered (10.3 m).

I have not traced the Hilti failure to one line. The likeliest suspect is its map: a FIFO of the
newest 60,000 points with no notion of space, so in a small room the oldest, best-registered
structure is the first thing it throws away, and the outlier gate from Bug 3 lets in more of the
near-field clutter a basement is full of. The start was not the problem: its static first second
had an accelerometer spread of 0.015 m/s² per axis. The 3.3 cm on Spires is also
flattered by the window: an alignment fitted to 112 s has less drift to absorb than one fitted to
286 s.

## What came after FAST-LIO2

FAST-LIO2's filter has barely changed in the five years since. What its successors change is
the map, the threading, and on fast vehicles, where the registration runs.

**The map moved from a tree to a hash.** [Faster-LIO](https://github.com/gaoxiang12/faster-lio)
(Bai et al., RA-L 2022) replaced the ikd-Tree with iVox, a hash table of voxels with a small
fixed neighbourhood search. A hash lookup has no depth and no rebalancing, and the points of a
voxel sit together in memory. The cost moves into the search: the true nearest neighbour can sit
just outside the fixed stencil of voxels that gets examined, and the work per query depends on how
many points each voxel has collected.

**Super-LIO bounds that.** Its OctVox map splits each voxel into 2 × 2 × 2 subvoxels and keeps one
running mean per subvoxel, so a voxel never holds more than eight points and repeated hits on the
same surface average its noise down. Its HKNN search precomputes, once, the order in which to visit
neighbouring subvoxels by distance, and stops as soon as no remaining group can hold a closer point.
The filter is FAST-LIO2's IESKF.

<Figure
  src="https://media.thesatyajit.com/ai/articles/fastlio2/superlio-overview.png?v=d5e8713443f1c19d"
  alt="Super-LIO overview: LiDAR feeds undistortion, center-based downsampling and HKNN matching; the IMU feeds IESKF prediction, which also drives undistortion; HKNN residuals feed the IESKF update, which outputs odometry at LiDAR frequency and updates an OctVox map drawn as a voxel split into eight subvoxels with one green representative point in each occupied one."
  caption="Super-LIO keeps FAST-LIO2's loop (IMU prediction, undistortion, point-to-plane residuals, IESKF update) and swaps the map for OctVox, at most eight averaged representatives per voxel, searched by HKNN (Super-LIO paper, Figure 2)."
/>

The paper's headline is about 73% faster per frame than the state of the art at competitive
accuracy. Its Table II is more specific, and more useful. On the authors' x86 laptop, averaged over
seven groups of sequences, FAST-LIO2 takes 10.90 ms a frame and Super-LIO 2.99 ms. The same table
has a column for FAST-LIO2*, the authors' port of FAST-LIO2 from OpenMP to Intel TBB with the
algorithm unchanged, and it takes 5.67 ms. So of the 3.6x between FAST-LIO2 and Super-LIO, about 1.9x
is threading (10.90 to 5.67) and about 1.9x is the map and search (5.67 to 2.99). Accuracy over 19
sequences averages 0.738 m for Super-LIO and 0.809 m for FAST-LIO2 in its Table I; per sequence the
two trade places, FAST-LIO2 is better on six of them, and the authors played every bag at five times
real time.

<Figure
  src="https://media.thesatyajit.com/ai/articles/fastlio2/superlio-frametime.png?v=b9388cfac00c6b43"
  alt="Per-frame processing time over about 67,000 frames of the NCLT 1 sequence, smoothed every 50 frames: Fast-LIO2 is highest, between about 8 and 22 ms, Faster-LIO next, Fast-LIO2* (TBB) around 7 to 10 ms, iG-LIO around 5 to 7 ms, and Super-LIO and Super-LIO* lowest, around 3 to 6 ms."
  caption="Smoothed per-frame time on NCLT 1 for six systems, including FAST-LIO2* (FAST-LIO2 with TBB threading instead of OpenMP), which closes much of the gap on its own (Super-LIO paper, Figure 9)."
/>

**FAR-LIO moves the registration to a GPU.** Built for an autonomous race car at 250 km/h, it drops
both the iterated filter and the tree: a CUDA voxel hashmap with 4 m voxels and adaptive density, a
sparsity-aware GICP solved on the GPU, and a small kinematic EKF on the CPU that upsamples the IMU and
extrapolates the registration's own delay. I went through it in the [FAR-LIO article](/articles/far-lio).
On its racing data it is 19.23 ms a scan using about a fifth of an RTX A5000 and beats FAST-LIO2 on two of
three race sequences; on Monza, FAST-LIO2's 262.16 m APE is better than FAR-LIO's 297.39 m. It also
calibrates the IMU biases once at standstill instead of estimating them, and its EKF has a vehicle
model. A handheld walk is outside what it was designed for, which is what I tested it on.

<Figure
  src="https://media.thesatyajit.com/ai/articles/far-lio/fig2.png?v=95bd5e7302e70932"
  alt="FAR-LIO architecture overview: a green GPU LiDAR Scan Pipeline (Preprocessing and Undistortion, then GICP-Registration built from Cov-Calc on the cuVoxelMap, kNN-Search, and Least-Squares Optimization, against an Adaptive Local Submap) feeds registered pose and velocity into a blue CPU Sensor Fusion block (Delay-Compensation and a Kinematic Extended Kalman Filter) that also takes IMU accelerations and angular velocities and outputs position, orientation and velocity."
  caption="FAR-LIO splits the job: registration on the GPU (green), a small delay-compensating EKF on the CPU (blue) whose pose is fed back as the next scan's initial guess (FAR-LIO docs, architecture overview)."
/>

**Others kept the filter and shrank it.** [Point-LIO](https://github.com/hku-mars/Point-LIO) (same
lab) updates the state point by point instead of scan by scan, for motion past the IMU's range. The
[Mobile SLAM app](/articles/mobile-slam-iphone) runs FAST-LIO's filter on an iPhone with a 15-dimensional
error state, fixed gravity and a never-trimmed hash of 0.2 m voxels, which is close to the shape of
my Python port with a better map. [α-LiDAR](/articles/alpha-lidar) keeps this filter and this
deskew almost line for line, swaps the map for VoxelMap's planes with a covariance on every return,
and puts the LiDAR and its IMU on a gimbal motor that turns them through the whole sphere.

**Does any of it pay on these two walks?** Super-LIO's map does. It matched FAST-LIO2 within a
centimetre outdoors at 44% of the time and 61% of the memory, and in the basement it was the only
system that worked with its shipped settings, because a voxel that keeps eight points instead of
one is fine enough for a room without being retuned. Its paper's 3.7x over FAST-LIO2 came out as
2.3x here, which fits its own Table II: about half of that gap is FAST-LIO2's OpenMP threading.
FAR-LIO's ideas did not get a fair test: without its GPU build I measured its algorithm on one CPU
thread, and its scene-scale voxels need choosing per place, which is the opposite of what it was
designed to remove on a race track.

## Where the site picks it up

Ten later pieces on this site lean on this one, and each picks up a different part of the
loop:

- [Voxel-SLAM](/articles/voxel-slam) is this lab's full SLAM system: a FAST-LIO2-style filter as
  its odometry, then a 10-scan bundle adjustment on planes, loop closure and a global BA, built
  without ROS and run through the same kind of harness.
- [PV-LIO](/articles/pv-lio) keeps this filter and swaps the ikd-Tree for VoxelMap's planes, each
  residual weighted by its variance instead of `LASER_POINT_COV`; built without ROS, it tracks the
  basement above to 3.95 cm with the repo's Hilti config.
- [FAR-LIO](/articles/far-lio) is the GPU rethink above: the same problem at 250 km/h, with the
  registration on CUDA and a delay-compensating EKF.
- [The Hilti SLAM datasets](/articles/hilti-slam-dataset) explains how the reference I scored
  against in the basement is made (a terrestrial scan, ICP to it, a steel tip on surveyed floor
  crosses) and why its dense trajectory is good to a couple of centimetres, not to a millimetre.
  FAST-LIO2 variants placed in all three editions of that challenge.
- [GTSAM 4.3](/articles/gtsam-4-3) is the smoothing side of the same maths: the iterated update
  here is Gauss-Newton on one pose; a factor graph does it over a window and relinearises the past.
- [The open robotics mapping roundup](/articles/open-robotics-mapping-roundup) has the Calibrex
  deskew clip, where a wrong LiDAR-to-IMU extrinsic smears every sweep before the filter sees it,
  which is the deskew section's failure mode in a real calibration.
- [MetricTrail](/articles/metrictrail) gets its scale from a depth prior on video, the camera route
  to odometry; this is the route where the sensor measures metres directly.
- [SurfSLAM](/articles/surfslam) integrates an IMU between keyframes with GTSAM's preintegration
  factor, the batch cousin of the forward propagation above.
- [Mobile SLAM on an iPhone](/articles/mobile-slam-iphone) rewrites FAST-LIO's filter in about
  1,180 lines of C++ for a Livox Mid-360, with a fixed-gravity, 15-dimensional error state and a
  hash-voxel map, which makes it the closest relative of the Python port here.
- [Accord](/articles/accord-metric-mapping) is the camera route to a dense metric map: an OpenVINS
  filter, not a LiDAR filter, supplies the metres, and a depth model the surfaces.

## What I would use

For a handheld or backpack scanner today I would start with Super-LIO: same filter as FAST-LIO2,
the same accuracy where both work, half the time, less memory, and a map that degrades gracefully
when the room gets small. I would still learn the filter from FAST-LIO2, because every system here
except FAR-LIO is FAST-LIO2's IESKF with a different map, and the mathematics above is the part that
transfers. Whichever one you run, set the map voxel for the space: 0.5 m with one point per voxel is
a car's setting, and in a basement the shipped one left
FAST-LIO2 five times behind Super-LIO. And keep the deskew. The
cheapest experiment in this article, one `if` around a loop, was worth 24 cm of ATE on an ordinary
walk.

None of these is a scanner. On Spires the best odometry is still 7 cm off after 283 m with no loop
closure, which is fine for a robot and not fine for checking an anchor hole against a drawing. For
that you close loops and register to control points, which is what
[the Hilti datasets](/articles/hilti-slam-dataset) grade.

## Notes on the method

- **What I ran:** every number in the benchmark section and both widgets that use it: four
  systems, two sequences, one beast2 script, four runs. The first two failed in setup (package
  metadata, then a glog 0.7 header change), the third lost the Hilti download partway, and FAR-LIO's
  CUDA build failed every time. The
  per-sweep rotation rates and timings in the deskew widget come from the same run's converter.
- **What I read:** the FAST-LIO2, ikd-Tree, Super-LIO and FAR-LIO papers and code at the pinned
  commits (`hku-mars/FAST_LIO` ROS2 branch `cc3c9e8`, `Super-LIO` `f89f48d`, `FAR-LIO` `ef20510`),
  and S-FAST_LIO for the quoted C++. The 31 ms, 92 ms, 1.82 ms and 5.23 ms in the clips, the
  Super-LIO tables and the Spires paper's Table 3 are the authors' numbers.
- **What I changed in the systems:** one `printf` per scan in each, for pose, time and map size;
  an environment switch around FAST-LIO2's deskew loop; a stub `livox_ros_driver2` message package,
  because FAST-LIO2 and Super-LIO both depend on it for a sensor I did not use; FAST-LIO2 built as
  C++17 instead of C++14 so it compiles against ROS 2 Jazzy.
- **What is not settled:** FAST-LIO2 indoors at a smaller voxel; FAR-LIO on its GPU; the Python
  port over all of Spires (it would take about four hours); and why the port diverged in the
  basement.

## The whole file

The port in full (393 lines). It is deliberately unoptimised for reading: a `cKDTree` rebuilt
per scan and plain Python loops. Expand it to read or copy it, or
[download it](https://ai.satyajit.si/articles/fastlio2/fastlio2_mini.py):

<CodeCollapse label="fastlio2_mini.py, the whole file" collapsedHeight={460}>

```python
"""
fastlio2_mini.py — a minimal, ROS-free FAST-LIO2-style LiDAR-inertial odometry.

A teaching reimplementation of the FAST-LIO2 core: an iterated error-state Kalman
filter on SO(3), fed a high-rate IMU and corrected by raw point-to-plane LiDAR
residuals over an incremental k-d-tree map. It supports a LiDAR->IMU extrinsic and
per-scan voxel downsampling; the simplifications vs. the paper (called out where
they matter) are gravity fixed after init and a scipy cKDTree rebuilt per scan
instead of a true ikd-Tree. Everything else — the manifold state, forward/backward
propagation, the reformulated Kalman gain — is faithful.

    pip install numpy scipy rosbags
    python fastlio2_mini.py                 # runs a synthetic demo (no bag needed)
    python fastlio2_mini.py avia.bag        # runs a real Livox Avia bag (calibrated)
    # or: from fastlio2_mini import read_bag, run_offline

Validated: ~4 cm ATE on an 8 s synthetic trajectory, and it tracks the real HKU
Livox Avia bag (491 scans, ~50 s) — see run_offline's calibration arguments.
"""
import numpy as np
from scipy.spatial import cKDTree

# ============================================================ SO(3) utilities
def hat(w):                                   # vector -> skew-symmetric matrix
    return np.array([[0, -w[2], w[1]], [w[2], 0, -w[0]], [-w[1], w[0], 0]])

def Exp(w):                                   # so(3) -> SO(3)  (Rodrigues)
    th = np.linalg.norm(w)
    if th < 1e-9:
        return np.eye(3) + hat(w)
    K = hat(w / th)
    return np.eye(3) + np.sin(th) * K + (1 - np.cos(th)) * K @ K

def Log(R):                                   # SO(3) -> so(3)
    c = np.clip((np.trace(R) - 1) / 2, -1, 1)
    th = np.arccos(c)
    v = np.array([R[2, 1] - R[1, 2], R[0, 2] - R[2, 0], R[1, 0] - R[0, 1]])
    return 0.5 * v if th < 1e-9 else (th / (2 * np.sin(th))) * v

# ============================================================ state on the manifold
# error-state layout (15): [ p(0:3) th(3:6) v(6:9) bg(9:12) ba(12:15) ]
class State:
    def __init__(s):
        s.p = np.zeros(3); s.R = np.eye(3); s.v = np.zeros(3)
        s.bg = np.zeros(3); s.ba = np.zeros(3)
    def copy(s):
        t = State()
        t.p, t.R, t.v, t.bg, t.ba = s.p.copy(), s.R.copy(), s.v.copy(), s.bg.copy(), s.ba.copy()
        return t

def boxplus(x, d):                            # x ⊞ d  (retract onto the manifold)
    y = x.copy()
    y.p += d[0:3]; y.R = x.R @ Exp(d[3:6]); y.v += d[6:9]
    y.bg += d[9:12]; y.ba += d[12:15]
    return y

def boxminus(a, b):                           # a ⊟ b  (tangent so that a = b ⊞ d)
    d = np.zeros(15)
    d[0:3] = a.p - b.p; d[3:6] = Log(b.R.T @ a.R); d[6:9] = a.v - b.v
    d[9:12] = a.bg - b.bg; d[12:15] = a.ba - b.ba
    return d

# ============================================================ the filter
class ESEKF:
    def __init__(s, g):
        s.x = State(); s.P = np.eye(15) * 1e-2; s.g = g.copy()

    def predict(s, am, wm, dt, Q):
        """Forward propagation: integrate one IMU sample, inflate covariance."""
        x = s.x
        w = wm - x.bg                          # de-biased angular velocity
        a = x.R @ (am - x.ba) + s.g            # de-biased, gravity-corrected accel (world)
        # --- nominal mean ---
        x.p = x.p + x.v * dt + 0.5 * a * dt * dt
        Rn = x.R @ Exp(w * dt)
        x.v = x.v + a * dt
        x.R = Rn
        # --- error-state transition F_x and noise map F_w (paper Eq. 7/8) ---
        A = np.zeros((15, 15))
        A[0:3, 6:9] = np.eye(3)                # dp/dv
        A[3:6, 3:6] = -hat(w); A[3:6, 9:12] = -np.eye(3)      # dth/dth, dth/dbg
        A[6:9, 3:6] = -x.R @ hat(am - x.ba); A[6:9, 12:15] = -x.R   # dv/dth, dv/dba
        Fx = np.eye(15) + A * dt
        Fw = np.zeros((15, 12))
        Fw[3:6, 0:3] = -np.eye(3); Fw[6:9, 3:6] = -x.R
        Fw[9:12, 6:9] = np.eye(3); Fw[12:15, 9:12] = np.eye(3)
        s.P = Fx @ s.P @ Fx.T + (Fw * dt) @ Q @ (Fw * dt).T

    def update(s, pts_body, lmap, R=1e-3, max_iter=4, eps=1e-3):
        """Iterated point-to-plane update with the reformulated Kalman gain."""
        x_prior = s.x.copy()
        n = 15; K = None; Hfull = None
        for _ in range(max_iter):
            x = s.x
            pw = (x.R @ pts_body.T).T + x.p     # body -> world at current estimate
            H_rows, z = [], []
            for i in range(len(pts_body)):
                nrm, off, ok = lmap.fit_plane(pw[i])    # nearest-5 plane via kd-tree
                if not ok:
                    continue
                r = nrm @ pw[i] + off          # point-to-plane distance
                # FAST-LIO weights acceptance by range (`s = 1 - 0.9|d|/sqrt(range)`),
                # but on a sparse, voxel-downsampled scan that gate can starve a slightly-
                # off prediction of *all* correspondences — the update is then skipped and
                # the pose dead-reckons away. We keep a plain metric gate (correct deskew
                # already removes the smear a tight gate was meant to fight) with a mild
                # range allowance so far points must still fit reasonably.
                rng = np.linalg.norm(pts_body[i])
                if abs(r) > 0.3 + 0.05 * rng:
                    continue
                Hr = np.zeros(15)
                Hr[0:3] = nrm
                Hr[3:6] = hat(pts_body[i]) @ (x.R.T @ nrm)   # d(residual)/d(theta)
                H_rows.append(Hr); z.append(r)
            if len(H_rows) < 10:
                break
            H = np.array(H_rows); z = np.array(z)
            dx_prior = boxminus(s.x, x_prior)
            # reformulated gain: invert a 15x15 (state), NOT an mxm (measurements)
            S = H.T @ H / R + np.linalg.inv(s.P)
            K = np.linalg.solve(S, H.T) / R    # K = (H'R^-1 H + P^-1)^-1 H' R^-1
            Hfull = H
            dx = -K @ z - (np.eye(n) - K @ H) @ dx_prior
            s.x = boxplus(s.x, dx)
            if np.max(np.abs(dx)) < eps:
                break
        if K is not None:
            s.P = (np.eye(n) - K @ Hfull) @ s.P

# ============================================================ map (stand-in for ikd-Tree)
class LocalMap:
    def __init__(s, voxel=0.4, cap=60000):
        s.voxel = voxel; s.cap = cap; s.pts = None; s.tree = None
    def add(s, world_pts):
        s.pts = world_pts if s.pts is None else np.vstack([s.pts, world_pts])
        if len(s.pts) > s.cap:
            s.pts = s.pts[-s.cap:]
        s.tree = cKDTree(s.pts)                # a real ikd-Tree updates in place instead
    def fit_plane(s, p, k=5, max_d=1.0, thick=0.1):
        d, idx = s.tree.query(p, k=k)
        if d[-1] > max_d:
            return None, None, False
        near = s.pts[idx]; c = near.mean(0)
        _, _, Vt = np.linalg.svd(near - c)     # smallest singular vector = normal
        nrm = Vt[2]
        if np.max(np.abs((near - c) @ nrm)) > thick:
            return None, None, False           # neighbours aren't planar enough
        return nrm, -nrm @ c, True

# ============================================================ deskew (backward propagation)
def deskew(points, point_dts, imu_poses, t_end):
    """Backward propagation: transform each point from the pose it was *sampled* at
    into the single scan-end frame, undoing the shear a moving sensor bakes into a
    sweep. imu_poses: list of (t, R, p) propagated across the sweep; point_dts:
    per-point time before scan end. We interpolate the propagated trajectory to each
    point's capture time — SO(3) for rotation, linear for position — so the
    within-sweep *rotation and velocity* are both compensated (using only the nearest
    pose, as a naive version does, leaves fast scans warped and smears the map)."""
    ts = np.array([q[0] for q in imu_poses])
    R_end, p_end = imu_poses[-1][1], imu_poses[-1][2]
    n = len(imu_poses)
    out = np.empty_like(points)
    for i, pb in enumerate(points):
        t = t_end - point_dts[i]
        j = min(max(np.searchsorted(ts, t) - 1, 0), n - 2) if n >= 2 else 0
        if n >= 2:
            t0, R0, p0 = imu_poses[j][0], imu_poses[j][1], imu_poses[j][2]
            t1, R1, p1 = imu_poses[j + 1][0], imu_poses[j + 1][1], imu_poses[j + 1][2]
            a = 0.0 if t1 == t0 else min(max((t - t0) / (t1 - t0), 0.0), 1.0)
            R_c = R0 @ Exp(a * Log(R0.T @ R1))     # interpolate rotation on SO(3)
            p_c = p0 + a * (p1 - p0)               # interpolate position (carries velocity)
        else:
            R_c, p_c = imu_poses[0][1], imu_poses[0][2]
        wpt = R_c @ pb + p_c                       # point in world at its capture pose
        out[i] = R_end.T @ (wpt - p_end)           # back into the scan-end frame
    return out

# ============================================================ downsample (voxel grid)
def voxel_downsample(pts, voxel=0.5):
    """One representative point per occupied voxel — FAST-LIO's per-scan downsample.
    100k raw points per scan is overkill; a sparse, even set keeps the update real-time."""
    if len(pts) == 0:
        return pts
    keys = np.floor(pts / voxel).astype(np.int64)
    _, idx = np.unique(keys, axis=0, return_index=True)
    return pts[np.sort(idx)]

# ============================================================ offline driver
def imu_init(imu_samples, g_mag=9.81):
    """Estimate gravity direction and gyro bias from a short static window."""
    a = np.mean([s[1] for s in imu_samples], 0)   # mean specific force
    w = np.mean([s[2] for s in imu_samples], 0)   # mean angular velocity = gyro bias
    g = -a / np.linalg.norm(a) * g_mag            # gravity opposes measured accel
    return g, w

def run_offline(imu_stream, lidar_scans, voxel=0.4, scan_voxel=0.5,
                T_LI=None, R_LI=None, acc_cov=1e-2, gyr_cov=1e-2,
                bacc_cov=1e-4, bgyr_cov=1e-4, init_secs=0.5):
    """imu_stream: list of (t, acc[3], gyro[3]); lidar_scans: list of dict with
       't_end', 'points'(N,3 body), 'dts'(N per-point time before scan end).

    T_LI / R_LI: LiDAR->IMU extrinsic (point in IMU frame = R_LI @ p_lidar + T_LI).
    acc_cov/gyr_cov: IMU noise densities (Avia's avia.yaml uses 0.1; the synthetic
    demo is quieter). The process-noise Q is built from these — too small and the
    filter trusts a stale prediction and refuses to move, too large and it's jumpy."""
    Q = np.diag([gyr_cov]*3 + [acc_cov]*3 + [bgyr_cov]*3 + [bacc_cov]*3)
    R_LI = np.eye(3) if R_LI is None else np.asarray(R_LI, float)
    T_LI = np.zeros(3) if T_LI is None else np.asarray(T_LI, float)
    to_imu = lambda p: (R_LI @ p.T).T + T_LI         # LiDAR points -> IMU body frame
    # --- init gravity + gyro bias from the first static window of IMU ---
    t0 = imu_stream[0][0]
    static = [s for s in imu_stream if s[0] < t0 + init_secs]
    g, bg = imu_init(static)
    kf = ESEKF(g); kf.x.bg = bg
    lmap = LocalMap(voxel)
    traj = []; imu_i = 0; bootstrapped = False
    for scan in lidar_scans:
        poses = []
        # forward-propagate every IMU sample up to scan end, caching poses for deskew
        while imu_i < len(imu_stream) and imu_stream[imu_i][0] <= scan['t_end']:
            t, acc, gyro = imu_stream[imu_i]
            dt = t - (imu_stream[imu_i-1][0] if imu_i > 0 else t)
            if dt > 0:
                kf.predict(acc, gyro, dt, Q)
            poses.append((t, kf.x.R.copy(), kf.x.p.copy()))
            imu_i += 1
        if not poses:
            poses = [(scan['t_end'], kf.x.R.copy(), kf.x.p.copy())]
        body = to_imu(scan['points'])                       # into the IMU body frame
        pts = deskew(body, scan['dts'], poses, scan['t_end'])
        pts = voxel_downsample(pts, scan_voxel)             # sparse, even set for the update
        if not bootstrapped:                    # seed the map from the first scan
            lmap.add((kf.x.R @ pts.T).T + kf.x.p); bootstrapped = True
        else:
            kf.update(pts, lmap)                # the iterated EKF correction
            lmap.add((kf.x.R @ pts.T).T + kf.x.p)
        traj.append((scan['t_end'], kf.x.p.copy(), kf.x.R.copy()))
    return traj, lmap

# ============================================================ read a .bag without ROS
_LIVOX_DEFS = (
    "uint32 offset_time\nfloat32 x\nfloat32 y\nfloat32 z\nuint8 reflectivity\nuint8 tag\nuint8 line\n",
    "std_msgs/Header header\nuint64 timebase\nuint32 point_num\nuint8 lidar_id\nuint8[3] rsvd\n"
    "livox_ros_driver/CustomPoint[] points\n",
)

def read_bag(path, imu_topic='/livox/imu', lidar_topic='/livox/lidar', g_mag=9.81):
    """Read IMU + LiDAR from a ROS1 bag with the pure-python `rosbags` (no ROS install).
       Handles sensor_msgs/PointCloud2 (Velodyne/Ouster) AND livox_ros_driver/CustomMsg
       (Livox Avia/Horizon). Livox accel (reported in g) is auto-scaled to m/s^2."""
    from pathlib import Path
    from rosbags.rosbag1 import Reader
    from rosbags.typesys import Stores, get_typestore
    from rosbags.typesys.msg import get_types_from_msg
    ts = get_typestore(Stores.ROS1_NOETIC)
    ts.register(get_types_from_msg(_LIVOX_DEFS[0], 'livox_ros_driver/msg/CustomPoint'))
    ts.register(get_types_from_msg(_LIVOX_DEFS[1], 'livox_ros_driver/msg/CustomMsg'))
    imu_stream, lidar_scans = [], []
    with Reader(Path(path)) as reader:
        conns = [c for c in reader.connections if c.topic in (imu_topic, lidar_topic)]
        for conn, t, raw in reader.messages(connections=conns):
            msg = ts.deserialize_ros1(raw, conn.msgtype)
            if conn.topic == imu_topic:
                a, w = msg.linear_acceleration, msg.angular_velocity
                imu_stream.append((t * 1e-9, np.array([a.x, a.y, a.z]), np.array([w.x, w.y, w.z])))
            elif 'CustomMsg' in conn.msgtype:                      # Livox
                pts, dts = parse_livox(msg)
                lidar_scans.append({'t_end': t * 1e-9, 'points': pts, 'dts': dts})
            else:                                                   # PointCloud2
                pts, dts = parse_pointcloud2(msg)
                lidar_scans.append({'t_end': t * 1e-9, 'points': pts, 'dts': dts})
    if imu_stream and np.mean([np.linalg.norm(s[1]) for s in imu_stream[:50]]) < 2.0:
        imu_stream = [(t, a * g_mag, w) for t, a, w in imu_stream]   # g -> m/s^2
    return imu_stream, lidar_scans

def parse_livox(msg):
    """Decode a livox_ros_driver/CustomMsg into (N,3) xyz and per-point dt-before-scan-end.

    Note: we deliberately ignore msg.header.stamp here. On real Avia bags the Livox
    header runs on the sensor's own clock (seconds-since-boot), while the IMU is stamped
    with the bag's record clock (Unix time). Mixing them silently breaks IMU/LiDAR sync,
    so read_bag uses the bag record time `t` for every scan's t_end and only uses the
    per-point offsets here for deskew."""
    P = msg.points
    xyz = np.array([[p.x, p.y, p.z] for p in P], float)
    off = np.array([p.offset_time for p in P], float) * 1e-9        # ns -> s from scan start
    keep = np.linalg.norm(xyz, axis=1) > 0.5
    xyz, off = xyz[keep], off[keep]
    return xyz, (off.max() - off if len(off) else off)             # dt before scan end

def parse_pointcloud2(msg):
    """Decode a sensor_msgs/PointCloud2 into (N,3) xyz + per-point time offset."""
    dtype = np.dtype({'names': [f.name for f in msg.fields],
                      'formats': [_PF[f.datatype] for f in msg.fields],
                      'offsets': [f.offset for f in msg.fields],
                      'itemsize': msg.point_step})
    arr = np.frombuffer(msg.data, dtype=dtype, count=msg.width * msg.height)
    xyz = np.stack([arr['x'], arr['y'], arr['z']], -1).astype(float)
    # the per-point time field is named 'time'/'t'/'offset_time' depending on driver
    tcol = next((n for n in ('time', 't', 'offset_time', 'timestamp') if n in arr.dtype.names), None)
    dts = (arr[tcol].astype(float) if tcol else np.zeros(len(xyz)))
    if dts.max() > 1.0:                         # ns/us -> s heuristics
        dts = dts * (1e-9 if dts.max() > 1e6 else 1e-3)
    return xyz, dts
_PF = {1: 'i1', 2: 'u1', 3: 'i2', 4: 'u2', 5: 'i4', 6: 'u4', 7: 'f4', 8: 'f8'}

# ============================================================ synthetic world (no dataset)
def simulate_room(seconds=8, seed=0):
    """A robot looping through a 10x10x3 m room. Returns (imu_stream, lidar_scans,
    truth) in exactly the format run_offline / a real bag would give you."""
    rng = np.random.default_rng(seed)
    Rz = lambda a: np.array([[np.cos(a), -np.sin(a), 0], [np.sin(a), np.cos(a), 0], [0, 0, 1]])
    truth = lambda t: (np.array([2*np.sin(0.4*t), 1.5*(1-np.cos(0.4*t)), 0.0]), Rz(0.3*np.sin(0.5*t)))
    acc = lambda t: np.array([-0.32*np.sin(0.4*t), 0.24*np.cos(0.4*t), 0.0])
    yawrate = lambda t: 0.15*np.cos(0.5*t)
    g = np.array([0, 0, -9.81])
    wall = []
    for _ in range(4000):
        f = rng.integers(0, 5); u, v = rng.uniform(-5, 5), rng.uniform(0, 3)
        wall.append([[-5, u, v], [5, u, v], [u, -5, v], [u, 5, v], [u, rng.uniform(-5, 5), 0]][f])
    wall = np.array(wall, float)
    bg_t, ba_t = np.array([2e-3, -1e-3, 1.5e-3]), np.array([2e-2, -3e-2, 1e-2])
    imu_stream = []                                       # 200 Hz IMU
    for k in range(int(seconds * 200)):
        t = k / 200; _, R = truth(t)
        am = R.T @ (acc(t) - g) + ba_t + rng.normal(0, 0.01, 3)   # specific force in body
        wm = np.array([0, 0, yawrate(t)]) + bg_t + rng.normal(0, 1e-3, 3)
        imu_stream.append((t, am, wm))
    scans = []                                            # 10 Hz LiDAR, skewed over the sweep
    for s in range(1, int(seconds * 10)):
        tc = s / 10; p, _ = truth(tc)
        vis = wall[np.linalg.norm(wall - p, axis=1) < 8]
        idx = rng.choice(len(vis), size=min(400, len(vis)), replace=False)
        pts, dts = [], []
        for j, kk in enumerate(idx):
            tau = tc - 0.1 + (j / len(idx)) * 0.1; pp, RR = truth(tau)
            pts.append(RR.T @ (vis[kk] - pp) + rng.normal(0, 0.01, 3)); dts.append(tc - tau)
        scans.append({'t_end': tc, 'points': np.array(pts), 'dts': np.array(dts)})
    return imu_stream, scans, truth

def write_demo_bag(path, seconds=6):
    """Write the simulated room to a real ROS1 .bag (sensor_msgs/Imu + PointCloud2),
    so you can exercise the read_bag() path without downloading a dataset."""
    import struct
    from rosbags.rosbag1 import Writer
    from rosbags.typesys import Stores, get_typestore
    ts = get_typestore(Stores.ROS1_NOETIC)
    Imu, PC2, PF = (ts.types[f'sensor_msgs/msg/{n}'] for n in ('Imu', 'PointCloud2', 'PointField'))
    Header, Time = ts.types['std_msgs/msg/Header'], ts.types['builtin_interfaces/msg/Time']
    Quat, Vec3 = ts.types['geometry_msgs/msg/Quaternion'], ts.types['geometry_msgs/msg/Vector3']
    H = lambda t, f: Header(seq=0, stamp=Time(sec=int(t), nanosec=int((t % 1) * 1e9)), frame_id=f)
    imu_stream, scans, _ = simulate_room(seconds)
    with Writer(path) as w:
        ci = w.add_connection('/imu', Imu.__msgtype__, typestore=ts)
        cp = w.add_connection('/velodyne_points', PC2.__msgtype__, typestore=ts)
        for t, a, wv in imu_stream:
            m = Imu(header=H(t, 'imu'), orientation=Quat(x=0., y=0., z=0., w=1.),
                    orientation_covariance=np.zeros(9),
                    angular_velocity=Vec3(x=wv[0], y=wv[1], z=wv[2]), angular_velocity_covariance=np.zeros(9),
                    linear_acceleration=Vec3(x=a[0], y=a[1], z=a[2]), linear_acceleration_covariance=np.zeros(9))
            w.write(ci, int(t * 1e9), ts.serialize_ros1(m, Imu.__msgtype__))
        flds = [PF(name=n, offset=o, datatype=7, count=1) for n, o in (('x', 0), ('y', 4), ('z', 8), ('time', 12))]
        for sc in scans:
            blob = b''.join(struct.pack('ffff', *p, d) for p, d in zip(sc['points'], sc['dts']))
            m = PC2(header=H(sc['t_end'], 'lidar'), height=1, width=len(sc['points']), fields=flds,
                    is_bigendian=False, point_step=16, row_step=16 * len(sc['points']),
                    data=np.frombuffer(blob, np.uint8).copy(), is_dense=True)
            w.write(cp, int(sc['t_end'] * 1e9), ts.serialize_ros1(m, PC2.__msgtype__))

def _ate(traj, truth):
    err = [np.linalg.norm(p - truth(t)[0]) for t, p, _ in traj]
    return float(np.sqrt(np.mean(np.square(err)))), float(err[-1])

if __name__ == '__main__':
    import sys
    if len(sys.argv) > 1:                       # python fastlio2_mini.py path/to/real.bag
        # defaults target the HKU Livox Avia bag: its avia.yaml extrinsic + noise
        imu, scans = read_bag(sys.argv[1], imu_topic='/livox/imu', lidar_topic='/livox/lidar')
        traj, lmap = run_offline(imu, scans, T_LI=[0.04165, 0.02326, -0.0284],
                                 acc_cov=0.1, gyr_cov=0.1, scan_voxel=0.5, init_secs=1.5)
        ps = np.array([p for _, p, _ in traj])
        plen = float(np.sum(np.linalg.norm(np.diff(ps, axis=0), axis=1)))
        print(f"{len(traj)} poses, map={len(lmap.pts)} pts, path={plen:.2f} m, "
              f"final={np.round(ps[-1], 2)}")
    else:                                       # self-contained demo: in-memory + a real .bag
        imu, scans, truth = simulate_room()
        traj, _ = run_offline(imu, scans)
        print("in-memory  : ATE rmse = %.3f m   final = %.3f m" % _ate(traj, truth))
        write_demo_bag('/tmp/fastlio2_demo.bag')
        imu_b, scans_b = read_bag('/tmp/fastlio2_demo.bag',
                                  imu_topic='/imu', lidar_topic='/velodyne_points')
        traj_b, _ = run_offline(imu_b, scans_b)
        print("via .bag   : ATE rmse = %.3f m   final = %.3f m" % _ate(traj_b, truth))
```

</CodeCollapse>

---

*Built on [FAST-LIO2: Fast Direct LiDAR-Inertial Odometry](https://arxiv.org/abs/2107.06829)
(Xu, Cai, He, Lin, Zhang, 2021), [ikd-Tree](https://arxiv.org/abs/2102.10808),
[FAST-LIO](https://arxiv.org/abs/2010.08196), [Super-LIO](https://arxiv.org/abs/2509.05723),
[FAR-LIO](https://arxiv.org/abs/2606.26010), the [Oxford Spires dataset](https://arxiv.org/abs/2411.10546)
and the [Hilti-Oxford dataset](https://arxiv.org/abs/2208.09825); code from
[hku-mars/FAST_LIO](https://github.com/hku-mars/FAST_LIO), [hku-mars/ikd-Tree](https://github.com/hku-mars/ikd-Tree),
[zlwang7/S-FAST_LIO](https://github.com/zlwang7/S-FAST_LIO),
[Liansheng-Wang/Super-LIO](https://github.com/Liansheng-Wang/Super-LIO) and
[TUMFTM/FAR-LIO](https://github.com/TUMFTM/FAR-LIO). Earlier, from building LiDAR mapping for
as-built scans at work: [3D mapping with LiDAR](https://satyajit.si/blog/3d-mapping-with-lidar) and
[Unseen drifts in 3D reconstruction](https://satyajit.si/blog/unseen-drifts-in-3d-reconstruction).*
