Algorithmadvanced
MonoSLAM
Also called Davison monocular SLAM.
Davison's real-time EKF SLAM with one camera, a sparse map of image patch landmarks and a constant velocity motion model.
- Solves
- Online SLAM
- Time
- O(k m^2) frame
- Space
- O(m^2) extra
- Where
- k = the number of features measured in one frame; m = the number of features in the map
- Model
- Real RAM
- Properties
- deterministicnot exactonlinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Andrew Davison, Ian Reid, Nicholas Molton, Olivier Stasse, 2003
MonoSLAM estimates the 3D motion of a single hand-held or robot-mounted camera and a sparse map of 3D points, in real time, from the images alone. It is EKF SLAM with a camera as the only sensor: one extended Kalman filter holds the camera pose and velocity and all the map points, each frame is a prediction by a constant velocity model and an update with the image positions of a few points. It differs from visual odometry, which estimates the motion from frame to frame and keeps no lasting map, so its error grows without bound even when the camera returns to a place it has seen. It also differs from bundle adjustment, which optimizes all cameras and points together by nonlinear least squares. MonoSLAM never revisits old frames: it keeps one Gaussian over the present state and the map, and pays for the map with a cost that grows with the square of its size. Davison, Reid, Molton and Stasse (2007) ran it at 30 frames per second with about 12 visible features.
In plain words
A person walks around a room with a single camera. The program keeps a small list of distinct image patches, such as corners of objects, and a guess of where each is in 3D. It also keeps a guess of where the camera is and how fast it moves. For each new image, it predicts where the camera is now and where each patch should appear. It looks for each patch only in a small area around that prediction, which is fast. The positions where it finds the patches correct both the camera and the patches. A new patch at first has an unknown distance, so the program tries many distances along its line of sight and keeps the ones that fit the next images.
The problem
The input is a video from one calibrated camera, with no odometry. The output, at every frame, is the camera pose and a map of 3D points with their uncertainty. This is online SLAM with a bearing-only sensor: one image point gives the direction to a map point but not its distance, so the depth of a new point is unknown, and with one camera the overall scale of the map and the motion cannot be found from the images alone. MonoSLAM fixes the scale at the start with a known target of about four features in front of the camera.
The state is the camera position , its orientation as a unit quaternion , its velocity and angular velocity (13 numbers), and three coordinates for each map point. The pinhole camera model, with the radial distortion of the lens, maps a point to its image position.
The algorithm
MONOSLAM_FRAME(μ, Σ, image I_t, Δt)- 1
r ← r + v Δt; q ← q ⊗ quat(ω Δt); Σ ← F Σ Fᵀ + G Q Gᵀ ▷ v, ω keep their mean; Q is the noise of V, Ω - 2
for each map point i that should be in view do - 3
ẑ_i ← project(r, q, y_i); H_i ← ∂ẑ_i/∂(state); S_i ← H_i Σ H_iᵀ + R - 4
search for the stored patch of point i by normalized cross-correlation, only inside the ellipse of S_i - 5
EKF update of μ and Σ with all matched points - 6
for each new point that is still a ray: weight its depth samples; if the spread is small, make it a 3D point - 7
if too few points are visible then start a new corner as a ray with depth samples from 0.5 m to 5 m - 8
delete points that often fail to match; return μ, Σ
The motion model. The camera has no odometry, so the filter assumes that the velocity and the angular velocity stay the same, with an unknown random change in each frame. This "constant velocity, constant angular velocity" model with Gaussian accelerations lets the filter follow smooth hand motion. A sudden jerk larger than the noise allows makes the prediction wrong and the search regions miss.
Active search (line L4). The innovation covariance gives an ellipse in the image where the patch must be with high probability. Searching only there, by normalized cross-correlation of the stored pixel patch, keeps the image work small and avoids many false matches. The size of the ellipse also tells which points are most useful to measure.
New points (lines L6 and L7). A new point is found by the Shi-Tomasi corner detector. Its depth is unknown, so it starts as a line in 3D with 100 depth samples spread uniformly from 0.5 m to 5 m. As the camera moves, the line projects to a line in the next images, along which the patch is searched; the samples that fit get more weight. When the ratio of the standard deviation of the depth to its mean drops below 0.3, the point becomes a normal 3D map point with a Gaussian. The later inverse depth form of Civera, Davison and Montiel lets a new point enter the filter at once.
The code is a toy. The Python file keeps the filter structure of lines L1 to L8 in a plane: the camera is with its velocities, the image has one coordinate, and there is no image processing, so a "detection" is a pixel with the id of its true point. It applies the matched points one at a time, which for a linear model gives the same result as one joint update. In a simulated run, a camera that moves 1.5 m to the side and speeds up from 0.3 m/s to 0.7 m/s ends within 5 cm of the true position on three seeds, while the prediction alone ends more than 0.5 m off. This is a measurement of the toy, not of MonoSLAM.
Example
The prediction. At 30 frames per second, s. A camera at the origin that moves with m/s is predicted at m in the next frame. If the random acceleration has a standard deviation of m/s², the velocity can change by m/s in one frame, and the position by about m more. These numbers are an example, not the values of the paper.
The depth of a new point. At the start, the 100 depth samples are uniform on m: the mean is 2.75 m and the standard deviation is m, a ratio of 0.47. After a few frames, suppose the samples that keep their weight are spread uniformly on m. The mean is 2.0 m and the standard deviation is m, a ratio of 0.14, below 0.3. The point now enters the map as a 3D point at depth 2.0 m along its ray.
Correctness
MonoSLAM is an extended Kalman filter, so it has the properties of EKF SLAM, and no more. If the models were linear and Gaussian, the filter would give the exact posterior. They are not: the projection is nonlinear, and so is the quaternion motion. So the filter is a local approximation that works when the errors stay small compared with the curvature of the models, which the high frame rate helps with. Like nonlinear EKF SLAM, it can become inconsistent, that is, more confident than its errors justify. The scale of the map comes only from the known target at the start; after that it is held by the correlations in the filter and drifts slowly. These are measured properties of the system, not theorems. The paper reports its accuracy from experiments, such as the augmented reality results of its Section 4 and the humanoid robot runs of its Section 5.
Proof: The filter steps of the planar MonoSLAM core are the EKF steps they claim to befull
Setting. This proof is about the toy core in impl/python/monoslam.py, not about the full system of Davison, Reid, Molton and Stasse (2007). The world is a plane. The state is the camera and the map points , two numbers each, with a mean and a covariance of size . A point at in the camera frame, with , gives the pixel , read with Gaussian noise of variance .
Claim. (1) The prediction of line L1 computes for the constant velocity model, and changes only the camera rows and columns. (2) Lines L3 to L5 are an EKF update with one scalar reading, and the gate of line L4 accepts a reading that follows the model with probability 0.99. (3) The depth samples of line L6 hold the posterior of the depth on a grid of 100 values, under the stated independence approximation. (4) The augmentation in add_point is the first-order covariance of the joint state with the new point. (5) The deletion of line L8 is an exact marginalization. (6) One frame costs time with readings and needs memory. None of this makes the filter exact or consistent: the projection is not linear, so the EKF is a local approximation (see the end).
(1) The prediction
The model of each frame of length is the one of Davison et al. for each coordinate: an unknown velocity change enters at the start of the frame, then the camera moves with the new velocity. For the coordinate, and , and the same for and for with . With for the linear velocities and for the angular one, a random acceleration of standard deviation over the frame gives this velocity change. The map points do not move.
The model is linear: and , where is the identity with , and adds to the position and to the velocity. So the new mean is , which is what the code computes, and the new covariance is . For one pair (position , velocity ) with noise , has the entries at , at and and at , which are the four additions in the code.
differs from the identity only in the camera rows, so changes only the camera rows of , and changes only its camera columns. The code does these two steps in place: first the six camera rows, then the six camera entries of each row. The map block is not touched, and the cross block becomes , where is the camera part. The test test_prediction_moves_only_the_camera compares the result with the dense product on a full random covariance.
(2) The update of one point and the gate
For the point at index , the predicted pixel is , with , and the code linearizes at the current mean: , where has nonzero entries only at the camera pose and at .
The derivatives are the chain rule. With , and , we have and . Next and , the derivatives by are the negatives of these, and , . These are the formulas of project_jac; the test compares them with central differences.
The innovation is and its variance is , a number. The Kalman gain is . The update and is the EKF update. The code forms once, from the five nonzero entries of , and then subtracts the outer product ; this is the same matrix, because for a symmetric . The result stays symmetric.
The code updates with one point at a time, and it computes again at the new mean before the next point. For a linear model with independent reading noises, a sequence of scalar updates gives exactly the joint update with all the readings: the posterior after both readings is the same Gaussian whatever the order, since each update multiplies the density by one Gaussian factor. For the nonlinear model the two differ to second order, and the sequential form uses the newer linearization point.
The gate. If the model holds, , so follows the chi-square distribution with one degree of freedom, and . Line L4 accepts the reading only if , the value CHI2[(1, 0.99)]. The width of the gate in pixels is ; this is the planar form of the search ellipse.
(3) The depth samples
A new point starts as a ray from the camera position at the angle of its first reading, and its depth is unknown. The code keeps the values for , which are uniform on m, with the log weights , a uniform prior on the grid.
When a later frame reads the point at , each sample gives the point , the pixel and the variance , where holds the derivatives by the camera pose. The code adds , up to a constant that is the same for all , to . By Bayes' rule on the finite set , , so the normalized weights are the posterior, if the readings of different frames are independent given . That is an approximation: the readings also depend on the camera poses, whose errors are correlated from frame to frame. Samples behind the camera get the weight zero.
stats returns the mean and the variance of this discrete posterior. It subtracts the largest before the exponential, which changes no normalized weight and avoids an underflow of all the weights.
The example of the page. For equal weights on points with spacing , the variance is . At the start and , so the standard deviation is m, the mean is 2.75 m, and the ratio is 0.472. The page uses the continuous value m. If only the 22 samples in keep their weight, from 1.5125 m to 2.4575 m, the mean is 1.985 m and the standard deviation is m, a ratio of 0.144, below the threshold 0.3. The test test_depth_samples_page_example checks these numbers.
(4) The new map point
When the ratio drops below 0.3, the code puts the point into the filter with the function , where is the bearing of the present reading and is the distance from the present camera position to the ray point at the mean depth. The inputs and are treated as independent of the state, with the variances and (the variance of the depth samples).
Let , and be the derivatives of by the camera pose, by and by . To first order , with the three terms independent. So the covariance of with any state entry is , and the covariance of with itself is . These are the two new rows and columns that add_point appends. The derivatives are , and , since . The test test_add_point_covariance compares all of this with central differences of .
Two approximations remain, and they make the new point more certain than it should be. The depth was estimated with the help of the camera estimate, so it is not independent of the state. And is the spread along the first ray, used here along the present one.
(5) Deleting a point
Line L8 deletes a point that was in view in at least 10 frames and was not found in more than half of them. The code removes its two entries from and its two rows and columns from . For a Gaussian, the marginal of the other variables has the mean and the covariance with these entries removed, so the deletion is exact marginalization and the rest of the filter is unchanged. The test test_delete_points_that_fail checks that the arrays stay consistent.
(6) Cost
Let . The prediction changes 6 rows of length and 6 entries in each of rows, with at most two terms per entry, so it costs . Each scalar update computes from five columns, , and subtracts an outer product, . Line L3 costs per point. So readings cost , and the frame loop over the points adds . Each ray costs per frame, and the number of rays is at most the target. The augmentation is for the new rows plus the appends, and a deletion is at most, which happens at most once per point. The covariance needs memory. This is the bound of the page.
What is not proved
The EKF linearizes at the mean. The posterior is Gaussian only if the model is linear, so for this model the filter is an approximation, and its error depends on how far the mean is from the true state compared with the curvature of the projection. The filter can become overconfident, as nonlinear EKF SLAM can. The test test_simulation_measurement is a measurement of this toy, not a proof: on three seeds the camera moves 1.5 m to the side, the known points leave the view, and the final camera error stays below 5 cm, while the prediction alone ends more than 0.5 m off.
Complexity
- Per frame: for the EKF update with measured points and map points, as in EKF SLAM, plus the image work of the active search, which grows with the area of the search ellipses.
- The prediction: only the 13 camera rows and columns of the covariance change, .
- Memory: for the covariance.
The quadratic cost limits the map to a small number of points, enough for a room or a desk. This is the main limit of the method.
Properties
- Real time with one camera. It was among the first systems to show SLAM with a single camera at frame rate, with no odometry and no other sensor.
- A persistent map. Unlike visual odometry, it keeps the points and recognizes them when the camera returns, so the error does not grow without bound in a small area.
- Sparse map. It keeps only the points that it needs to track the camera, not a dense model of the scene.
- Small area. The cost and the size of the patches limit it to a room-sized space.
Variants and improvements
- Inverse depth. Civera, Davison and Montiel parametrize a new point by its inverse depth along its first ray. The filter can then use it from the first frame, including points that are very far away.
- Keyframe methods. Later systems such as PTAM and ORB-SLAM track the camera against the map in each frame and refine the map by bundle adjustment over selected keyframes in a separate thread. They handle much larger maps than an EKF over all points.
- Submaps. Splitting the map into small local filters bounds the cost per frame.
When to use it
MonoSLAM shows the ideas of filter-based visual SLAM in a compact form: one state, active search and delayed initialization of the depth. For a new system, keyframe methods with bundle adjustment usually give better accuracy for the same computation, as shown by the later systems above. A small EKF over the camera and a few points is still a reasonable choice on a very small processor or when a covariance is needed at every frame.
Pitfalls
- Fast motion. If the camera moves faster than the motion noise allows, the patches fall outside the search ellipses and tracking is lost.
- A wrong match. A single wrong match in the EKF update can pull the whole state far off. Gate the matches, and check that the set of matches agrees.
- Unknown scale. Without the known target, or another source of scale, the map has an arbitrary scale.
- Large maps. The cost grows as ; the filter slows down as the map grows.
- Patches that change. A patch seen from a new angle looks different. MonoSLAM warps the stored patch by the predicted view to reduce this.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/monoslam/. The authors are listed in prov/HXRXPQ.jsonl.
"""A TOY core of MonoSLAM, in the plane. It is not MonoSLAM itself.
It keeps the structure of Davison, Reid, Molton and Stasse (2007): one EKF
over a camera with a constant velocity model and a sparse map of points;
a search for each point only inside the gate of its predicted image
position; new points that start as a ray with 100 depth samples from 0.5 m
to 5 m and enter the map when the depth spread is small; deletion of points
that often fail to match. What it leaves out makes it a toy:
- The world is a plane and the camera has a one-dimensional image: a point
at (a, b) in the camera frame (a > 0) appears at the pixel u = F b / a.
- There is no image processing. A "detection" is a pixel with the id of the
true point, and the id stands for the appearance of the image patch: the
search of line L4 finds a point if its detection lies inside the gate.
- The state has no quaternion: the camera is (x, y, theta, vx, vy, omega).
MonoSLAM(...) the filter; .frame(detections) is one step, lines L1 to L8
project(cam, p), project_jac the camera model and its Jacobians
simulate_detections(...) a simulated image for the tests
"""
import math
import robest
F = 500.0 # the focal length in pixels
HALF_WIDTH = 400.0 # the image spans u in [-400, 400], about +-38.7 degrees
CAM = 6 # x, y, theta, vx, vy, omega
def project(cam, p):
"""Return the pixel of the world point p, or None if p is behind the camera."""
c, s = math.cos(cam[2]), math.sin(cam[2])
dx, dy = p[0] - cam[0], p[1] - cam[1]
a = c * dx + s * dy
b = -s * dx + c * dy
if a <= 1e-9:
return None
return F * b / a
def project_jac(cam, p):
"""Return (d u / d(x, y, theta), d u / d p) at the camera pose and the point."""
c, s = math.cos(cam[2]), math.sin(cam[2])
dx, dy = p[0] - cam[0], p[1] - cam[1]
a = c * dx + s * dy
b = -s * dx + c * dy
# u = F b / a; du/da = -F b / a^2, du/db = F / a
ua, ub = -F * b / (a * a), F / a
dp = [ua * c - ub * s, ua * s + ub * c] # d u / d p
dth = ua * b + ub * (-a) # da/dtheta = b, db/dtheta = -a
return [-dp[0], -dp[1], dth], dp
def in_view(u):
return u is not None and -HALF_WIDTH <= u <= HALF_WIDTH
class Ray:
"""A new point whose depth is not known yet: 100 depth samples along a ray."""
def __init__(self, origin, angle, n=100, near=0.5, far=5.0):
self.origin, self.angle = origin, angle
self.depths = [near + (far - near) * (k + 0.5) / n for k in range(n)]
self.logw = [0.0] * n
def point(self, d):
return [self.origin[0] + d * math.cos(self.angle), self.origin[1] + d * math.sin(self.angle)]
def stats(self):
top = max(self.logw)
w = [math.exp(v - top) for v in self.logw]
t = sum(w)
mean = sum(wi * d for wi, d in zip(w, self.depths)) / t
var = sum(wi * (d - mean) ** 2 for wi, d in zip(w, self.depths)) / t
return mean, var
class MonoSLAM:
"""The EKF state is the camera (6 numbers) and then two numbers per map point."""
def __init__(self, cam, cam_cov, known_points, known_var=1e-6, accel_sd=1.0, alpha_sd=1.0, pixel_sd=1.0, dt=1.0 / 30.0, target=6, ratio=0.3):
self.mu = list(cam)
n = CAM + 2 * len(known_points)
self.cov = [[0.0] * n for _ in range(n)]
for i in range(CAM):
for j in range(CAM):
self.cov[i][j] = cam_cov[i][j]
self.ids = []
for pid, p in known_points: # the known target fixes the scale
k = len(self.mu)
self.mu += list(p)
self.cov[k][k] = self.cov[k + 1][k + 1] = known_var
self.ids.append(pid)
self.tries = {pid: [0, 0] for pid, _ in known_points} # attempts, failures
self.rays = {}
self.accel_sd, self.alpha_sd, self.r = accel_sd, alpha_sd, pixel_sd * pixel_sd
self.dt, self.target, self.ratio = dt, target, ratio
# -------------------------------------------------------------- the EKF parts
def predict(self):
"""Constant velocity: only the camera rows and columns of the covariance change."""
dt, mu, cov = self.dt, self.mu, self.cov
mu[0] += mu[3] * dt
mu[1] += mu[4] * dt
mu[2] = robest.wrap_angle(mu[2] + mu[5] * dt)
fc = [[1.0 if i == j else 0.0 for j in range(CAM)] for i in range(CAM)]
fc[0][3] = fc[1][4] = fc[2][5] = dt
n = len(mu)
# rows of F Sigma for the camera; the map rows stay
rows = [[sum(fc[i][k] * cov[k][j] for k in range(CAM) if fc[i][k] != 0.0) for j in range(n)] for i in range(CAM)]
for i in range(CAM):
cov[i] = rows[i]
for i in range(n): # then (F Sigma) F^T on the camera columns
row = cov[i]
new = [sum(row[k] * fc[j][k] for k in range(CAM) if fc[j][k] != 0.0) for j in range(CAM)]
row[:CAM] = new
qa = (self.accel_sd * dt) ** 2
qw = (self.alpha_sd * dt) ** 2
# a velocity change V over the frame moves the position by V dt
for pos, vel, q in ((0, 3, qa), (1, 4, qa), (2, 5, qw)):
cov[pos][pos] += q * dt * dt
cov[pos][vel] += q * dt
cov[vel][pos] += q * dt
cov[vel][vel] += q
def scalar_update(self, h, nu, s):
"""EKF update with one scalar reading: h is a dict {index: derivative}."""
cov, n = self.cov, len(self.mu)
pht = [sum(cov[i][k] * v for k, v in h.items()) for i in range(n)]
gain = [x / s for x in pht]
for i in range(n):
self.mu[i] += gain[i] * nu
gi = gain[i]
if gi != 0.0:
row = cov[i]
for j in range(n):
row[j] -= gi * pht[j]
self.mu[2] = robest.wrap_angle(self.mu[2])
def predicted(self, k):
"""Return (u_hat, h, s) for the map point at state index k, or None if out of view."""
cam, p = self.mu[:3], self.mu[k : k + 2]
u = project(cam, p)
if not in_view(u):
return None
dc, dp = project_jac(cam, p)
h = {0: dc[0], 1: dc[1], 2: dc[2], k: dp[0], k + 1: dp[1]}
s = self.r + sum(a * self.cov[i][j] * b for i, a in h.items() for j, b in h.items())
return u, h, s
# -------------------------------------------------------------- one frame
def frame(self, detections, gate=robest.CHI2[(1, 0.99)]):
"""One frame. detections maps a point id to its measured pixel u."""
self.predict() # @line L1
for idx, pid in enumerate(self.ids): # @line L2
k = CAM + 2 * idx
pred = self.predicted(k) # @line L3
if pred is None:
continue
u_hat, h, s = pred
self.tries[pid][0] += 1
u = detections.get(pid) # @line L4
if u is None or (u - u_hat) ** 2 / s > gate:
self.tries[pid][1] += 1
continue
self.scalar_update(h, u - u_hat, s) # @line L5
self.update_rays(detections) # @line L6
visible = sum(1 for idx in range(len(self.ids)) if self.predicted(CAM + 2 * idx) is not None)
for pid, u in sorted(detections.items()): # @line L7
if visible + len(self.rays) >= self.target:
break
if pid not in self.ids and pid not in self.rays:
self.rays[pid] = Ray(self.mu[:2], self.mu[2] + math.atan2(u, F))
self.delete_bad() # @line L8
def update_rays(self, detections):
cam = self.mu[:3]
for pid in list(self.rays):
ray = self.rays[pid]
u = detections.get(pid)
if u is None:
continue
for i, d in enumerate(ray.depths):
p = ray.point(d)
u_hat = project(cam, p)
if u_hat is None:
ray.logw[i] = -1e300
continue
dc, _ = project_jac(cam, p)
s = self.r + sum(dc[a] * self.cov[a][b] * dc[b] for a in range(3) for b in range(3))
ray.logw[i] += -0.5 * (u - u_hat) ** 2 / s - 0.5 * math.log(s)
mean, var = ray.stats()
if math.sqrt(var) / mean < self.ratio:
self.add_point(pid, ray, u, mean, var)
del self.rays[pid]
def add_point(self, pid, ray, u, depth_mean, depth_var):
"""Put a ray into the map: p = cam + d (cos(theta + b), sin(theta + b)), b = atan(u / F)."""
cam = self.mu[:3]
p0 = ray.point(depth_mean)
d = math.hypot(p0[0] - cam[0], p0[1] - cam[1])
b = math.atan2(u, F)
ang = cam[2] + b
c, s = math.cos(ang), math.sin(ang)
p = [cam[0] + d * c, cam[1] + d * s]
jc = [[1.0, 0.0, -d * s], [0.0, 1.0, d * c]] # d p / d (x, y, theta)
db = F / (F * F + u * u) # d b / d u
ju = [-d * s * db, d * c * db]
jd = [c, s]
n = len(self.mu)
cross = [[sum(jc[r][a] * self.cov[a][j] for a in range(3)) for j in range(n)] for r in range(2)]
pp = [[sum(cross[r][a] * jc[q][a] for a in range(3)) + ju[r] * ju[q] * self.r + jd[r] * jd[q] * depth_var for q in range(2)] for r in range(2)]
for i in range(n):
self.cov[i] += [cross[0][i], cross[1][i]]
self.cov.append(cross[0] + pp[0])
self.cov.append(cross[1] + pp[1])
self.mu += p
self.ids.append(pid)
self.tries[pid] = [0, 0]
def delete_bad(self, min_tries=10):
for idx in range(len(self.ids) - 1, -1, -1):
pid = self.ids[idx]
tries, fails = self.tries[pid]
if tries >= min_tries and 2 * fails > tries:
k = CAM + 2 * idx
del self.mu[k : k + 2]
del self.cov[k : k + 2]
for row in self.cov:
del row[k : k + 2]
del self.ids[idx]
del self.tries[pid]
def point(self, pid):
idx = self.ids.index(pid)
return self.mu[CAM + 2 * idx : CAM + 2 * idx + 2]
def simulate_detections(cam, points, rng, pixel_sd=1.0):
"""Return {id: pixel} for the points in view of the true camera, with noise."""
out = {}
for pid, p in points.items():
u = project(cam, p)
if in_view(u):
out[pid] = u + pixel_sd * rng.gauss(0.0, 1.0)
return out
rbm.py 482 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.
Conventions (Lynch and Park, Modern Robotics, 2017):
- A matrix is a list of rows. A vector is a flat list.
- hat3(w) is the skew-symmetric matrix [w], so that [w] x = w x x.
- A twist or screw is a 6-vector (omega, v), angular part first.
hat6(V) is the 4x4 matrix [[[omega], v], [0, 0]].
- A pose T is the 4x4 matrix [[R, p], [0, 1]].
- so3_exp and so3_log use exponential coordinates w = omega_hat * theta,
with theta = |w| in [0, pi] for so3_log.
- se3_exp and se3_log use 6-vectors (w, v) = S * theta.
- Quaternions are Hamilton, scalar first: q = (w, x, y, z), with i j = k.
- Angles are in radians.
The helper holds no algorithm of a robotics page except the four maps
so3_exp, so3_log, se3_exp and se3_log. The pages so3-logarithm-map and
se3-exponential-map hold their own complete versions with comments.
"""
import math
# Below this angle, the coefficient functions of the exponential and the
# logarithm are evaluated by their Taylor series. The first omitted term
# of each series is of order theta^6 and is below 3e-16 for theta < 1e-2;
# it also multiplies [w] or [w]^2, which are small. Above the threshold,
# the closed forms such as (1 - cos(theta)) / theta^2 lose at most about
# 1e-16 / theta^2 to cancellation, which [w] or [w]^2 brings to 1e-14.
SERIES_THETA = 1e-2
# Above pi - NEAR_PI, so3_log takes the axis from the symmetric part of R
# (which is (R + I) / 2 at theta = pi) and not from the skew part.
NEAR_PI = 1e-2
# A pivot whose magnitude is at most PIVOT_TOL times the largest entry of
# the matrix makes solve, inv and pinv_right raise ValueError.
PIVOT_TOL = 1e-12
# ---------------------------------------------------------------- matrices
def zeros(n, m):
"""Return the n by m zero matrix."""
return [[0.0] * m for _ in range(n)]
def eye(n):
"""Return the n by n identity matrix."""
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def _is_matrix(a):
return len(a) > 0 and isinstance(a[0], list)
def add(a, b):
"""Return a + b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a, b):
"""Return a - b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(a, s):
"""Return s * a for a vector or a matrix a and a number s."""
if _is_matrix(a):
return [[s * x for x in row] for row in a]
return [s * x for x in a]
def transpose(a):
"""Return the transpose of the matrix a."""
return [list(col) for col in zip(*a)]
def mul(a, b):
"""Return the matrix product a b."""
bt = transpose(b)
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the product of the matrix a and the vector x."""
return [sum(p * q for p, q in zip(row, x)) for row in a]
def dot(x, y):
"""Return the dot product of two vectors."""
return sum(p * q for p, q in zip(x, y))
def norm(x):
"""Return the Euclidean norm of a vector."""
return math.sqrt(dot(x, x))
def cross(a, b):
"""Return the cross product a x b of two 3-vectors."""
return [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
def _max_abs(a):
return max((abs(x) for row in a for x in row), default=0.0)
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
a is a square matrix. b is a vector or a matrix with one column per
right-hand side; the result has the same shape as b. Raise ValueError
if a pivot is at most PIVOT_TOL times the largest entry of a.
"""
n = len(a)
vec = not _is_matrix(b)
rhs = [[x] for x in b] if vec else [list(row) for row in b]
m = [list(map(float, row)) + list(map(float, r)) for row, r in zip(a, rhs)]
k = len(rhs[0]) if rhs else 0
tol = PIVOT_TOL * _max_abs(a)
for c in range(n):
piv = max(range(c, n), key=lambda r: abs(m[r][c]))
if abs(m[piv][c]) <= tol or m[piv][c] == 0.0:
raise ValueError("matrix is singular to working precision")
m[c], m[piv] = m[piv], m[c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
if f != 0.0:
row_r, row_c = m[r], m[c]
for j in range(c, n + k):
row_r[j] -= f * row_c[j]
x = [[0.0] * k for _ in range(n)]
for r in range(n - 1, -1, -1):
for j in range(k):
s = m[r][n + j] - sum(m[r][i] * x[i][j] for i in range(r + 1, n))
x[r][j] = s / m[r][r]
return [row[0] for row in x] if vec else x
def inv(a):
"""Return the inverse of the square matrix a (see solve for errors)."""
return solve(a, eye(len(a)))
def det(a):
"""Return the determinant of the square matrix a by elimination."""
n = len(a)
m = [list(map(float, row)) for row in a]
d = 1.0
for c in range(n):
piv = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[piv][c] == 0.0:
return 0.0
if piv != c:
m[c], m[piv] = m[piv], m[c]
d = -d
d *= m[c][c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
for j in range(c, n):
m[r][j] -= f * m[c][j]
return d
def cholesky(a):
"""Return the lower triangular L with a = L L^T.
a must be symmetric positive definite. Raise ValueError if a diagonal
entry of the factor is not positive.
"""
n = len(a)
low = zeros(n, n)
for i in range(n):
for j in range(i + 1):
s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
if i == j:
if s <= 0.0:
raise ValueError("matrix is not positive definite")
low[i][i] = math.sqrt(s)
else:
low[i][j] = s / low[j][j]
return low
def pinv_right(j):
"""Return the right pseudoinverse J^T (J J^T)^(-1) of a J with full row rank."""
jt = transpose(j)
return mul(jt, inv(mul(j, jt)))
# ---------------------------------------------------------------- hat and vee
def hat3(w):
"""Return the 3x3 skew-symmetric matrix [w] of a 3-vector w."""
return [
[0.0, -w[2], w[1]],
[w[2], 0.0, -w[0]],
[-w[1], w[0], 0.0],
]
def vee3(m):
"""Return the 3-vector w of a skew-symmetric matrix m = [w]."""
return [m[2][1], m[0][2], m[1][0]]
def hat6(v):
"""Return the 4x4 matrix [V] = [[[omega], v], [0, 0]] of V = (omega, v)."""
w = hat3(v[:3])
return [
[w[0][0], w[0][1], w[0][2], v[3]],
[w[1][0], w[1][1], w[1][2], v[4]],
[w[2][0], w[2][1], w[2][2], v[5]],
[0.0, 0.0, 0.0, 0.0],
]
def vee6(m):
"""Return the 6-vector (omega, v) of a 4x4 matrix [V]."""
return [m[2][1], m[0][2], m[1][0], m[0][3], m[1][3], m[2][3]]
# ---------------------------------------------------------------- rotations
def rot_x(a):
"""Return the rotation by a radians about the x axis."""
c, s = math.cos(a), math.sin(a)
return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]
def rot_y(a):
"""Return the rotation by a radians about the y axis."""
c, s = math.cos(a), math.sin(a)
return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]
def rot_z(a):
"""Return the rotation by a radians about the z axis."""
c, s = math.cos(a), math.sin(a)
return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]
def rpy(roll, pitch, yaw):
"""Return R = Rz(yaw) Ry(pitch) Rx(roll)."""
return mul(rot_z(yaw), mul(rot_y(pitch), rot_x(roll)))
def so3_exp(w):
"""Return exp([w]) for exponential coordinates w = omega_hat * theta.
Rodrigues' formula in the form I + A [w] + B [w]^2 with
A = sin(theta) / theta and B = (1 - cos(theta)) / theta^2.
"""
t = norm(w)
if t < SERIES_THETA:
t2 = t * t
a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
else:
a = math.sin(t) / t
b = (1.0 - math.cos(t)) / (t * t)
k = hat3(w)
k2 = mul(k, k)
return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]
def so3_log(r):
"""Return w = omega_hat * theta with exp([w]) = r and theta in [0, pi].
theta = atan2(|s|, c), where c = (trace(r) - 1) / 2 = cos(theta) and
s = vee(r - r^T) / 2 = sin(theta) omega_hat. For theta below
SERIES_THETA, w = s (1 + theta^2 / 6 + 7 theta^4 / 360). For theta
above pi - NEAR_PI, the axis comes from the symmetric part
((r + r^T) / 2 - c I) / (1 - c) = omega_hat omega_hat^T, and its sign
from s. At theta = pi both signs are valid; the sign is then chosen so
that the largest component of the axis is positive.
"""
c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
c = max(-1.0, min(1.0, c))
s = [(r[2][1] - r[1][2]) / 2.0, (r[0][2] - r[2][0]) / 2.0, (r[1][0] - r[0][1]) / 2.0]
sn = norm(s)
t = math.atan2(sn, c)
if t < SERIES_THETA:
t2 = t * t
f = 1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0
return [f * x for x in s]
if t <= math.pi - NEAR_PI:
return [t / sn * x for x in s]
b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
# b = (1 - c) omega_hat omega_hat^T. Its column k with the largest
# diagonal entry is (1 - c) omega_k omega_hat, with omega_k^2 >= 1/3.
k = max(range(3), key=lambda i: b[i][i])
col = [b[i][k] for i in range(3)]
axis = [x / norm(col) for x in col]
if dot(axis, s) < 0.0 or (dot(axis, s) == 0.0 and axis[k] < 0.0):
axis = [-x for x in axis]
return [t * x for x in axis]
# ---------------------------------------------------------------- poses
def make_T(r, p):
"""Return the 4x4 pose [[r, p], [0, 1]]."""
return [
[r[0][0], r[0][1], r[0][2], p[0]],
[r[1][0], r[1][1], r[1][2], p[1]],
[r[2][0], r[2][1], r[2][2], p[2]],
[0.0, 0.0, 0.0, 1.0],
]
def _rp(t):
return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]
def T_inv(t):
"""Return the inverse [[R^T, -R^T p], [0, 1]] of a pose t."""
r, p = _rp(t)
rt = transpose(r)
return make_T(rt, [-x for x in matvec(rt, p)])
def T_apply(t, x):
"""Return R x + p, the image of the point x under the pose t."""
r, p = _rp(t)
return add(matvec(r, x), p)
def se3_exp(xi):
"""Return exp([xi]) for a 6-vector xi = (w, v) = S * theta.
The rotation is so3_exp(w). The translation is G v with
G = I + B [w] + C [w]^2, B = (1 - cos(theta)) / theta^2 and
C = (theta - sin(theta)) / theta^3, theta = |w|. For w = 0 this is a
translation by v.
"""
w, v = xi[:3], xi[3:]
t = norm(w)
if t < SERIES_THETA:
t2 = t * t
b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
else:
b = (1.0 - math.cos(t)) / (t * t)
c = (t - math.sin(t)) / (t * t * t)
k = hat3(w)
k2 = mul(k, k)
g = [[(1.0 if i == j else 0.0) + b * k[i][j] + c * k2[i][j] for j in range(3)] for i in range(3)]
return make_T(so3_exp(w), matvec(g, v))
def se3_log(t):
"""Return the 6-vector xi = (w, v) with se3_exp(xi) = t and |w| in [0, pi].
w = so3_log(R) and v = G^(-1) p with
G^(-1) = I - [w] / 2 + D [w]^2, D = (1 - (theta / 2) cot(theta / 2)) / theta^2.
"""
r, p = _rp(t)
w = so3_log(r)
th = norm(w)
if th < SERIES_THETA:
t2 = th * th
d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
else:
half = th / 2.0
d = (1.0 - half * math.cos(half) / math.sin(half)) / (th * th)
k = hat3(w)
k2 = mul(k, k)
gi = [[(1.0 if i == j else 0.0) - 0.5 * k[i][j] + d * k2[i][j] for j in range(3)] for i in range(3)]
return w + matvec(gi, p)
def adjoint(t):
"""Return the 6x6 adjoint [[R, 0], [[p] R, R]] of a pose t."""
r, p = _rp(t)
pr = mul(hat3(p), r)
out = zeros(6, 6)
for i in range(3):
for j in range(3):
out[i][j] = r[i][j]
out[i + 3][j + 3] = r[i][j]
out[i + 3][j] = pr[i][j]
return out
# ---------------------------------------------------------------- quaternions
def quat_mul(q, r):
"""Return the Hamilton product q r of quaternions (w, x, y, z)."""
a1, b1, c1, d1 = q
a2, b2, c2, d2 = r
return [
a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
]
def quat_conj(q):
"""Return the conjugate (w, -x, -y, -z)."""
return [q[0], -q[1], -q[2], -q[3]]
def quat_to_rot(q):
"""Return the rotation matrix of the quaternion q, so that (0, R v) = q (0, v) q*.
q need not be of unit length; the result is the rotation of q / |q|.
"""
w, x, y, z = q
n = w * w + x * x + y * y + z * z
s = 2.0 / n
return [
[1.0 - s * (y * y + z * z), s * (x * y - w * z), s * (x * z + w * y)],
[s * (x * y + w * z), 1.0 - s * (x * x + z * z), s * (y * z - w * x)],
[s * (x * z - w * y), s * (y * z + w * x), 1.0 - s * (x * x + y * y)],
]
def quat_from_axis_angle(axis, angle):
"""Return (cos(angle / 2), sin(angle / 2) axis / |axis|).
A zero axis is allowed only with angle 0 (the identity); otherwise
raise ValueError.
"""
n = norm(axis)
if n == 0.0:
if angle == 0.0:
return [1.0, 0.0, 0.0, 0.0]
raise ValueError("zero axis with a nonzero angle")
s = math.sin(angle / 2.0) / n
return [math.cos(angle / 2.0), s * axis[0], s * axis[1], s * axis[2]]
# ---------------------------------------------------------------- derivatives
def num_jacobian(f, x, h=1e-6):
"""Return the Jacobian of f at x by central differences with step h.
f maps a list of n numbers to a list of m numbers; the result is m by n.
"""
cols = []
for i in range(len(x)):
xp = list(x)
xm = list(x)
xp[i] += h
xm[i] -= h
fp, fm = f(xp), f(xm)
cols.append([(a - b) / (2.0 * h) for a, b in zip(fp, fm)])
return transpose(cols)
# ---------------------------------------------------------------- self-test
def self_test():
"""Check the area check values; return True or raise AssertionError."""
r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
w = so3_log(want)
assert abs(norm(w) - 2.0943951) < 1e-7
assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
return True
robest.py 149 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small estimation helpers for the localization and SLAM pages.
Vectors are lists of floats and matrices are lists of rows, as in rbm.py.
The notation follows Thrun, Burgard and Fox, Probabilistic Robotics (2005).
wrap_angle(a) a wrapped to [-pi, pi)
gauss_sample(rng, mean, cov) one draw of N(mean, cov), by a Cholesky factor
gauss_pdf(x, mean, cov) the density of N(mean, cov) at x
mahalanobis2(x, mean, cov) (x - mean)^T cov^(-1) (x - mean)
low_variance_resample(rng, w) indices of a systematic (low variance) resample
logodds(p), prob_from_logodds(l) l = log(p / (1 - p)) and its inverse
CHI2[(dof, level)] chi-square quantiles for gates, dof 1 to 3
gauss_pdf and mahalanobis2 also take plain numbers: then cov is a variance.
This module holds no filter, no SLAM back end and no planner.
"""
import math
import rbm
CHI2 = {
(1, 0.95): 3.841,
(1, 0.99): 6.635,
(2, 0.95): 5.991,
(2, 0.99): 9.210,
(3, 0.95): 7.815,
(3, 0.99): 11.345,
}
_TWO_PI = 2.0 * math.pi
def wrap_angle(a):
"""Return a + 2 pi k in [-pi, pi), with ((a + pi) mod 2 pi) - pi.
An angle that is already in [-pi, pi) comes back unchanged, so that
small angles keep all their digits.
"""
if -math.pi <= a < math.pi:
return float(a)
w = math.fmod(a + math.pi, _TWO_PI)
if w < 0.0:
w += _TWO_PI
w -= math.pi
if w >= math.pi: # rounding can give exactly pi
w -= _TWO_PI
return w
def _as_vector(x):
if isinstance(x, (int, float)):
return [float(x)], True
return [float(v) for v in x], False
def _as_matrix(cov, scalar):
if scalar:
if isinstance(cov, (int, float)):
return [[float(cov)]]
return [[float(cov[0][0])]]
return [[float(v) for v in row] for row in cov]
def gauss_sample(rng, mean, cov):
"""Draw x = mean + L z, with cov = L L^T and z standard normal.
rng is a random.Random. cov must be symmetric positive definite.
A number for mean (with a variance for cov) gives a number.
"""
mu, scalar = _as_vector(mean)
if scalar:
var = float(cov) if isinstance(cov, (int, float)) else float(cov[0][0])
if var < 0.0:
raise ValueError("negative variance")
return mu[0] + math.sqrt(var) * rng.gauss(0.0, 1.0)
L = rbm.cholesky(_as_matrix(cov, False))
z = [rng.gauss(0.0, 1.0) for _ in mu]
return [mu[i] + sum(L[i][j] * z[j] for j in range(i + 1)) for i in range(len(mu))]
def mahalanobis2(x, mean, cov):
"""Return the squared Mahalanobis distance (x - mean)^T cov^(-1) (x - mean)."""
xv, scalar = _as_vector(x)
mv, _ = _as_vector(mean)
if len(xv) != len(mv):
raise ValueError("x and mean differ in size")
d = [a - b for a, b in zip(xv, mv)]
S = _as_matrix(cov, scalar)
if len(d) == 1:
return d[0] * d[0] / S[0][0]
y = rbm.solve(S, d)
return sum(a * b for a, b in zip(d, y))
def gauss_pdf(x, mean, cov):
"""Return the density of N(mean, cov) at x."""
xv, scalar = _as_vector(x)
S = _as_matrix(cov, scalar)
k = len(xv)
det = S[0][0] if k == 1 else rbm.det(S)
if det <= 0.0:
raise ValueError("covariance is not positive definite")
m2 = mahalanobis2(xv, mean if not scalar else [mean], S)
return math.exp(-0.5 * m2) / math.sqrt((_TWO_PI ** k) * det)
def low_variance_resample(rng, weights):
"""Return len(weights) indices drawn by the low variance sampler.
This is systematic resampling (Thrun et al. 2005, Table 4.4): one
uniform offset r in [0, 1/N), and the N points r + m / N select the
indices through the cumulative weights. The weights need not sum to 1.
"""
n = len(weights)
if n == 0:
return []
total = float(sum(weights))
if total <= 0.0 or any(w < 0.0 for w in weights):
raise ValueError("weights must be nonnegative with a positive sum")
r = rng.random() / n
c = weights[0] / total
i = 0
out = []
for m in range(n):
u = r + m / n
while u > c and i < n - 1:
i += 1
c += weights[i] / total
out.append(i)
return out
def logodds(p):
"""Return log(p / (1 - p)) for p in (0, 1)."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
return math.log(p / (1.0 - p))
def prob_from_logodds(l):
"""Return p = 1 - 1 / (1 + exp(l)), the inverse of logodds, without overflow."""
if l >= 0.0:
return 1.0 / (1.0 + math.exp(-l))
e = math.exp(l)
return e / (1.0 + e)
test_monoslam.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/monoslam/. The authors are listed in prov/HXRXPQ.jsonl.
import math
import random
import monoslam as M
import rbm
import robest
def small_cov(pos=1e-6, vel=0.01):
cov = [[0.0] * M.CAM for _ in range(M.CAM)]
for i in range(3):
cov[i][i] = pos
cov[i + 3][i + 3] = vel
return cov
KNOWN = [(0, [1.5, -0.3]), (1, [1.5, 0.3]), (2, [1.8, -0.1]), (3, [1.8, 0.2])]
def test_projection_jacobians():
rng = random.Random(1)
for _ in range(20):
cam = [rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-0.5, 0.5)]
p = [cam[0] + 2.0 * math.cos(cam[2]) + rng.uniform(-0.3, 0.3), cam[1] + 2.0 * math.sin(cam[2]) + rng.uniform(-0.3, 0.3)]
dc, dp = M.project_jac(cam, p)
nc = rbm.num_jacobian(lambda c: [M.project(c, p)], cam)[0]
npnt = rbm.num_jacobian(lambda q: [M.project(cam, q)], p)[0]
assert max(abs(a - b) for a, b in zip(dc, nc)) < 1e-4
assert max(abs(a - b) for a, b in zip(dp, npnt)) < 1e-4
assert M.project([0, 0, 0], [-1.0, 0.0]) is None
assert M.project([0, 0, 0], [2.0, 0.4]) == 100.0
def test_prediction_moves_only_the_camera():
s = M.MonoSLAM([0.0, 0.0, 0.0, 0.3, 0.0, 0.0], small_cov(1e-4, 0.01), KNOWN, known_var=1e-4)
rng = random.Random(2)
n = len(s.mu)
for i in range(n): # a full, correlated covariance
for j in range(i + 1):
v = 1e-5 * rng.uniform(-1, 1) if i != j else s.cov[i][i]
s.cov[i][j] = s.cov[j][i] = v
before = [row[:] for row in s.cov]
s.predict()
assert abs(s.mu[0] - 0.01) < 1e-15 and s.mu[1] == 0.0
dt = s.dt
f = rbm.eye(n)
f[0][3] = f[1][4] = f[2][5] = dt
want = rbm.mul(rbm.mul(f, before), rbm.transpose(f))
for pos, vel, q in ((0, 3, (s.accel_sd * dt) ** 2), (1, 4, (s.accel_sd * dt) ** 2), (2, 5, (s.alpha_sd * dt) ** 2)):
want[pos][pos] += q * dt * dt
want[pos][vel] += q * dt
want[vel][pos] += q * dt
want[vel][vel] += q
assert max(abs(want[i][j] - s.cov[i][j]) for i in range(n) for j in range(n)) < 1e-15
for i in range(M.CAM, n): # the map block stays
for j in range(M.CAM, n):
assert s.cov[i][j] == before[i][j]
def test_depth_samples_page_example():
ray = M.Ray([0.0, 0.0], 0.0)
mean, var = ray.stats()
assert abs(mean - 2.75) < 1e-12
assert abs(math.sqrt(var) / mean - 0.47) < 0.005
ray.logw = [0.0 if 1.5 <= d <= 2.5 else -1e300 for d in ray.depths]
mean, var = ray.stats() # the 22 samples inside [1.5, 2.5] run from 1.5125 to 2.4575
assert abs(mean - 2.0) < 0.02
assert abs(math.sqrt(var) / mean - 0.144) < 0.005 and math.sqrt(var) / mean < 0.3
def test_gate_and_update():
s = M.MonoSLAM([0.0, 0.0, 0.0, 0.0, 0.0, 0.0], small_cov(1e-4, 1e-6), KNOWN[:1], known_var=1e-4)
s.predict()
u_hat, h, sd2 = s.predicted(M.CAM)
assert abs(u_hat - M.project([0, 0, 0], KNOWN[0][1])) < 1e-12
far = u_hat + 4.0 * math.sqrt(sd2) # 16 > 6.635: rejected
s.dt = 0.0 # no motion and no process noise, so the frame is only the update
s.frame({0: far})
assert s.tries[0] == [1, 1]
near = u_hat + 1.0
cov00 = s.cov[1][1]
s.frame({0: near})
assert s.tries[0] == [2, 1]
assert s.cov[1][1] < cov00 # the reading reduced the uncertainty
assert 2 * s.tries[0][1] <= s.tries[0][0]
def test_add_point_covariance():
s = M.MonoSLAM([0.2, -0.1, 0.1, 0.0, 0.0, 0.0], small_cov(1e-3, 1e-2), KNOWN[:1], known_var=1e-3)
rng = random.Random(3)
n = len(s.mu)
for i in range(n):
for j in range(i):
s.cov[i][j] = s.cov[j][i] = 1e-4 * rng.uniform(-1, 1)
before = [row[:] for row in s.cov]
u, depth, dvar = 37.0, 2.2, 0.05
ray = M.Ray(s.mu[:2], s.mu[2] + math.atan2(u, M.F))
s.add_point(9, ray, u, depth, dvar)
def g(z): # z = (x, y, theta, u, d)
a = z[2] + math.atan2(z[3], M.F)
return [z[0] + z[4] * math.cos(a), z[1] + z[4] * math.sin(a)]
z0 = s.mu[:3] + [u, depth]
assert max(abs(a - b) for a, b in zip(g(z0), s.point(9))) < 1e-12
jz = rbm.num_jacobian(g, z0)
# the new rows: J_cam Sigma_cam,all, and J Sigma_z J^T with u and d independent
for j in range(n):
for r in range(2):
want = sum(jz[r][a] * before[a][j] for a in range(3))
assert abs(s.cov[n + r][j] - want) < 1e-8
assert s.cov[j][n + r] == s.cov[n + r][j]
for r in range(2):
for q in range(2):
want = sum(jz[r][a] * before[a][b] * jz[q][b] for a in range(3) for b in range(3))
want += jz[r][3] * jz[q][3] * s.r + jz[r][4] * jz[q][4] * dvar
assert abs(s.cov[n + r][n + q] - want) < 1e-8
def test_delete_points_that_fail():
s = M.MonoSLAM([0.0, 0.0, 0.0, 0.0, 0.0, 0.0], small_cov(1e-6, 1e-8), KNOWN, known_var=1e-6)
s.dt = 0.0
rng = random.Random(4)
true = [0.0, 0.0, 0.0]
pts = dict(KNOWN)
for _ in range(12): # point 3 is never found
det = M.simulate_detections(true, pts, rng)
del det[3]
s.frame(det)
assert s.ids == [0, 1, 2] and len(s.mu) == M.CAM + 6 and len(s.cov) == M.CAM + 6
assert all(len(row) == M.CAM + 6 for row in s.cov)
def run(seed, measure=True, frames=90):
rng = random.Random(seed)
pts = dict(KNOWN)
for i in range(10, 26):
pts[i] = [rng.uniform(2.0, 4.0), rng.uniform(-1.5, 3.0)]
s = M.MonoSLAM([0.0, 0.0, 0.0, 0.0, 0.3, 0.0], small_cov(1e-6, 0.01), KNOWN, target=8)
true = [0.0, 0.0, 0.0]
for f in range(frames): # the camera speeds up from 0.3 m/s to 0.7 m/s and turns
vy, w = 0.3 + 0.4 * f / frames, 0.15 * math.cos(f / 20.0)
true = [true[0], true[1] + vy * s.dt, true[2] + w * s.dt]
det = M.simulate_detections(true, pts, rng) if measure else {}
s.frame(det)
cam_err = math.hypot(s.mu[0] - true[0], s.mu[1] - true[1])
pt_err = [math.hypot(s.point(p)[0] - pts[p][0], s.point(p)[1] - pts[p][1]) for p in s.ids if p >= 10]
return s, true, cam_err, pt_err
def test_simulation_measurement():
# a measurement of this toy, not a theorem: the camera moves 1.5 m to the side and
# turns; the known points leave the view, and the new points keep the track
for seed in (0, 1, 2):
s, true, cam_err, pt_err = run(seed)
_, _, blind_err, _ = run(seed, measure=False)
assert cam_err < 0.05
assert abs(robest.wrap_angle(s.mu[2] - true[2])) < 0.01
assert blind_err > 0.5 # the prediction alone keeps the first speed
assert len(pt_err) >= 4 and max(pt_err) < 0.3
assert sorted(pt_err)[len(pt_err) // 2] < 0.1
assert M.project(true, KNOWN[0][1]) is None or not M.in_view(M.project(true, KNOWN[0][1]))
History
Davison showed real-time SLAM with a single camera in 2003, as an extended Kalman filter with a sparse map of image patches. The paper by Davison, Reid, Molton and Stasse in the IEEE Transactions on Pattern Analysis and Machine Intelligence in 2007 describes the full system: the constant velocity model, active search, the particle initialization of the depth and the map management, with applications to augmented reality and to a humanoid robot. Keyframe methods with bundle adjustment, starting with PTAM in 2007, later took over most of visual SLAM.
References
- Andrew J. Davison, Ian D. Reid, Nicholas D. Molton and Olivier Stasse, MonoSLAM: Real-time single camera SLAM, IEEE Transactions on Pattern Analysis and Machine Intelligence 29(6), 2007, pages 1052 to 1067, Section 3 (the state, the constant velocity model, active search, the particle initialization of new features and the map management), Section 4 (augmented reality) and Section 5 (the humanoid robot)
- Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 10 (EKF SLAM, the filter that MonoSLAM uses)
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag HXRXPQ Edit this page History Report an error Markdown