Algorithm Search⌘K

Algorithmresearch

Lidar odometry and mapping

Also called LOAM.

Zhang and Singh's lidar odometry and mapping, which matches edge and planar feature points at a high rate for odometry and at a low rate against the map.

Time
O(n k + n log n) feature_extractionO(g n) mapping_stepO(g f + n) odometry_step
Space
O(m) map
Where
f = the number of feature points of one scan; g = the number of Gauss-Newton iterations; k = the half width of the smoothness window; m = the number of map points; n = the number of points of one scan
Properties
deterministicnot exactonlinetoy code
Origin
Ji Zhang, Sanjiv Singh, 2014

Lidar odometry and mapping, LOAM, estimates the motion of a lidar and builds a map of point features at the same time. It splits the work between two algorithms that run at different rates. The odometry runs at the rate of the scans, 10 Hz in the paper. It matches a few feature points of the new scan to the previous scan and finds the motion between them. It is fast, but its errors add up. The mapping runs at a lower rate, 1 Hz in the paper. It matches many more feature points to the map, which is built from all earlier scans, and corrects the pose. Both algorithms use the same features. An edge point lies on a sharp edge of the scene, and a planar point lies on a flat surface. Edge points are matched to edge lines and planar points to planes, and the motion is found by nonlinear least squares with robust weights.

The code on this page is a toy. It works in the plane with a 2D scanner, its scans have no motion distortion, and it keeps only the feature extraction, the scan to scan odometry and the scan to map step. In the plane a surface is a line and an edge is a corner, so a flat point is matched to a line and a sharp point to a point.

In plain words

A laser scanner spins and measures the distance to everything around it. To know how it moved, compare two scans. Most points on a flat wall look alike, so the method picks only two kinds of points: points on sharp corners and points on smooth flat parts. It asks how the new scan must move so that its corner points fall on the old corners and its flat points fall on the old walls. This guess is quick and is made for every scan, but small errors pile up. Less often, the method compares the new scan with the whole map made so far, which has many more points, and corrects the position. Then it adds the new points to the map.

The problem

The input is a stream of lidar scans. Each scan is a list of points in the frame of the sensor, in the order of the beams. The output, after each scan, is the pose of the sensor relative to the first scan, and a map of feature points in that frame. The method must run in real time on one computer, and it has no other sensor. LOAM has no loop closure, so it is an odometry and mapping method, not a full solution of the SLAM problem. The drift that the map does not remove stays.

In the toy, the poses are planar, (tx,ty,θ)(t_x, t_y, \theta), and a scan has 360 beams over a full turn.

The algorithm

  1. PROCESS-SCAN(points X_1 .. X_n in beam order)
  2. 1for each point i: c_i ← ‖Σ_{j ∈ S_i} (X_i - X_j)‖ / (|S_i| ‖X_i‖), with S_i the k beams on each side of i
  3. 2in each sector, take the points with the largest c as sharp and the smallest c as flat; skip points next to a range jump and points next to a chosen point
  4. 3if this is the first scan then add the features to the map M and return the pose 0
  5. 4motion T ← the last motion; repeat Gauss-Newton on T:
  6. 5for each flat point p: find the nearest flat point a of the last scan and a second one b next to it on the scan line; r ← the distance from T(p) to the line ab
  7. 6for each sharp point p: find the nearest sharp point a of the last scan; r ← T(p) - a
  8. 7weight each match by the bisquare of its distance; solve the weighted normal equations for the step and update T
  9. 8until the step is small
  10. 9pose ← pose ⊕ T; every m-th scan, refine pose by the same loop against M, with a line fitted to the nearest map points for each flat point
  11. 10every m-th scan, add the features at the refined pose to M, on a voxel grid

The smoothness value (line L1). The value cic_i is the distance from XiX_i to the mean of its 2k2k neighbors on the scan line, divided by the range of XiX_i. It is near 0 on an evenly sampled flat surface and large at a corner. Because it is divided by the range, it does not change when the scene is scaled about the sensor, so one threshold works at all ranges.

The choice of features (line L2). LOAM splits each scan line into four subregions and takes at most two edge points and four planar points from each, so the features spread over the scene. It also rejects two kinds of unreliable points: points on a surface nearly parallel to the beam, and points at the edge of an occluded region, where the range jumps. A point that looks sharp only because the object behind it is far away is not a real edge, and it moves when the sensor moves. The toy uses six sectors, at most two sharp and eight flat points per sector, and rejects every point within k+1k + 1 beams of a range jump of more than 10 percent.

Odometry (lines L4 to L8). The motion between two scans starts from the last motion, a constant velocity guess. In 3D, LOAM matches an edge point to the line through two edge points of the last sweep on nearby scan lines, and a planar point to the plane through three planar points. The residual is the distance to that line or plane. The matches are found again at each iteration. Each match gets a bisquare weight (1−(d/τ)2)2(1 - (d/\tau)^2)^2, which is zero for far matches, and LOAM takes Levenberg-Marquardt steps. The toy takes plain Gauss-Newton steps. LOAM also removes the motion distortion: a spinning lidar takes a sweep over a time interval, and each point is moved by the part of the motion that happened before it was measured, by linear interpolation of the pose in time.

Mapping (lines L9 and L10). The mapping step starts from the odometry pose and matches the features to the map. For each feature point, it takes the nearby map points and computes their covariance. For an edge, one eigenvalue must be much larger than the others, and its eigenvector is the direction of the line. For a plane, one eigenvalue must be much smaller, and its eigenvector is the normal. Then it solves the same robust least squares problem. LOAM keeps the map in a cube around the sensor and thins it with a voxel grid. The published pose is the last mapped pose combined with the odometry since then, so it comes out at the high rate.

Example

The smoothness value by hand. Take k=5k = 5 and eleven points: (3,−0.5),(3,−0.4),…,(3,0)(3, -0.5), (3, -0.4), \dots, (3, 0) on one wall and (2.9,0),(2.8,0),…,(2.5,0)(2.9, 0), (2.8, 0), \dots, (2.5, 0) on another, with Xi=(3,0)X_i = (3, 0) at the corner. The five differences along the first wall are (0,0.1),…,(0,0.5)(0, 0.1), \dots, (0, 0.5), with sum (0,1.5)(0, 1.5). Along the second wall they sum to (1.5,0)(1.5, 0). So ci=∥(1.5,1.5)∥/(10⋅3)=2.121/30=0.071c_i = \|(1.5, 1.5)\| / (10 \cdot 3) = 2.121 / 30 = 0.071, above the edge threshold 0.05 of the toy. For eleven equally spaced points on one line, the differences cancel in pairs, and ci=0c_i = 0.

A run of the toy. The room is L-shaped, 12 m by 9 m, with two square pillars of side 0.8 m. The sensor drives on a circle of radius 1.8 m around one pillar, with 24 scans per lap, and takes 30 scans, a lap and a quarter. Each scan has 360 beams with range noise of standard deviation 0.03 m. The seed is 1. The first scan gives 8 sharp points, 33 flat points and 137 less flat points, which the mapping uses. Without noise, the same scan gives 3 sharp points, at room and pillar corners, and 251 less flat points, so the noise both adds false sharp points and moves points above the flat threshold. The mapping runs at every fifth scan.

scan odometry error (m) mapped error (m)
5 0.025 0.004
10 0.022 0.004
15 0.017 0.007
20 0.043 0.019
25 0.083 0.020
29 0.088 0.015

The largest position error is 0.090 m with odometry alone and 0.039 m with mapping. In the last quarter lap the sensor sees again the walls of the first scans, and the mapping pulls the pose back to the old map, while the odometry error keeps growing. At the end the map has 28 sharp and 522 flat points. On the seeds 1 to 6, the largest odometry error was 0.045 to 0.102 m and the largest mapped error was 0.022 to 0.058 m, between 0.37 and 0.61 times as large. These are measurements of a toy on simulated scans.

Exact motion without noise. With noise-free scans and flat points only, the odometry finds the motion (0.2,0.05,0.04)(0.2, 0.05, 0.04) to within 10−610^{-6} from the start (0,0,0)(0, 0, 0), because at the true motion every flat point lies on the wall of its match.

Correctness

LOAM has no proof of accuracy. It is judged by measured drift, for example on the KITTI odometry benchmark. The correctness proof covers the toy. It shows that the smoothness value is the distance to the mean of the neighbors divided by the range, so it does not change under scaling and rotation about the sensor and is zero on evenly spaced collinear points; that the residuals are the distances to lines and points and the Jacobians are their derivatives; that on noise-free scans the true motion is a zero of the flat cost; that each step minimizes the weighted linearized cost; that the line fit uses the eigenvector of the larger eigenvalue and gives the least squares line; that the grid search returns exactly the points within the radius; and that the mapping never changes the odometry. It also says what is not proved: convergence from a far start, the bias of sharp points from the beam spacing, and any bound on the drift.

The tests check the smoothness value on a line and a corner with its invariance, the features of a scan of the room against the true corners and walls, the Jacobians against finite differences, the grid against brute force, the line fit, the exact recovery of two motions without noise, and the drift with and without mapping on two seeds.

Proof: The smoothness value does not depend on the scale or the rotation of the scan, a noise-free flat point has zero residual at the true motion, and the steps of the LOAM toy solve the problems that they claim to solvefull

Setting. The toy of impl/python/lidar_odometry_and_mapping.py takes planar scans, each a list of points X1,…,XnX_1, \dots, X_n in the frame of the sensor, in the order of the beams. A pose is T=(tx,ty,θ)T = (t_x, t_y, \theta), and it maps a point pp to T(p)=R(θ)p+tT(p) = R(\theta) p + t. Lines L1 to L10 of the pseudocode process one scan. These claims are about the toy, not about the full LOAM system.

Assumptions. (A1) Exact arithmetic. (A2) No point of a scan is at the sensor, so ∥Xi∥>0\|X_i\| > 0.

Claim 1 (the smoothness value). Let ci=∥∑j∈S(Xi−Xj)∥/(∣S∣ ∥Xi∥)c_i = \|\sum_{j \in S} (X_i - X_j)\| / (|S| \, \|X_i\|), where SS holds the kk beams on each side of beam ii, so ∣S∣=2k|S| = 2k. Then:

(a) for every λ>0\lambda > 0 and every rotation RR, the scan λRX1,…,λRXn\lambda R X_1, \dots, \lambda R X_n has the same values cic_i;

(b) if Xi+d=Xi+d vX_{i+d} = X_i + d\,v for d=−k,…,kd = -k, \dots, k and some vector vv (equally spaced points on a line, centered on XiX_i), then ci=0c_i = 0;

(c) ci=∥Xi−Xˉ∥/∥Xi∥c_i = \|X_i - \bar X\| / \|X_i\|, where Xˉ\bar X is the mean of the 2k2k neighbors.

Proof. (c) ∑j∈S(Xi−Xj)=2kXi−∑j∈SXj=2k(Xi−Xˉ)\sum_{j \in S}(X_i - X_j) = 2k X_i - \sum_{j \in S} X_j = 2k (X_i - \bar X), and dividing by 2k∥Xi∥2k \|X_i\| gives the formula. (a) Both Xi−XˉX_i - \bar X and XiX_i are multiplied by λR\lambda R, and ∥λRx∥=λ∥x∥\|\lambda R x\| = \lambda \|x\|, so the ratio does not change. (b) The neighbors are Xi+dvX_i + d v for d=±1,…,±kd = \pm 1, \dots, \pm k, and their mean is Xi+v∑d/(2k)=XiX_i + v \sum d / (2k) = X_i, so ci=0c_i = 0 by (c). □\square

So cic_i measures how far XiX_i lies from the mean of its neighbors, as a fraction of its range. It is near zero on a wall that is sampled evenly and large at a corner. Because of (a), the same thresholds work at every range. The value is not invariant under translation of the scan, but a translation of the sensor is not a valid change of a scan anyway, because the points are measured from the sensor.

Claim 2 (the residuals and their Jacobians). For a point pp and a pose TT, let q=T(p)q = T(p). The sharp residual is r=q−mr = q - m for a target point mm. The flat residual is r=n⊤(q−a)r = n^\top (q - a) for a point aa on a line with unit normal nn, and ∣r∣|r| is the distance from qq to the line. The Jacobians in the code are the derivatives of these residuals with respect to (tx,ty,θ)(t_x, t_y, \theta).

Proof. The distance from qq to the line {a+sd}\{a + s d\} with unit direction dd and unit normal n⊥dn \perp d is the length of the component of q−aq - a along nn, which is ∣n⊤(q−a)∣|n^\top (q - a)|. The derivative of qq is the identity in (tx,ty)(t_x, t_y), and in θ\theta it is R′(θ)p=(−sin⁡θ px−cos⁡θ py, cos⁡θ px−sin⁡θ py)R'(\theta) p = (-\sin\theta\, p_x - \cos\theta\, p_y,\ \cos\theta\, p_x - \sin\theta\, p_y), the vector (dqx, dqy) of the code. The chain rule gives the rows [1,0,dqx][1, 0, \mathrm{dqx}] and [0,1,dqy][0, 1, \mathrm{dqy}] for the sharp residual and [nx,ny,nxdqx+nydqy][n_x, n_y, n_x \mathrm{dqx} + n_y \mathrm{dqy}] for the flat residual. □\square

Claim 3 (the true motion is a zero of the flat cost on noise-free scans). Let two scans be taken without noise from the poses AA and B=A⊕MB = A \oplus M, so a point pp of the new scan is the world point B(p)B(p) and a point aa of the old scan is A(a)A(a). If a flat point pp of the new scan is matched to two old points a,ba, b, and B(p)B(p), A(a)A(a) and A(b)A(b) lie on one wall, then the flat residual of pp at the motion MM is zero. If this holds for every match found at MM, then MM is a global minimizer of the weighted flat cost, and the Gauss-Newton loop of lines L4 to L8 stops at MM when it reaches it.

Proof. The residual is computed in the frame of the old scan. There M(p)=A−1(B(p))M(p) = A^{-1}(B(p)), and aa and bb are A−1(A(a))A^{-1}(A(a)) and A−1(A(b))A^{-1}(A(b)). The map A−1A^{-1} is rigid, so it sends the wall to a line that holds all three points. The line through aa and bb is that line, so M(p)M(p) is on it and the residual is zero. The cost is a sum of nonnegative terms wr2w r^2, so a cost of zero is a global minimum. At MM the gradient ∑wJ⊤r\sum w J^\top r is zero, so the step solves Hδ=0H \delta = 0 and is δ=0\delta = 0 when HH is positive definite, and the loop stops. □\square

The same holds for the map: on noise-free data from exact poses, the map points of one wall are collinear and the fitted line is the wall, by Claim 5. A sharp point is different. The beam nearest to a corner hits the wall up to one beam spacing away from the corner, so a sharp residual at the true motion is not zero in general. The tests check the claim with flat points only.

Claim 4 (one Gauss-Newton step). Let the matches and the weights wm=ρ(dm)w_m = \rho(d_m) be fixed, where ρ(d)=(1−(d/τ)2)2\rho(d) = (1 - (d/\tau)^2)^2 for ∣d∣<τ|d| < \tau and 0 otherwise. If H=∑mwmJm⊤JmH = \sum_m w_m J_m^\top J_m is positive definite, the step δ\delta of line L7 is the unique minimizer of the linearized cost ∑mwm∥rm+Jmδ∥2\sum_m w_m \|r_m + J_m \delta\|^2.

Proof. The linearized cost is a quadratic in δ\delta with Hessian 2H2H and gradient 2(Hδ+g)2(H \delta + g) with g=∑mwmJm⊤rmg = \sum_m w_m J_m^\top r_m. A strictly convex quadratic has one minimizer, the zero of the gradient, δ=−H−1g\delta = -H^{-1} g. The code accumulates HH and −g-g and solves Hδ=−gH \delta = -g by Gaussian elimination with partial pivoting, which is exact in exact arithmetic for a nonsingular matrix. □\square

This is one step of iteratively reweighted least squares with the bisquare weight. Matches with dm≥τd_m \ge \tau get the weight zero and do not count. The code stops with an error when fewer than three matches are left or the matrix is singular, because then the features do not fix the three degrees of freedom.

Claim 5 (the line fit). For points p1,…,pmp_1, \dots, p_m with mean μ\mu and covariance C=1m∑(pk−μ)(pk−μ)⊤C = \frac1m \sum (p_k - \mu)(p_k - \mu)^\top, fit_line returns μ\mu, a unit eigenvector dd of CC for the larger eigenvalue, and the two eigenvalues. The line {μ+sd}\{\mu + s d\} minimizes the sum of squared distances of the points to a line, and the smaller eigenvalue is zero if and only if the points are collinear.

Proof. With C=(sxxsxysxysyy)C = \begin{pmatrix} s_{xx} & s_{xy} \\ s_{xy} & s_{yy} \end{pmatrix}, the eigenvalues are sxx+syy2±(sxx−syy2)2+sxy2\frac{s_{xx} + s_{yy}}2 \pm \sqrt{(\frac{s_{xx} - s_{yy}}2)^2 + s_{xy}^2}, which is what the code computes. The vector (cos⁡ϕ,sin⁡ϕ)(\cos\phi, \sin\phi) with ϕ=12atan2(2sxy,sxx−syy)\phi = \frac12 \mathrm{atan2}(2 s_{xy}, s_{xx} - s_{yy}) maximizes d⊤Cd=sxx+syy2+sxx−syy2cos⁡2ϕ+sxysin⁡2ϕd^\top C d = \frac{s_{xx} + s_{yy}}2 + \frac{s_{xx} - s_{yy}}2 \cos 2\phi + s_{xy} \sin 2\phi, since the last two terms are the inner product of (cos⁡2ϕ,sin⁡2ϕ)(\cos 2\phi, \sin 2\phi) with (sxx−syy2,sxy)(\frac{s_{xx} - s_{yy}}2, s_{xy}). So it is an eigenvector for the larger eigenvalue. The sum of squared distances to a line through μ\mu with unit normal nn is m n⊤Cnm\, n^\top C n, which is smallest for n⊥dn \perp d, and the best line passes through the mean because shifting a line along its normal adds mm times the square of the shift to the sum. The smaller eigenvalue is 1m\frac1m times this least sum, which is zero if and only if all points lie on the line. □\square

Claim 6 (the grid search). Grid.near(q, r) returns the indices of exactly the points within distance rr of qq, in order of distance.

Proof. A point is stored in the cell (⌊x/h⌋,⌊y/h⌋)(\lfloor x / h \rfloor, \lfloor y / h \rfloor) for the cell size hh. If ∣px−qx∣≤r|p_x - q_x| \le r, then ∣⌊px/h⌋−⌊qx/h⌋∣≤⌈r/h⌉|\lfloor p_x / h \rfloor - \lfloor q_x / h \rfloor| \le \lceil r / h \rceil, and the same holds for yy. So every point within distance rr lies in one of the cells that the search visits. The search tests the distance of each point in these cells and keeps exactly those within rr, then sorts them. □\square

Claim 7 (the two rates). After each scan, odom_path ends with the composition of all odometry motions, and path ends with the latest mapped pose composed with the odometry motions after it. The mapping step never changes the odometry motions.

Proof. odom_pose is changed only by composition with motion at each scan. pose is composed with the same motion and, at every map_every-th scan, replaced by the result of the scan to map step, which starts from it. The odometry step reads only the previous scan and the last motion, not pose or the map. □\square

What this does not show. It does not show that the Gauss-Newton loop converges from a far start, or to the true motion when the matches found from the start are wrong; the motion guess must be close, which is why the last motion is used as the guess. It does not show that a sharp point matches the same corner in two scans, and the beam spacing bias of Claim 3 remains. It does not bound the drift: the mapping step removes error only where the map is older and more accurate than the odometry chain, and nothing closes a loop. The tests measure the drift on simulated scans; they do not prove a bound. It does not cover what the toy leaves out: 3D scans, the removal of motion distortion within a sweep, Levenberg-Marquardt, and the local cube of the map in LOAM.

Complexity

Let nn be the number of points of a scan, kk the half width of the window, ff the number of feature points, gg the number of Gauss-Newton iterations and mm the number of map points.

  • The smoothness values cost O(nk)O(n k), and sorting each sector costs O(nlog⁡n)O(n \log n) in total.
  • An odometry iteration finds one or two neighbors for each of the ff features. With a grid or a k-d tree over the points of the last scan and a bounded density of points, this costs O(f)O(f) expected time per iteration, plus O(n)O(n) to build the search structure once per scan.
  • A mapping iteration matches all O(n)O(n) less sharp and less flat points of the scan, with a small fixed number of map neighbors each. LOAM bounds the cost by keeping only the map in a cube around the sensor, so mm does not grow with the length of the run in the matching step.
  • The map takes O(m)O(m) space.

Properties

  • Two rates. The odometry gives a pose at every scan. The mapping corrects it at a lower rate, and the published pose combines the two.
  • Features, not all points. Matching a few hundred features instead of all points makes each iteration cheap, compared with ICP on whole scans.
  • Point-to-line and point-to-plane residuals. As in point-to-plane ICP, a point may slide along its surface without cost, which avoids wrong pairings of points between two samplings of the same surface.
  • Robust weights. The bisquare weights make the estimate an iteratively reweighted least squares fit that ignores far matches.
  • No loop closure. Drift is reduced but never removed. A revisit helps only when the map near it is still accurate.

Variants and improvements

  • V-LOAM. Zhang and Singh added a camera, with visual odometry at a high rate and lidar odometry for refinement.
  • LeGO-LOAM. Shan and Englot segmented the ground, used it for some degrees of freedom, and added loop closure with a pose graph.
  • LIO-SAM and other lidar-inertial methods. An inertial sensor removes the motion distortion and gives the motion guess, and a factor graph with iSAM2-style smoothing joins lidar, inertial and loop factors.
  • A-LOAM and F-LOAM. A-LOAM is a shorter open implementation of the same scheme. F-LOAM drops the scan to scan step and matches every scan to the map.
  • Other registration. NDT and correlative scan matching match whole scans to a map without features. They are slower or coarser per scan, but they need no corners or flat surfaces.

When to use it

Use LOAM or one of its successors for real-time lidar odometry and local mapping with a spinning lidar, in scenes with enough edges and surfaces, such as buildings and streets. Add an inertial sensor when the motion is fast, and add loop closure detection with pose graph optimization when the robot returns to old places over long runs. In long corridors, tunnels and open fields, the features do not fix all degrees of freedom, and the estimate slides. Use the toy only to study the feature extraction and the two rates.

Pitfalls

  • Degenerate scenes. In a long corridor all flat points constrain only the motion across it, and the normal equations are nearly singular along it. A check on the eigenvalues of the normal matrix finds this.
  • Occlusion edges. A point at the border of a near object in front of a far wall looks sharp but is not a fixed point of the scene. The range jump test removes it.
  • Motion distortion. A sweep that is treated as one instant bends straight walls when the sensor moves fast.
  • Bad motion guess. The matches are found from the guess. A sudden change of motion, with no inertial sensor, can make most matches wrong.
  • Beam spacing at corners. The beam nearest a corner hits a wall up to one beam spacing away from it, so sharp point matches carry an error that grows with the range.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

lidar_odometry_and_mapping.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lidar-odometry-and-mapping/. The authors are listed in prov/GTC8AH.jsonl.

"""A planar toy of LOAM, the lidar odometry and mapping of Zhang and Singh.

This is a toy. The lidar is a 2D scanner, the scans are taken at one instant
(there is no motion distortion to remove), and the map is a flat list of
points in a hash grid. What the toy keeps from LOAM:

  - the smoothness value c of each point, from the points next to it on the
    same scan line, and the choice of sharp points (large c) and flat points
    (small c) in each sector, with points at depth jumps left out,
  - odometry at every scan: match the sharp and flat points of the new scan
    to the feature points of the previous scan and solve for the motion by
    Gauss-Newton with bisquare weights,
  - mapping at a lower rate: match the features to the map, with a line
    fitted to the nearby map points by an eigenvector, refine the pose, and
    add the features to the map.

What the toy leaves out: the 3D scan lines, the removal of the motion
distortion inside a sweep, the less sharp points, Levenberg-Marquardt, and the
cube of map points around the sensor.

In 3D, LOAM matches an edge point to a line and a planar point to a plane.
In the plane, a wall is a line and a corner is a point, so a flat point is
matched to a line and a sharp point to a point.
"""

import math

# ------------------------------------------------------------- planar poses


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


def compose(a, b):
    c, s = math.cos(a[2]), math.sin(a[2])
    return (a[0] + c * b[0] - s * b[1], a[1] + s * b[0] + c * b[1], wrap(a[2] + b[2]))


def inverse(a):
    c, s = math.cos(a[2]), math.sin(a[2])
    return (-c * a[0] - s * a[1], s * a[0] - c * a[1], -a[2])


def transform(pose, p):
    c, s = math.cos(pose[2]), math.sin(pose[2])
    return (pose[0] + c * p[0] - s * p[1], pose[1] + s * p[0] + c * p[1])


# ------------------------------------------------------------- features


def smoothness(points, i, k):
    """LOAM's c: |sum over the 2k neighbors j of (X_i - X_j)| / (2k |X_i|)."""
    n = len(points)
    xi, yi = points[i]
    sx = sy = 0.0
    for d in range(-k, k + 1):
        if d:
            xj, yj = points[(i + d) % n]
            sx += xi - xj
            sy += yi - yj
    return math.hypot(sx, sy) / (2 * k * math.hypot(xi, yi))


def reliable_points(points, k, jump):
    """ok[i] is False if the range jumps by more than the fraction `jump`
    between two consecutive beams within k + 1 beams of beam i.

    Such points lie at the edge of an occluded region, or next to it, and
    LOAM does not take them as features.
    """
    n = len(points)
    r = [math.hypot(x, y) for x, y in points]
    smooth = [abs(r[(a + 1) % n] - r[a]) <= jump * min(r[(a + 1) % n], r[a]) for a in range(n)]
    return [all(smooth[(i + d) % n] for d in range(-k - 1, k + 1)) for i in range(n)]


def extract_features(points, k=5, sectors=6, n_sharp=2, n_flat=8, c_edge=0.05, c_flat=0.01, jump=0.1):
    """Return (sharp, flat, less_flat) as lists of point indices.

    In each sector, the sharp points are the points with the largest c above
    c_edge and the flat points are the points with the smallest c below c_flat.
    A chosen point blocks its k neighbors on each side, so the features spread
    out. less_flat holds every reliable point with c below c_flat.
    """
    n = len(points)
    c = [smoothness(points, i, k) for i in range(n)]  # @line L1
    ok = reliable_points(points, k, jump)
    sharp, flat, less_flat = [], [], []
    taken = set()
    for s in range(sectors):
        idx = [i for i in range(s * n // sectors, (s + 1) * n // sectors) if ok[i]]
        got = 0
        for i in sorted(idx, key=lambda i: -c[i]):
            if c[i] <= c_edge or got == n_sharp:
                break
            if i not in taken:
                sharp.append(i)
                got += 1
                taken.update((i + d) % n for d in range(-k, k + 1))
        got = 0
        for i in sorted(idx, key=lambda i: c[i]):
            if c[i] >= c_flat or got == n_flat:
                break
            if i not in taken:
                flat.append(i)
                got += 1
                taken.update((i + d) % n for d in range(-k, k + 1))
        less_flat.extend(i for i in idx if c[i] < c_flat)  # @line L2
    return sorted(sharp), sorted(flat), less_flat


# ------------------------------------------------------------- neighbor search


class Grid:
    """Points in a hash grid with square cells, for nearest neighbor queries."""

    def __init__(self, points, cell=0.5):
        self.cell = cell
        self.points = list(points)
        self.cells = {}
        for idx, p in enumerate(self.points):
            self.cells.setdefault(self._key(p), []).append(idx)

    def _key(self, p):
        return (math.floor(p[0] / self.cell), math.floor(p[1] / self.cell))

    def near(self, q, radius):
        """Indices of the points within `radius` of q, nearest first."""
        cx, cy = self._key(q)
        r = int(math.ceil(radius / self.cell))
        found = []
        for dx in range(-r, r + 1):
            for dy in range(-r, r + 1):
                for idx in self.cells.get((cx + dx, cy + dy), ()):
                    p = self.points[idx]
                    d = math.hypot(p[0] - q[0], p[1] - q[1])
                    if d <= radius:
                        found.append((d, idx))
        found.sort()
        return [idx for _, idx in found]


# ------------------------------------------------------------- residuals


def point_residual(pose, p, target):
    """Sharp point: q - target, two rows, with the Jacobian in (tx, ty, theta)."""
    q = transform(pose, p)
    c, s = math.cos(pose[2]), math.sin(pose[2])
    dqx, dqy = -s * p[0] - c * p[1], c * p[0] - s * p[1]
    return [q[0] - target[0], q[1] - target[1]], [[1.0, 0.0, dqx], [0.0, 1.0, dqy]]


def line_residual(pose, p, a, normal):
    """Flat point: signed distance n . (q - a) to a line, with its Jacobian."""
    q = transform(pose, p)
    c, s = math.cos(pose[2]), math.sin(pose[2])
    dqx, dqy = -s * p[0] - c * p[1], c * p[0] - s * p[1]
    r = normal[0] * (q[0] - a[0]) + normal[1] * (q[1] - a[1])
    return [r], [[normal[0], normal[1], normal[0] * dqx + normal[1] * dqy]]


def bisquare(d, tau):
    return (1.0 - (d / tau) ** 2) ** 2 if abs(d) < tau else 0.0


def solve3(h, g):
    """Solve a 3 x 3 system by Gaussian elimination with partial pivoting."""
    m = [list(h[i]) + [g[i]] for i in range(3)]
    for col in range(3):
        piv = max(range(col, 3), key=lambda r: abs(m[r][col]))
        if abs(m[piv][col]) < 1e-12:
            raise ValueError("degenerate: the features do not fix the motion")
        m[col], m[piv] = m[piv], m[col]
        for r in range(col + 1, 3):
            f = m[r][col] / m[col][col]
            for c in range(col, 4):
                m[r][c] -= f * m[col][c]
    x = [0.0] * 3
    for r in (2, 1, 0):
        x[r] = (m[r][3] - sum(m[r][c] * x[c] for c in range(r + 1, 3))) / m[r][r]
    return x


def gauss_newton(pose, make_terms, iterations=20, tau=0.3, tol=1e-6):
    """Minimize the sum of bisquare-weighted squared residuals over the pose.

    make_terms(pose) returns (residual rows, Jacobian rows, distance) per match;
    the matches are found again at every iteration.
    """
    for _ in range(iterations):
        h = [[0.0] * 3 for _ in range(3)]
        g = [0.0] * 3
        used = 0
        for rows, jac, dist in make_terms(pose):
            w = bisquare(dist, tau)
            if w == 0.0:
                continue
            used += 1
            for r, jr in zip(rows, jac):
                for a in range(3):
                    g[a] -= w * jr[a] * r
                    for b in range(3):
                        h[a][b] += w * jr[a] * jr[b]
        if used < 3:
            raise ValueError("too few matches")
        dx = solve3(h, g)  # @line L7
        pose = (pose[0] + dx[0], pose[1] + dx[1], wrap(pose[2] + dx[2]))
        if max(abs(v) for v in dx) < tol:  # @line L8
            break
    return pose


# ------------------------------------------------------------- matching


def line_through(a, b):
    dx, dy = b[0] - a[0], b[1] - a[1]
    norm = math.hypot(dx, dy)
    return (-dy / norm, dx / norm)


def scan_to_scan_terms(cur, sharp, flat, prev, prev_sharp, prev_less_flat, radius=1.0, sharp_radius=0.5):
    """Matches of the new features to the feature points of the previous scan.

    A flat point is matched to the line through the nearest less flat point a
    of the previous scan and the nearest less flat point b that is at most 3
    beams away from a. A sharp point is matched to the nearest sharp point.
    """
    flat_grid = Grid([prev[i] for i in prev_less_flat])
    sharp_grid = Grid([prev[i] for i in prev_sharp])

    def terms(pose):
        out = []
        for i in flat:
            near = flat_grid.near(transform(pose, cur[i]), radius)
            if not near:
                continue
            a_idx = prev_less_flat[near[0]]
            b_idx = next((prev_less_flat[m] for m in near[1:] if 0 < abs(prev_less_flat[m] - a_idx) <= 3), None)
            if b_idx is None:
                continue
            a = prev[a_idx]
            rows, jac = line_residual(pose, cur[i], a, line_through(a, prev[b_idx]))  # @line L5
            out.append((rows, jac, abs(rows[0])))
        for i in sharp:
            near = sharp_grid.near(transform(pose, cur[i]), sharp_radius)
            if near:
                rows, jac = point_residual(pose, cur[i], sharp_grid.points[near[0]])  # @line L6
                out.append((rows, jac, math.hypot(*rows)))
        return out

    return terms


def fit_line(points):
    """Mean and unit direction of the largest spread, and the two eigenvalues."""
    n = len(points)
    mx = sum(p[0] for p in points) / n
    my = sum(p[1] for p in points) / n
    sxx = sum((p[0] - mx) ** 2 for p in points) / n
    syy = sum((p[1] - my) ** 2 for p in points) / n
    sxy = sum((p[0] - mx) * (p[1] - my) for p in points) / n
    half = math.hypot((sxx - syy) / 2.0, sxy)
    big, small = (sxx + syy) / 2.0 + half, (sxx + syy) / 2.0 - half
    angle = 0.5 * math.atan2(2.0 * sxy, sxx - syy)
    return (mx, my), (math.cos(angle), math.sin(angle)), big, small


def scan_to_map_terms(cur, sharp, flat, map_sharp, map_flat, radius=1.0, sharp_radius=0.5, count=5, line_ratio=0.01):
    """Matches of the features to the map.

    A flat point is matched to the line fitted to its `count` nearest map flat
    points, if their spread is long and thin. A sharp point is matched to the
    mean of the map sharp points within 0.2 of the nearest one.
    """
    flat_grid = Grid(map_flat)
    sharp_grid = Grid(map_sharp)

    def terms(pose):
        out = []
        for i in flat:
            near = flat_grid.near(transform(pose, cur[i]), radius)[:count]
            if len(near) < count:
                continue
            mean, d, big, small = fit_line([flat_grid.points[m] for m in near])
            if small > line_ratio * big:  # the points do not lie on a line
                continue
            rows, jac = line_residual(pose, cur[i], mean, (-d[1], d[0]))
            out.append((rows, jac, abs(rows[0])))
        for i in sharp:
            near = sharp_grid.near(transform(pose, cur[i]), sharp_radius)
            if not near:
                continue
            pts = [sharp_grid.points[m] for m in sharp_grid.near(sharp_grid.points[near[0]], 0.2)]
            mean = (sum(p[0] for p in pts) / len(pts), sum(p[1] for p in pts) / len(pts))
            rows, jac = point_residual(pose, cur[i], mean)
            out.append((rows, jac, math.hypot(*rows)))
        return out

    return terms


# ------------------------------------------------------------- the toy system


def voxel_filter(points, cell):
    seen = {}
    for p in points:
        seen.setdefault((math.floor(p[0] / cell), math.floor(p[1] / cell)), p)
    return list(seen.values())


class ToyLoam:
    """Odometry at every scan and mapping at every `map_every`-th scan.

    Poses are relative to the pose of the first scan. `odom_path` is the chain
    of odometry motions alone. `path` is the output: the last mapped pose
    composed with the odometry motions since then.
    """

    def __init__(self, map_every=5, voxel=0.1):
        self.map_every = map_every
        self.voxel = voxel
        self.prev = None
        self.motion = (0.0, 0.0, 0.0)
        self.odom_pose = (0.0, 0.0, 0.0)
        self.pose = (0.0, 0.0, 0.0)
        self.map_sharp = []
        self.map_flat = []
        self.count = 0
        self.odom_path = []
        self.path = []

    def _add_to_map(self, pose, scan, sharp, less_flat):
        self.map_sharp = voxel_filter(self.map_sharp + [transform(pose, scan[i]) for i in sharp], self.voxel)
        self.map_flat = voxel_filter(self.map_flat + [transform(pose, scan[i]) for i in less_flat], self.voxel)

    def add_scan(self, scan):
        """Process one scan (points in the sensor frame, in beam order). Return the pose."""
        sharp, flat, less_flat = extract_features(scan)
        if self.prev is None:  # @line L3
            self._add_to_map(self.pose, scan, sharp, less_flat)
        else:
            prev, p_sharp, p_less_flat = self.prev
            terms = scan_to_scan_terms(scan, sharp, flat, prev, p_sharp, p_less_flat)
            self.motion = gauss_newton(self.motion, terms)  # @line L4
            self.odom_pose = compose(self.odom_pose, self.motion)
            self.pose = compose(self.pose, self.motion)
            self.count += 1
            if self.count % self.map_every == 0:
                terms = scan_to_map_terms(scan, sharp, less_flat, self.map_sharp, self.map_flat)
                self.pose = gauss_newton(self.pose, terms)  # @line L9
                self._add_to_map(self.pose, scan, sharp, less_flat)  # @line L10
        self.odom_path.append(self.odom_pose)
        self.path.append(self.pose)
        self.prev = (scan, sharp, less_flat)
        return self.pose
test_lidar_odometry_and_mapping.py 184 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lidar-odometry-and-mapping/. The authors are listed in prov/GTC8AH.jsonl.

import math
import random

from lidar_odometry_and_mapping import (
    Grid,
    ToyLoam,
    compose,
    extract_features,
    fit_line,
    gauss_newton,
    inverse,
    line_residual,
    point_residual,
    scan_to_scan_terms,
    smoothness,
    transform,
    wrap,
)


def room():
    """An L-shaped room with two square pillars, as wall segments."""
    poly = [(0, 0), (12, 0), (12, 4), (8, 4), (8, 9), (0, 9)]
    segs = [(poly[i], poly[(i + 1) % len(poly)]) for i in range(len(poly))]
    for cx, cy in ((3, 3), (5, 6.5)):
        box = [(cx - 0.4, cy - 0.4), (cx + 0.4, cy - 0.4), (cx + 0.4, cy + 0.4), (cx - 0.4, cy + 0.4)]
        segs += [(box[i], box[(i + 1) % 4]) for i in range(4)]
    return segs


def cast(pose, segs, beams, rng=None, noise=0.0):
    """A 360 degree scan from `pose`, as points in the sensor frame in beam order."""
    pts = []
    for b in range(beams):
        la = 2 * math.pi * b / beams
        dx, dy = math.cos(pose[2] + la), math.sin(pose[2] + la)
        best = math.inf
        for (x1, y1), (x2, y2) in segs:
            ex, ey = x2 - x1, y2 - y1
            den = dx * ey - dy * ex
            if abs(den) < 1e-12:
                continue
            wx, wy = x1 - pose[0], y1 - pose[1]
            t = (wx * ey - wy * ex) / den
            u = (wx * dy - wy * dx) / den
            if t > 1e-9 and -1e-9 <= u <= 1 + 1e-9:
                best = min(best, t)
        r = best + (rng.gauss(0, noise) if noise else 0.0)
        pts.append((r * math.cos(la), r * math.sin(la)))
    return pts


def circle(n, per_lap=24):
    """n poses on a circle of radius 1.8 around the first pillar, facing forward."""
    out = []
    for k in range(n):
        a = -math.pi / 2 + 2 * math.pi * k / per_lap
        out.append((3 + 1.8 * math.cos(a), 3 + 1.8 * math.sin(a), wrap(a + math.pi / 2)))
    return out


def run(seed, n=30, noise=0.03):
    truth = circle(n)
    rng = random.Random(seed)
    loam = ToyLoam(map_every=5)
    for pose in truth:
        loam.add_scan(cast(pose, room(), 360, rng, noise))
    return truth, loam


def errors(poses, truth):
    start = truth[0]
    return [math.hypot(*(a - b for a, b in zip(compose(start, p)[:2], t[:2]))) for p, t in zip(poses, truth)]


def test_smoothness_is_zero_on_a_line_and_scale_free():
    line = [(3.0, -1.0 + 0.1 * j) for j in range(21)]
    assert smoothness(line, 10, 5) < 1e-12
    corner = [(3.0, 0.1 * j) for j in range(-5, 1)] + [(3.0 - 0.1 * j, 0.0) for j in range(1, 6)]
    c = smoothness(corner, 5, 5)
    assert c > 0.05
    for lam, th in ((2.0, 0.0), (0.5, 1.3)):
        moved = [(lam * (math.cos(th) * x - math.sin(th) * y), lam * (math.sin(th) * x + math.cos(th) * y)) for x, y in corner]
        assert abs(smoothness(moved, 5, 5) - c) < 1e-12


def test_sharp_points_lie_at_corners_and_flat_points_on_walls():
    segs = room()
    pose = (2.0, 1.5, 0.2)
    scan = cast(pose, segs, 360)
    sharp, flat, less_flat = extract_features(scan)
    corners = [p for s in segs for p in s]
    assert len(sharp) >= 3
    for i in sharp:
        q = transform(pose, scan[i])
        r = math.hypot(*scan[i])
        # within two beam spacings of a corner of the room or of a pillar
        assert min(math.hypot(q[0] - x, q[1] - y) for x, y in corners) < 2 * r * 2 * math.pi / 360
    for i in less_flat:
        q = transform(pose, scan[i])
        assert min(segment_distance(q, s) for s in segs) < 1e-9
    assert set(flat) <= set(less_flat)


def segment_distance(q, seg):
    (x1, y1), (x2, y2) = seg
    ex, ey = x2 - x1, y2 - y1
    t = max(0.0, min(1.0, ((q[0] - x1) * ex + (q[1] - y1) * ey) / (ex * ex + ey * ey)))
    return math.hypot(q[0] - x1 - t * ex, q[1] - y1 - t * ey)


def test_jacobians_match_finite_differences():
    rng = random.Random(4)
    for _ in range(20):
        pose = (rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(-3, 3))
        p = (rng.uniform(-5, 5), rng.uniform(-5, 5))
        a = (rng.uniform(-5, 5), rng.uniform(-5, 5))
        th = rng.uniform(0, math.pi)
        normal = (math.cos(th), math.sin(th))
        for f in (lambda x: point_residual(x, p, a), lambda x: line_residual(x, p, a, normal)):
            rows, jac = f(pose)
            for k in range(3):
                h = 1e-6
                plus = list(pose)
                plus[k] += h
                minus = list(pose)
                minus[k] -= h
                for r in range(len(rows)):
                    num = (f(tuple(plus))[0][r] - f(tuple(minus))[0][r]) / (2 * h)
                    assert abs(num - jac[r][k]) < 1e-6


def test_grid_equals_brute_force():
    rng = random.Random(6)
    pts = [(rng.uniform(-5, 5), rng.uniform(-5, 5)) for _ in range(300)]
    grid = Grid(pts, cell=0.7)
    for _ in range(50):
        q = (rng.uniform(-6, 6), rng.uniform(-6, 6))
        rad = rng.uniform(0.1, 2.0)
        brute = sorted((math.hypot(p[0] - q[0], p[1] - q[1]), i) for i, p in enumerate(pts))
        assert grid.near(q, rad) == [i for d, i in brute if d <= rad]


def test_fit_line_finds_the_direction():
    pts = [(1.0 + t * math.cos(0.7), 2.0 + t * math.sin(0.7)) for t in (-1.0, -0.5, 0.0, 0.25, 1.5)]
    mean, d, big, small = fit_line(pts)
    assert abs(d[0] * math.sin(0.7) - d[1] * math.cos(0.7)) < 1e-12
    assert small < 1e-12 < big


def test_flat_points_recover_the_motion_exactly_without_noise():
    # on noise-free scans every flat point lies on the line of its match at
    # the true motion, so the true motion is a zero of the cost
    segs = room()
    a = (2.0, 1.5, 0.1)
    for motion in ((0.2, 0.05, 0.04), (0.3, -0.1, -0.06)):
        b = compose(a, motion)
        s0, s1 = cast(a, segs, 360), cast(b, segs, 360)
        sh0, fl0, lf0 = extract_features(s0)
        sh1, fl1, lf1 = extract_features(s1)
        terms = scan_to_scan_terms(s1, [], fl1, s0, [], lf0)
        got = gauss_newton((0.0, 0.0, 0.0), terms)
        assert all(abs(x - y) < 1e-6 for x, y in zip(got, motion))
        assert all(abs(r) < 1e-9 for rows, _, _ in terms(motion) for r in rows)


def test_mapping_reduces_the_drift_of_odometry():
    # 30 scans, a lap and a quarter around a pillar, with range noise 0.03
    for seed in (1, 2):
        truth, loam = run(seed)
        # odom_path is what odometry alone gives, since mapping does not feed back into it
        odom = errors(loam.odom_path, truth)
        mapped = errors(loam.path, truth)
        assert max(mapped) < 0.6 * max(odom)
        assert max(mapped) < 0.05 and mapped[-1] < 0.05


def test_inverse_and_compose():
    a = (1.0, -2.0, 0.7)
    e = compose(a, inverse(a))
    assert all(abs(x) < 1e-12 for x in e)

History

Lidar scan matching for mobile robots goes back to the ICP of Besl and McKay (1992) and the work of Lu and Milios (1997) on 2D scans. Biber and Straßer (2003) gave NDT. Zhang and Singh (2014) presented LOAM at RSS. Their key ideas were the split into a fast odometry and a slow mapping step and the use of edge and planar feature points with point-to-line and point-to-plane distances. The journal version (2017) added detail and tests on the KITTI odometry benchmark, where LOAM was among the most accurate methods for years. LeGO-LOAM (2018) and LIO-SAM (2020) built on it, and its feature scheme is still the base of many lidar odometry systems.

References

  1. Ji Zhang and Sanjiv Singh, LOAM: Lidar Odometry and Mapping in Real-time, Robotics: Science and Systems X, 2014, the smoothness value c, the choice of edge and planar points per subregion, the point-to-edge and point-to-plane distances, the bisquare weights and Levenberg-Marquardt, the odometry at 10 Hz and the mapping at 1 Hz
  2. Ji Zhang and Sanjiv Singh, Low-drift and real-time lidar odometry and mapping, Autonomous Robots 41(2), 2017, pages 401 to 416, the journal version, with the removal of motion distortion within a sweep, the map matching with the eigenvalues of the covariance of nearby map points, and the tests on the KITTI odometry benchmark

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.feature_extraction
  • a full proof of time.mapping_step
  • a full proof of time.odometry_step
  • a full proof of space.map
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example