Algorithm Search⌘K

Algorithmcore

Occupancy grid mapping

Also called log-odds occupancy update, Moravec-Elfes mapping.

Builds an occupancy grid from known poses by adding the log odds of an inverse sensor model to each cell that a reading touches.

Time
O(T g b) worstO(g b) per_scan
Space
O(1) extraO(g) total
Where
T = the number of scans; b = the number of beams in one scan; g = the number of grid cells
Properties
deterministicnot exactincrementalonline
Origin
Hans Moravec, Alberto Elfes, 1985

Occupancy grid mapping builds a map of a robot's world from range readings taken at known poses. The map is an occupancy grid map: each cell mim_i holds the probability that something occupies it, stored as log odds lil_i. For each new scan, the algorithm asks an inverse sensor model how likely each cell is to be occupied given this scan alone, and adds the log odds of the answer to the cell, minus the log odds of the prior. Each cell is a separate binary Bayes filter with a static state. The method is exact under one strong approximation, that the cells are independent of each other, and it costs O(g)O(g) evaluations of the inverse model per scan for a grid of gg cells. The poses must be known; if they are not, the problem is SLAM, and a method such as grid-based Rao-Blackwellized particle filter SLAM runs this algorithm once per particle.

In plain words

Draw a grid of small squares over the floor. At first the robot does not know anything about any square, so each square says "maybe". The robot stands at a known place and sends out laser beams. A beam stops at a wall. Every square that the beam passes through is probably empty, so it moves a little towards "empty". The square where the beam stops is probably a wall, so it moves a little towards "full". Squares that no beam reaches do not change. The robot does this again and again from many places. A square that many beams pass through becomes very sure to be empty, and a square where many beams stop becomes very sure to be a wall. The robot does not multiply small numbers: it adds a score for "full" and subtracts a score for "empty", which is the same thing in a different unit.

The problem

The input is a sequence of poses x1:Tx_{1:T} of the robot, each a planar pose (x,y,θ)(x, y, \theta) in meters and radians, and a scan ztz_t taken at each pose. A scan is a set of beams: beam kk has the bearing θk\theta_k in the robot frame and the measured range ztkz_t^k, at most the maximum range zmax⁡z_{\max}. The map mm is a grid of cells m1,…,mgm_1, \ldots, m_g, and each cell is occupied (mi=1m_i = 1) or free (mi=0m_i = 0). The notation is the one of Thrun, Burgard and Fox (2005).

The goal is the posterior p(m∣z1:t,x1:t)p(m \mid z_{1:t}, x_{1:t}). It is a distribution over 2g2^g maps, which is far too large to store. The algorithm stores instead the gg marginals p(mi∣z1:t,x1:t)p(m_i \mid z_{1:t}, x_{1:t}) and uses them as if

p(m∣z1:t,x1:t)=∏i=1gp(mi∣z1:t,x1:t).p(m \mid z_{1:t}, x_{1:t}) = \prod_{i=1}^{g} p(m_i \mid z_{1:t}, x_{1:t}).

This independence of the cells is an approximation that makes the update tractable, not a property of real maps: two neighboring cells of one wall are clearly not independent. Each cell keeps its log odds

lt,i=log⁡p(mi∣z1:t,x1:t)1−p(mi∣z1:t,x1:t),l0=log⁡p(mi)1−p(mi),l_{t,i} = \log \frac{p(m_i \mid z_{1:t}, x_{1:t})}{1 - p(m_i \mid z_{1:t}, x_{1:t})}, \qquad l_0 = \log \frac{p(m_i)}{1 - p(m_i)},

where p(mi)p(m_i) is the prior probability of occupancy, often 0.50.5, so that l0=0l_0 = 0.

The algorithm

The first procedure is Thrun et al., Table 9.1. The second is the inverse range sensor model of Table 9.2, for a planar scanner with a beam width β\beta and an obstacle thickness α\alpha.

  1. OCCUPANCY-GRID-MAPPING(l, x_t, z_t) ▷ l_i = l_(t-1,i) for each cell m_i
  2. 1for each cell m_i do
  3. 2if m_i is in the perceptual field of z_t then
  4. 3l_i ← l_i + INVERSE-SENSOR-MODEL(m_i, x_t, z_t) - l_0
  5. 4else l_i stays the same
  6. 5return l
  7. INVERSE-SENSOR-MODEL(m_i, x_t, z_t) ▷ x_t = (x, y, theta)
  8. 6(x_i, y_i) ← the center of cell m_i
  9. 7r ← sqrt((x_i - x)^2 + (y_i - y)^2); phi ← atan2(y_i - y, x_i - x) - theta
  10. 8k ← the beam j with the smallest |phi - theta_j|, angles wrapped to [-pi, pi)
  11. 9if r > min(z_max, z_t^k + alpha/2) or |phi - theta_k| > beta/2 then return l_0
  12. 10if z_t^k < z_max and |r - z_t^k| < alpha/2 then return l_occ
  13. 11if r ≤ z_t^k then return l_free
  14. 12return l_0

Line L7 gives the range and the bearing of the cell center as seen from the robot. Line L8 picks the beam that points closest to the cell. Line L9 returns the prior for a cell that is behind the reading or outside the beam: the scan says nothing about it. Line L10 marks a cell near the end point of the beam as occupied, except when the reading is a max range reading, which means that the beam hit nothing. Line L11 marks a cell in front of the end point as free. Line L12 is only reached on the boundary r=ztk+α/2r = z_t^k + \alpha/2 when ∣r−ztk∣<α/2|r - z_t^k| < \alpha/2 fails; Table 9.2 has no line for this case, and the prior is the natural value.

The values are locc=log⁡(0.7/0.3)=0.84730l_{\mathrm{occ}} = \log(0.7/0.3) = 0.84730 and lfree=log⁡(0.4/0.6)=−0.40547l_{\mathrm{free}} = \log(0.4/0.6) = -0.40547 in the implementation below. These probabilities are rules of thumb, not values derived from the sensor; Thrun et al. (Section 9.3) show how to learn an inverse model from data instead.

The perceptual field test of line L2 needs no separate geometry: a cell outside the field gets l0l_0 from the inverse model, and line L3 would add zero. The implementation therefore calls the model for each cell within zmax⁡+αz_{\max} + \alpha of the robot and skips the cells farther away, which the model would map to l0l_0 anyway.

Example

The robot is at (0,0)(0, 0) with heading θ=0\theta = 0. Its scan has one beam at bearing 00 with range z=1.0z = 1.0 m, and zmax⁡=3z_{\max} = 3 m, α=0.2\alpha = 0.2 m, β=0.1\beta = 0.1 rad. The prior is p(mi)=0.5p(m_i) = 0.5, so l0=0l_0 = 0.

cell center (m) rr (m) rule value
(0.5,0)(0.5, 0) 0.5 L11, in front of the end point lfree=−0.40547l_{\mathrm{free}} = -0.40547
(0.95,0)(0.95, 0) 0.95 L10, ∣r−z∣=0.05<0.1\lvert r - z \rvert = 0.05 < 0.1 locc=0.84730l_{\mathrm{occ}} = 0.84730
(1.05,0)(1.05, 0) 1.05 L10 locc=0.84730l_{\mathrm{occ}} = 0.84730
(1.2,0)(1.2, 0) 1.2 L9, r>z+α/2=1.1r > z + \alpha/2 = 1.1 l0=0l_0 = 0
(0.5,0.5)(0.5, 0.5) 0.707 L9, bearing π/4>β/2\pi/4 > \beta/2 l0=0l_0 = 0

If the robot takes the same scan three times, a cell at (0.5,0)(0.5, 0) ends at l=3⋅(−0.40547)=−1.21640l = 3 \cdot (-0.40547) = -1.21640, which is the probability (0.4/0.6)3/(1+(0.4/0.6)3)=8/35=0.2286(0.4/0.6)^3 / (1 + (0.4/0.6)^3) = 8/35 = 0.2286. A cell at (1.0,0)(1.0, 0) ends at l=2.54189l = 2.54189, which is 0.343/0.370=0.92700.343 / 0.370 = 0.9270. A cell that is seen as free once and as occupied once ends at l=0.44183l = 0.44183, which is 0.60870.6087: one hit outweighs one miss, because 0.84730>0.405470.84730 > 0.40547.

The term −l0-l_0 matters when the prior is not 0.50.5. With p(mi)=0.3p(m_i) = 0.3, the prior is l0=−0.84730l_0 = -0.84730. Two hits must give l=l0+2(0.84730−l0)=2.54189l = l_0 + 2 (0.84730 - l_0) = 2.54189, which is 0.92700.9270, the same value as above. A program that forgets −l0-l_0 gets l0+2⋅0.84730=0.84730l_0 + 2 \cdot 0.84730 = 0.84730, which is 0.70.7, and so it counts the prior twice too often.

The tests also map a room of 4 m by 3 m with walls through the cell centers, from three poses and 120 beams per scan, on a grid of 51 by 41 cells of 0.1 m. All wall cells away from the corners end with l>0l > 0, all interior cells with l<0l < 0, and every cell 0.2 m or more behind a wall keeps exactly l0l_0.

Correctness

Fix one cell mim_i. Assume that, given mim_i and the poses, the scan ztz_t is independent of the earlier scans, and that the inverse model returns the log odds of p(mi∣zt,xt)p(m_i \mid z_t, x_t). Then Bayes' rule, written in odds, gives

lt,i=lt−1,i+log⁡p(mi∣zt,xt)1−p(mi∣zt,xt)−l0,l_{t,i} = l_{t-1,i} + \log \frac{p(m_i \mid z_t, x_t)}{1 - p(m_i \mid z_t, x_t)} - l_0,

because the evidence p(zt∣z1:t−1,x1:t)p(z_t \mid z_{1:t-1}, x_{1:t}) cancels in the ratio of the two posteriors for mi=1m_i = 1 and mi=0m_i = 0, and p(zt∣mi,xt)p(z_t \mid m_i, x_t) is turned into p(mi∣zt,xt)p(m_i \mid z_t, x_t) by Bayes' rule once more, which brings in the prior. Line L3 is this equation. By induction, lT,i=l0+∑t(ismt(mi)−l0)l_{T,i} = l_0 + \sum_t (\mathrm{ism}_t(m_i) - l_0), and the order of the scans does not matter. The assumption is the approximation of independent cells in another form: the readings depend on the other cells too, so the result is the posterior of the cell only under that assumption. The full argument is in the correctness proof.

Proof: The log odds update gives the posterior of each cell under the independence assumptionfull

Setting. Fix one cell mim_i of the grid. It is occupied (mi=1m_i = 1) or free (mi=0m_i = 0), and its prior is p(mi=1)=p0p(m_i = 1) = p_0 with 0<p0<10 < p_0 < 1. The poses x1,…,xTx_1, \ldots, x_T are known and fixed in advance, and ztz_t is the scan taken at xtx_t. Write odds⁡(p)=p/(1−p)\operatorname{odds}(p) = p / (1 - p) and lo⁡(p)=log⁡odds⁡(p)\operatorname{lo}(p) = \log \operatorname{odds}(p), so that l0=lo⁡(p0)l_0 = \operatorname{lo}(p_0). Write $\mathrm{ism}_t = $ INVERSE-SENSOR-MODEL(mi,xt,zt)(m_i, x_t, z_t).

Assumptions.

  • (I) Given the state of the cell and the poses, a scan is independent of the earlier scans: p(zt∣mi,z1:t−1,x1:t)=p(zt∣mi,xt)p(z_t \mid m_i, z_{1:t-1}, x_{1:t}) = p(z_t \mid m_i, x_t).
  • (S) The inverse model gives the log odds of the posterior of the cell from one scan: ismt=lo⁡(p(mi=1∣zt,xt))\mathrm{ism}_t = \operatorname{lo}(p(m_i = 1 \mid z_t, x_t)), and this probability is in (0,1)(0, 1).
  • (K) A pose alone carries no information about the map: p(mi∣xt)=p(mi)p(m_i \mid x_t) = p(m_i) and p(mi∣z1:t−1,x1:t)=p(mi∣z1:t−1,x1:t−1)p(m_i \mid z_{1:t-1}, x_{1:t}) = p(m_i \mid z_{1:t-1}, x_{1:t-1}). This holds because the poses are fixed in advance and do not depend on the map.

Claim. Let l0,i=l0l_{0,i} = l_0, and let lt,il_{t,i} be the value of the cell after OCCUPANCY-GRID-MAPPING has processed z1,…,ztz_1, \ldots, z_t. Then for every t≥0t \ge 0,

lt,i=lo⁡(p(mi=1∣z1:t,x1:t))=l0+∑s=1t(isms−l0).l_{t,i} = \operatorname{lo}\big(p(m_i = 1 \mid z_{1:t}, x_{1:t})\big) = l_0 + \sum_{s=1}^{t} (\mathrm{ism}_s - l_0).

Proof. First, the algorithm computes the sum on the right. Line L3 adds ismt−l0\mathrm{ism}_t - l_0 to lil_i. Line L4 leaves lil_i unchanged, and line L2 sends a cell to line L4 only when it is outside the perceptual field, where the inverse model returns l0l_0 (line L9), so that the term ismt−l0\mathrm{ism}_t - l_0 is zero. So in both branches the value grows by ismt−l0\mathrm{ism}_t - l_0, and induction on tt gives the sum.

Next, the sum is the posterior log odds. By induction on tt. For t=0t = 0 both sides are l0l_0. Let t≥1t \ge 1. For v∈{0,1}v \in \{0, 1\}, Bayes' rule gives

p(mi=v∣z1:t,x1:t)=p(zt∣mi=v,z1:t−1,x1:t) p(mi=v∣z1:t−1,x1:t)p(zt∣z1:t−1,x1:t).p(m_i = v \mid z_{1:t}, x_{1:t}) = \frac{p(z_t \mid m_i = v, z_{1:t-1}, x_{1:t})\, p(m_i = v \mid z_{1:t-1}, x_{1:t})}{p(z_t \mid z_{1:t-1}, x_{1:t})}.

By (I) the first factor is p(zt∣mi=v,xt)p(z_t \mid m_i = v, x_t), and by (K) the second is p(mi=v∣z1:t−1,x1:t−1)p(m_i = v \mid z_{1:t-1}, x_{1:t-1}). The denominator does not depend on vv. Divide the equation for v=1v = 1 by the equation for v=0v = 0:

odds⁡t=p(zt∣mi=1,xt)p(zt∣mi=0,xt) odds⁡t−1,\operatorname{odds}_t = \frac{p(z_t \mid m_i = 1, x_t)}{p(z_t \mid m_i = 0, x_t)}\, \operatorname{odds}_{t-1},

where odds⁡t\operatorname{odds}_t is the odds of mi=1m_i = 1 given z1:t,x1:tz_{1:t}, x_{1:t}. Bayes' rule once more, with (K), gives p(zt∣mi=v,xt)=p(mi=v∣zt,xt) p(zt∣xt)/p(mi=v)p(z_t \mid m_i = v, x_t) = p(m_i = v \mid z_t, x_t)\, p(z_t \mid x_t) / p(m_i = v). In the ratio, p(zt∣xt)p(z_t \mid x_t) cancels, and

p(zt∣mi=1,xt)p(zt∣mi=0,xt)=odds⁡(p(mi=1∣zt,xt))odds⁡(p0).\frac{p(z_t \mid m_i = 1, x_t)}{p(z_t \mid m_i = 0, x_t)} = \frac{\operatorname{odds}(p(m_i = 1 \mid z_t, x_t))}{\operatorname{odds}(p_0)}.

Take logarithms and use (S): log⁡odds⁡t=log⁡odds⁡t−1+ismt−l0\log \operatorname{odds}_t = \log \operatorname{odds}_{t-1} + \mathrm{ism}_t - l_0. With the induction hypothesis, log⁡odds⁡t=l0+∑s=1t(isms−l0)\log \operatorname{odds}_t = l_0 + \sum_{s=1}^{t} (\mathrm{ism}_s - l_0). All odds are positive and finite, because (S) puts every probability in (0,1)(0, 1), so each step is defined. □\square

The cells that the implementation skips. The implementation calls the inverse model only for the cells that Grid.cells_within returns for the radius zmax⁡+αz_{\max} + \alpha. Let a=(x−zmax⁡−α−ox)/sa = (x - z_{\max} - \alpha - o_x)/s, where oxo_x is the grid origin and ss the cell side. A cell whose center ox+(i+1/2)so_x + (i + 1/2) s is at least x−zmax⁡−αx - z_{\max} - \alpha has i≥⌈a−1/2⌉≥⌊a⌋i \ge \lceil a - 1/2 \rceil \ge \lfloor a \rfloor, and the same holds at the upper end and for yy. So every cell whose center lies in the square of half side zmax⁡+αz_{\max} + \alpha around the robot is visited. A cell that is not visited has its center outside this square, so its distance rr to the robot is more than zmax⁡z_{\max}, and line L9 returns l0l_0. Skipping it is the same as line L4.

Order of the scans. The sum does not depend on the order of its terms, so any order of the scans gives the same map. In floating-point arithmetic the results of two orders differ only by rounding.

Termination. One scan does one call of the inverse model for each of the at most gg cells, and each call ends after a search over bb beams. So a scan ends after O(gb)O(g b) steps.

What the assumptions mean. The claim is about one cell at a time. Assumption (I) is false for real scans: a reading depends on all cells along the beam, not only on mim_i, so the readings are dependent given mim_i alone. The product of the per-cell results is therefore not the joint posterior over maps; it is the approximation of independent cells. Assumption (S) holds only for an inverse model that is learned from the forward model. The fixed values 0.70.7 and 0.40.4 of the implementation are rules of thumb, so the output is the result of a consistent update rule, with the exact sum above, and not a calibrated probability.

Complexity

Let gg be the number of cells, bb the number of beams in a scan and TT the number of scans. The bounds are in the word RAM model, with one step for each arithmetic operation on a log odds value, which is a floating-point number in one word.

  • One call of the inverse model costs O(b)O(b) for the search of line L8, and O(1)O(1) for the rest. If the beams are evenly spaced, the index kk is a rounding of (ϕ−θ1)/Δθ(\phi - \theta_1) / \Delta\theta, and the call costs O(1)O(1).
  • One scan costs O(gb)O(g b) in the worst case, and O(g)O(g) with evenly spaced beams. Only cells within zmax⁡+αz_{\max} + \alpha of the robot can change, so with a cell side ss the number of cells visited is at most about π(zmax⁡+α)2/s2\pi (z_{\max} + \alpha)^2 / s^2, whatever the size of the grid.
  • TT scans cost O(Tgb)O(T g b) time. The memory is the grid, O(g)O(g), and the update needs O(1)O(1) extra memory, since it changes the grid in place.

The variant that traces each beam through the grid instead of testing each cell costs O(b zmax⁡/s)O(b\, z_{\max} / s) per scan: each beam crosses at most about zmax⁡/sz_{\max} / s cells.

Properties

  • Additive and commutative. The map after TT scans is l0l_0 plus a sum of terms, one per scan. Scans can be added in any order, and a scan can be removed by subtracting its term.
  • Incremental and online. Each scan updates the grid in place, and old scans are not stored.
  • No normalization and no products. Log odds turn the product of likelihood ratios into a sum, so the update cannot underflow and needs no division. Probabilities come back by p=1−1/(1+el)p = 1 - 1 / (1 + e^{l}) when they are needed.
  • Unbounded certainty. Without clamping, lil_i grows linearly with the number of consistent readings, so a cell seen 100 times as free has l=−40.5l = -40.5 and needs 48 hits to get back above l0l_0 with the values above.
  • Not exact for the joint map. The output is the product of the per-cell posteriors under the independence approximation. It is not the marginal of the true joint posterior over maps.

Variants and improvements

  • Ray casting of each beam. Trace each beam from the robot to its end point with the Bresenham line algorithm or the Amanatides-Woo traversal, update the cells it crosses as free and the end cell as occupied. This visits only the cells that change and is the usual form for laser scanners.
  • Clamping. Keep each lil_i between two bounds, so that the map can adapt when the world changes. The octree occupancy map (OctoMap) uses clamping thresholds and then merges identical children of the tree.
  • Learned inverse models. Thrun et al. (Section 9.3) learn the inverse model by sampling maps and readings from the forward model, instead of using fixed values such as 0.7 and 0.4.
  • Forward models and MAP maps. Thrun et al. (Section 9.4) search for the most likely map under the forward beam range finder model, which keeps the dependencies between cells that the inverse model ignores. It is a batch method, and it needs a search over maps.
  • Several sensors. With sonar and laser on one robot, Thrun et al. (Section 9.2) keep one grid per sensor and combine the grids per cell, for example by the maximum, because the sensors see different obstacles.
  • Unknown poses. When the poses are estimated, the algorithm runs inside SLAM: once per particle in grid-based Rao-Blackwellized particle filter SLAM, or once after a pose graph optimization with the corrected poses.

When to use it

Use it when the poses are known or estimated well, and the robot needs a dense map of free and occupied space for planning, exploration or localization. It is simple, each scan touches only the cells near the robot, and it fuses noisy readings over time. For 3D maps, a dense grid of cells uses too much memory; use an octree occupancy map. For maps of point landmarks, use a feature map and the landmark measurement model instead.

Pitfalls

  • Forgetting the prior term. The update is l+ism−l0l + \mathrm{ism} - l_0. With a prior of 0.50.5 the term is zero and the mistake is invisible, but with any other prior it counts the prior once for every scan.
  • Wrong angle differences. The difference ϕ−θk\phi - \theta_k must be wrapped to [−π,π)[-\pi, \pi). Without wrapping, a cell behind the robot at a bearing of π−0.01\pi - 0.01 and a beam at −π+0.01-\pi + 0.01 look 2π2\pi apart, and the cell is never updated.
  • Max range readings. A reading at zmax⁡z_{\max} usually means that the beam hit nothing. Marking its end as occupied puts a ring of false obstacles at the maximum range. Many implementations also skip the free update for such beams, because the reading may come from a glass surface or a failed return.
  • Too much confidence. Neighboring beams and repeated scans from the same pose are not independent, so the sum counts the same evidence many times. The resulting probabilities are too close to 0 and 1. Clamping limits the effect; it does not remove it.
  • Beam width and cell size. If β\beta is less than the angle between two beams, cells between the beams far from the robot are never updated, and the map has radial gaps. If α\alpha is less than the cell side, some walls fall between cell centers and get no hit.
  • Moving objects and wrong poses. People who walk by leave traces, and a pose error of a few degrees smears the walls. The algorithm assumes a static world and known poses, and it cannot correct either.

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.

occupancy_grid_mapping.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/occupancy-grid-mapping/. The authors are listed in prov/NBXJ4P.jsonl.

"""Occupancy grid mapping with known poses (Thrun, Burgard and Fox 2005, Tables 9.1 and 9.2).

The grid has W by H square cells of side res. Cell (i, j) has its center at
(ox + (i + 0.5) res, oy + (j + 0.5) res); the map is a list of W columns of
H log odds values, l[i][j]. A pose is (x, y, theta) in meters and radians.
A scan is a list of beams (z, bearing): the range z in meters, at most
z_max, and the bearing of the beam in the robot frame in radians.
"""

import math

import robest


class Grid:
    """The geometry of a grid: origin (ox, oy), cell side res, W by H cells."""

    def __init__(self, ox, oy, res, width, height):
        self.ox, self.oy, self.res = float(ox), float(oy), float(res)
        self.width, self.height = int(width), int(height)

    def center(self, i, j):
        return (self.ox + (i + 0.5) * self.res, self.oy + (j + 0.5) * self.res)

    def cells_within(self, x, y, radius):
        """Yield the cells whose center can be within radius of (x, y)."""
        i0 = max(0, int(math.floor((x - radius - self.ox) / self.res)))
        i1 = min(self.width - 1, int(math.floor((x + radius - self.ox) / self.res)))
        j0 = max(0, int(math.floor((y - radius - self.oy) / self.res)))
        j1 = min(self.height - 1, int(math.floor((y + radius - self.oy) / self.res)))
        for i in range(i0, i1 + 1):
            for j in range(j0, j1 + 1):
                yield i, j


class InverseRangeSensorModel:
    """The inverse range sensor model of Table 9.2, with its parameters.

    alpha is the thickness of obstacles and beta the width of a beam.
    The log odds l_occ and l_free are rules of thumb, not derived values.
    """

    def __init__(self, z_max, alpha, beta, p_occ=0.7, p_free=0.4, p_prior=0.5):
        self.z_max, self.alpha, self.beta = z_max, alpha, beta
        self.l_occ = robest.logodds(p_occ)
        self.l_free = robest.logodds(p_free)
        self.l0 = robest.logodds(p_prior)

    def __call__(self, center, pose, scan):
        xi, yi = center
        x, y, theta = pose
        r = math.hypot(xi - x, yi - y)  # @line L7
        phi = math.atan2(yi - y, xi - x) - theta
        k = min(range(len(scan)), key=lambda j: abs(robest.wrap_angle(phi - scan[j][1])))  # @line L8
        zk, bk = scan[k]
        dphi = abs(robest.wrap_angle(phi - bk))
        if r > min(self.z_max, zk + self.alpha / 2) or dphi > self.beta / 2:  # @line L9
            return self.l0
        if zk < self.z_max and abs(r - zk) < self.alpha / 2:  # @line L10
            return self.l_occ
        if r <= zk:  # @line L11
            return self.l_free
        return self.l0  # @line L12


def occupancy_grid_mapping(l, grid, pose, scan, ism):
    """Return the log odds map after one scan taken at a known pose.

    l is updated in place and returned. Only the cells within reach of the
    sensor are visited; for the others the inverse model returns l0, so the
    update would leave them unchanged.
    """
    reach = ism.z_max + ism.alpha
    for i, j in grid.cells_within(pose[0], pose[1], reach):  # @line L1
        center = grid.center(i, j)  # @line L6
        v = ism(center, pose, scan)
        if v != ism.l0:  # @line L2
            l[i][j] += v - ism.l0  # @line L3
        # else the cell is outside the perceptual field and keeps its value  # @line L4
    return l  # @line L5


def new_map(grid, ism):
    """Return a map with every cell at the prior log odds l0."""
    return [[ism.l0] * grid.height for _ in range(grid.width)]


def probabilities(l):
    """Return the map of occupancy probabilities of a log odds map."""
    return [[robest.prob_from_logodds(v) for v in col] for col in l]
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_occupancy_grid_mapping.py 188 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/occupancy-grid-mapping/. The authors are listed in prov/NBXJ4P.jsonl.

import math
import random

import pytest

import robest
from occupancy_grid_mapping import (
    Grid,
    InverseRangeSensorModel,
    new_map,
    occupancy_grid_mapping,
    probabilities,
)

# A rectangular room with walls on x = 0, x = 4, y = 0 and y = 3. The grid
# puts cell centers at -0.5, -0.4, ..., so the walls run through the centers
# of the columns i = 5 and i = 45 and of the rows j = 5 and j = 35.
GRID = Grid(-0.55, -0.55, 0.1, 51, 41)
ROOM = (0.0, 4.0, 0.0, 3.0)
POSES = [(1.0, 1.0, 0.3), (2.0, 1.5, 0.0), (3.0, 2.0, 1.0)]
N_BEAMS = 120
BEARINGS = [-math.pi + 2.0 * math.pi * k / N_BEAMS for k in range(N_BEAMS)]


def room_range(pose, bearing, z_max):
    """Return the exact range to the room walls, capped at z_max."""
    x, y, theta = pose
    c, s = math.cos(theta + bearing), math.sin(theta + bearing)
    x0, x1, y0, y1 = ROOM
    ts = []
    if c > 0:
        ts.append((x1 - x) / c)
    elif c < 0:
        ts.append((x0 - x) / c)
    if s > 0:
        ts.append((y1 - y) / s)
    elif s < 0:
        ts.append((y0 - y) / s)
    return min(min(ts), z_max)


def room_scan(pose, z_max):
    return [(room_range(pose, b, z_max), b) for b in BEARINGS]


def room_ism():
    # The beam width is a little more than the beam spacing, so every
    # direction is within beta / 2 of a beam.
    return InverseRangeSensorModel(z_max=6.0, alpha=0.2, beta=1.2 * 2.0 * math.pi / N_BEAMS)


@pytest.fixture(scope="module")
def room_map():
    ism = room_ism()
    l = new_map(GRID, ism)
    for pose in POSES:
        occupancy_grid_mapping(l, GRID, pose, room_scan(pose, ism.z_max), ism)
    return l


def test_logodds_check_values():
    ism = InverseRangeSensorModel(z_max=5.0, alpha=0.2, beta=0.05)
    assert ism.l_occ == pytest.approx(0.84730, abs=1e-5)
    assert ism.l_free == pytest.approx(-0.40547, abs=1e-5)
    assert ism.l0 == 0.0


def test_inverse_model_hand_cases():
    ism = InverseRangeSensorModel(z_max=3.0, alpha=0.2, beta=0.1)
    pose = (0.0, 0.0, 0.0)
    scan = [(1.0, 0.0), (2.0, math.pi / 2)]
    assert ism((0.5, 0.0), pose, scan) == ism.l_free
    assert ism((1.0, 0.0), pose, scan) == ism.l_occ
    assert ism((1.05, 0.0), pose, scan) == ism.l_occ
    assert ism((0.95, 0.0), pose, scan) == ism.l_occ
    assert ism((1.2, 0.0), pose, scan) == ism.l0
    assert ism((0.5, 0.5), pose, scan) == ism.l0  # between the beams
    assert ism((0.0, 1.5), pose, scan) == ism.l_free
    assert ism((0.0, 2.0), pose, scan) == ism.l_occ
    assert ism((0.0, -1.0), pose, scan) == ism.l0  # no beam points there


def test_inverse_model_max_range_reading_marks_no_obstacle():
    ism = InverseRangeSensorModel(z_max=3.0, alpha=0.2, beta=0.1)
    pose = (0.0, 0.0, 0.0)
    scan = [(3.0, 0.0)]
    assert ism((2.95, 0.0), pose, scan) == ism.l_free
    assert ism((3.0, 0.0), pose, scan) == ism.l_free
    assert ism((3.05, 0.0), pose, scan) == ism.l0


def test_inverse_model_uses_the_robot_heading():
    ism = InverseRangeSensorModel(z_max=3.0, alpha=0.2, beta=0.1)
    scan = [(1.0, 0.0)]
    pose = (1.0, 1.0, math.pi / 2)
    assert ism((1.0, 2.0), pose, scan) == ism.l_occ
    assert ism((2.0, 1.0), pose, scan) == ism.l0
    # The bearing difference wraps around at pi.
    scan = [(1.0, math.pi - 0.01)]
    pose = (0.0, 0.0, 0.0)
    assert ism((-1.0, -0.01), pose, scan) == ism.l_occ


def test_update_equals_binary_bayes_filter_in_probability_form():
    # A prior other than 0.5 makes the "- l0" term matter.
    ism = InverseRangeSensorModel(z_max=3.0, alpha=0.2, beta=0.1, p_prior=0.3)
    grid = Grid(-1.0, -1.0, 0.25, 8, 8)
    rng = random.Random(7)
    l = new_map(grid, ism)
    p0 = 0.3
    bel = [[p0] * grid.height for _ in range(grid.width)]
    for _ in range(12):
        pose = (rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5), rng.uniform(-math.pi, math.pi))
        scan = [(rng.uniform(0.2, 3.0), -math.pi + 2 * math.pi * k / 72) for k in range(72)]
        for i in range(grid.width):
            for j in range(grid.height):
                p = robest.prob_from_logodds(ism(grid.center(i, j), pose, scan))
                a = p * bel[i][j] / p0
                b = (1 - p) * (1 - bel[i][j]) / (1 - p0)
                bel[i][j] = a / (a + b)
        occupancy_grid_mapping(l, grid, pose, scan, ism)
    got = probabilities(l)
    for i in range(grid.width):
        for j in range(grid.height):
            assert got[i][j] == pytest.approx(bel[i][j], abs=1e-12)


def test_reach_restriction_equals_the_full_loop():
    ism = InverseRangeSensorModel(z_max=1.0, alpha=0.2, beta=0.08)
    grid = Grid(0.0, 0.0, 0.1, 30, 20)
    pose = (1.0, 1.0, 0.4)
    rng = random.Random(3)
    scan = [(rng.uniform(0.3, 1.0), -math.pi + 2 * math.pi * k / 90) for k in range(90)]
    fast = occupancy_grid_mapping(new_map(grid, ism), grid, pose, scan, ism)
    full = new_map(grid, ism)
    for i in range(grid.width):
        for j in range(grid.height):
            full[i][j] += ism(grid.center(i, j), pose, scan) - ism.l0
    assert fast == full
    assert any(v != ism.l0 for col in fast for v in col)


def test_order_of_scans_does_not_matter():
    ism = room_ism()
    grid = Grid(-0.55, -0.55, 0.2, 26, 21)
    scans = [(pose, room_scan(pose, ism.z_max)) for pose in POSES]
    a = new_map(grid, ism)
    for pose, scan in scans:
        occupancy_grid_mapping(a, grid, pose, scan, ism)
    b = new_map(grid, ism)
    for pose, scan in reversed(scans):
        occupancy_grid_mapping(b, grid, pose, scan, ism)
    for ca, cb in zip(a, b):
        for va, vb in zip(ca, cb):
            assert va == pytest.approx(vb, abs=1e-12)


def test_room_walls_are_occupied(room_map):
    for i in range(8, 43):  # the walls y = 0 and y = 3, away from the corners
        assert room_map[i][5] > 0.0
        assert room_map[i][35] > 0.0
    for j in range(8, 33):  # the walls x = 0 and x = 4
        assert room_map[5][j] > 0.0
        assert room_map[45][j] > 0.0


def test_room_interior_is_free(room_map):
    for i in range(8, 43):
        for j in range(8, 33):
            assert room_map[i][j] < 0.0


def test_cells_behind_the_walls_keep_the_prior(room_map):
    for i in range(GRID.width):
        for j in range(GRID.height):
            if i <= 3 or i >= 47 or j <= 3 or j >= 37:
                assert room_map[i][j] == 0.0


def test_probabilities_of_the_room_map(room_map):
    p = probabilities(room_map)
    assert p[0][0] == 0.5
    assert p[25][5] > 0.9
    # Three scans saw the cell (2.0, 1.5) as free: odds (0.4 / 0.6)^3 = 8 / 27.
    assert p[25][20] == pytest.approx(8 / 35, abs=1e-12)

History

Moravec and Elfes (1985) built maps from many readings of wide angle sonar sensors on a mobile robot. Each reading told something about a cone of space: probably empty inside, probably occupied near the arc at the measured range. They kept these probabilities in a grid of cells. Elfes (1989) presented the occupancy grid as a random field of cell states, estimated by Bayes' rule, and used it for navigation. The log odds form with an inverse sensor model, and its derivation as a binary Bayes filter for each cell, are the ones of Thrun, Burgard and Fox (2005), Chapter 9, which also describes the limits of the independence assumption.

References

  1. Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 9, Section 9.2 (the algorithm of Table 9.1, the inverse range sensor model of Table 9.2 and the factorization over cells), Section 9.4 (maps with forward models), and Chapter 4, Section 4.2 (the binary Bayes filter with static state)
  2. Hans P. Moravec and Alberto Elfes, High resolution maps from wide angle sonar, Proceedings of the 1985 IEEE International Conference on Robotics and Automation, volume 2, pages 116 to 121, the grid of cells with probabilities of empty and occupied space, built from many sonar cones
  3. Alberto Elfes, Using occupancy grids for mobile robot perception and navigation, Computer 22(6), 1989, pages 46 to 57, the occupancy grid as a random field of cell states, updated by Bayes' rule from sensor readings

Where this leads

About this page

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per_scan
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of space.total
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
  • a scene preset for the example