Algorithm Search⌘K

Data structureintro

Occupancy grid map

Also called occupancy grid, evidence grid.

A grid of cells, each holding the probability that the cell is occupied, assumed independent of the others.

Time
O(1 + L / s) cells_on_segment · insert_rayO(1) index · probability · update
Space
O(g) total
Where
L = the length of a ray in meters; g = the number of cells; s = the side of a cell in meters
Origin
Hans Moravec, Alberto Elfes, 1985

An occupancy grid map divides a bounded part of the plane into square cells of one size, and stores for each cell the probability that an obstacle occupies it. The robotics literature stores the log odds l=log⁡(p/(1−p))l = \log(p / (1 - p)) instead of pp, because the Bayes update of one cell is then a sum. The cells are treated as independent random variables: the map is the product of gg separate binary distributions, which is an approximation that makes the update and the storage linear in gg. This page describes the grid itself, its fields and its operations: cell lookup, the log odds update with optional clamping, and the traversal of the cells that a sensor beam crosses. The algorithm that fills the grid from scans is occupancy grid mapping, and the model that turns one reading into cell values is the inverse sensor model. In computer-aided design the same grid of cells, with a yes or no value per cell, is called spatial occupancy enumeration.

In plain words

Lay a sheet of squared paper over the floor plan of a building. In each square, write a number that says how sure you are that something stands there: a wall, a box, a table leg. At the start every square says "I do not know". A robot with a laser walks around. When a beam passes through a square, the square becomes a little more sure that it is empty. When a beam stops in a square, that square becomes a little more sure that it holds something. Each square keeps its own number and does not look at its neighbors. To find the square under a point, you divide the position by the size of a square. To find the squares a beam passes through, you walk from square to square along the beam, always to the next square that the beam enters.

The abstract type

The grid is a map from the cells of a bounded rectangle to probabilities, with these operations:

  • index(x, y): the cell that holds the point (x,y)(x, y), or none outside the grid.
  • update(i, j, l_meas): combine the evidence lmeasl_{\mathrm{meas}} of one reading with the value of cell (i,j)(i, j) by the binary Bayes rule in log odds.
  • probability(i, j): the occupancy probability of the cell.
  • cells_on_segment(a, b): the cells that the segment from aa to bb crosses, in order.
  • insert_ray(a, b, hit): update the cells of one beam from the sensor at aa to the end point bb.

It is a uniform grid over the plane with one number per cell, stored in an array.

Representation

  • The origin (ox,oy)(o_x, o_y) in meters, the cell side ss in meters, and the size W×HW \times H in cells, so g=WHg = W H.
  • Cell (i,j)(i, j) is the half-open square [ox+is,ox+(i+1)s)×[oy+js,oy+(j+1)s)[o_x + i s, o_x + (i + 1) s) \times [o_y + j s, o_y + (j + 1) s). Its center is (ox+(i+12)s,oy+(j+12)s)(o_x + (i + \tfrac12) s, o_y + (j + \tfrac12) s).
  • One flat array ll of gg log odds values, in row-major order: cell (i,j)(i, j) is at index jW+ij W + i.
  • The prior log odds l0=log⁡(p0/(1−p0))l_0 = \log(p_0 / (1 - p_0)), where p0p_0 is the prior occupancy probability of every cell, often 0.50.5, so l0=0l_0 = 0.
  • Optional clamping bounds lmin⁡≤l0≤lmax⁡l_{\min} \le l_0 \le l_{\max}.

Invariant (G). (1) The array has exactly WHW H entries. (2) Each entry is in [lmin⁡,lmax⁡][l_{\min}, l_{\max}]. (3) The entry of cell (i,j)(i, j) is the result of applying, in order, the clamped updates of that cell to l0l_0; without clamping, it is l0+∑k(lk−l0)l_0 + \sum_k (l_k - l_0) over the updates lkl_k of that cell.

Part 3 says that the cells do not interact: an update of one cell never changes another one. A cell whose value is still exactly l0l_0 has never received evidence, or has received evidence that cancels out. Programs that need to tell "unknown" from "seen" keep a separate flag or count per cell.

Operations

  1. INDEX(G, x, y) ▷ the cell that holds (x, y), or none
  2. 1i ← floor((x - o_x) / s); j ← floor((y - o_y) / s)
  3. 2if 0 ≤ i < W and 0 ≤ j < H then return (i, j) else return none
  4. UPDATE(G, i, j, l_meas) ▷ binary Bayes rule in log odds
  5. 3k ← j W + i
  6. 4G.l[k] ← min(l_max, max(l_min, G.l[k] + l_meas - l_0))
  7. PROBABILITY(G, i, j)
  8. 5return 1 - 1 / (1 + exp(G.l[j W + i]))

Line L4 is the log odds form of the binary Bayes filter with a static state: the evidence lmeasl_{\mathrm{meas}} is the log odds of p(mi∣zt,xt)p(m_i \mid z_t, x_t) from the inverse sensor model, and the prior is subtracted once per update so that it is counted only once in total. Line L5 is the logistic function; the implementation computes it in a form that cannot overflow.

  1. CELLS-ON-SEGMENT(G, a, b) ▷ Amanatides-Woo traversal on the infinite lattice
  2. 1(i, j) ← the cell of a; (i_b, j_b) ← the cell of b; d ← b - a
  3. 2t_x ← the t in [0, 1] where a + t d meets the next vertical cell edge; Δt_x ← s / |d_x|; the same for y
  4. 3output (i, j)
  5. 4repeat |i_b - i| + |j_b - j| times:
  6. 5if j = j_b or (i ≠ i_b and t_x < t_y) then i ← i + sign(d_x); t_x ← t_x + Δt_x
  7. 6else j ← j + sign(d_y); t_y ← t_y + Δt_y
  8. 7output (i, j)
  9. INSERT-RAY(G, a, b, hit)
  10. 8for each cell c of CELLS-ON-SEGMENT(G, a, b) except the last, inside the grid: UPDATE(G, c, l_free)
  11. 9if the last cell is inside the grid: UPDATE(G, last, l_occ if hit else l_free)

The traversal keeps txt_x and tyt_y, the parameters of the next crossings of a vertical and a horizontal cell edge, and always crosses the nearer one. A coordinate with dx=0d_x = 0 has tx=∞t_x = \infty. The segment crosses exactly ∣ib−ia∣|i_b - i_a| vertical edges and ∣jb−ja∣|j_b - j_a| horizontal ones, so line L9 runs a fixed number of steps; the tests j=jbj = j_b and i≠ibi \ne i_b of line L10 make the last cell the cell of bb even when rounding makes txt_x and tyt_y slightly wrong. When the segment passes exactly through a corner of four cells, the traversal steps in yy first and outputs one cell that the segment touches only at the corner.

Line L14 uses lfreel_{\mathrm{free}} for a max range reading: the beam passed through the last cell and hit nothing. The implementation uses 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 by default. These are rules of thumb, not values derived from a sensor.

Example

A grid of 5×35 \times 3 cells of side s=1s = 1 m with its origin at (0,0)(0, 0) and the prior p0=0.5p_0 = 0.5. The sensor is at a=(0.5,0.5)a = (0.5, 0.5), the center of cell (0,0)(0, 0).

The segment to b=(3.7,2.4)b = (3.7, 2.4) has d=(3.2,1.9)d = (3.2, 1.9). It crosses x=1x = 1 at t=0.5/3.2=0.156t = 0.5/3.2 = 0.156, y=1y = 1 at t=0.5/1.9=0.263t = 0.5/1.9 = 0.263, x=2x = 2 at t=0.469t = 0.469, x=3x = 3 at t=0.781t = 0.781 and y=2y = 2 at t=0.789t = 0.789. So CELLS-ON-SEGMENT returns (0,0),(1,0),(1,1),(2,1),(3,1),(3,2)(0,0), (1,0), (1,1), (2,1), (3,1), (3,2): five steps, since ∣3−0∣+∣2−0∣=5|3 - 0| + |2 - 0| = 5.

Now insert three rays, all with a hit: first to (3.7,2.4)(3.7, 2.4), then to (4.5,0.5)(4.5, 0.5) along row 0, then to (3.7,2.4)(3.7, 2.4) again. The log odds, with the probability below each value, are then:

row i=0i = 0 i=1i = 1 i=2i = 2 i=3i = 3 i=4i = 4
j=2j = 2 0 0 0 1.69460 0
0.5 0.5 0.5 0.8448 0.5
j=1j = 1 0 -0.81093 -0.81093 -0.81093 0
0.5 0.3077 0.3077 0.3077 0.5
j=0j = 0 -1.21640 -1.21640 -0.40547 -0.40547 0.84730
0.2286 0.2286 0.4 0.4 0.7

Cell (3,2)(3, 2) got two hits, 2⋅0.84730=1.694602 \cdot 0.84730 = 1.69460, which is 0.49/(0.49+0.09)=0.84480.49/(0.49 + 0.09) = 0.8448. Cells (0,0)(0, 0) and (1,0)(1, 0) are on all three rays, so they have three misses, (0.4/0.6)3=8/27(0.4/0.6)^3 = 8/27 in odds, or 8/35=0.22868/35 = 0.2286. The cells with the value 0 are on no ray and keep the prior.

Clamping. With pmin⁡=0.12p_{\min} = 0.12 and pmax⁡=0.97p_{\max} = 0.97, the bounds are lmin⁡=−1.992l_{\min} = -1.992 and lmax⁡=3.476l_{\max} = 3.476. Five hits and then one miss give min⁡(3.476,4.236)−0.405=3.071\min(3.476, 4.236) - 0.405 = 3.071. One miss and then five hits give −0.405+4.236=3.831-0.405 + 4.236 = 3.831, clamped to 3.4763.476. With clamping, the order of the updates matters.

Correctness

Each operation keeps the invariant (G). INDEX returns the cell whose half-open square holds the point, because the floor of (x−ox)/s(x - o_x)/s is the only integer ii with ox+is≤x<ox+(i+1)so_x + i s \le x < o_x + (i + 1) s. UPDATE changes only the entry of its own cell, and the clamp of line L4 keeps it in the bounds, so parts 2 and 3 hold. Without clamping, line L4 is the log odds form of Bayes' rule for one binary cell, and the value after the updates is the posterior log odds of the cell under the assumption that the readings are independent given the cell; occupancy grid mapping proves this. CELLS-ON-SEGMENT returns, for a segment that passes through no corner of a cell, exactly the cells whose open square meets the segment, in the order of the segment, each once. The full proof is in the correctness proof.

Proof: The occupancy grid operations keep the invariant, and the traversal returns exactly the cells a segment crossesfull

We use the names of the pseudocode. The grid has the origin (ox,oy)(o_x, o_y), the cell side s>0s > 0 and W×HW \times H cells. Cell (i,j)(i, j) is the half-open square Qij=[ox+is,ox+(i+1)s)×[oy+js,oy+(j+1)s)Q_{ij} = [o_x + i s, o_x + (i + 1) s) \times [o_y + j s, o_y + (j + 1) s), and its open square is Qij∘=(ox+is,ox+(i+1)s)×(oy+js,oy+(j+1)s)Q^\circ_{ij} = (o_x + i s, o_x + (i + 1) s) \times (o_y + j s, o_y + (j + 1) s). These definitions make sense for all integers i,ji, j; the grid is the part with 0≤i<W0 \le i < W and 0≤j<H0 \le j < H. The invariant (G) asks: (1) the array ll has WHW H entries; (2) each entry is in [lmin⁡,lmax⁡][l_{\min}, l_{\max}]; (3) the entry of cell (i,j)(i, j) is the value obtained from l0l_0 by the updates of that cell, in order, each by line L4. We assume exact arithmetic; the remark at the end treats rounding.

Lemma 1 (index). For a real xx, the integer i=⌊(x−ox)/s⌋i = \lfloor (x - o_x)/s \rfloor is the only integer with ox+is≤x<ox+(i+1)so_x + i s \le x < o_x + (i + 1) s. Proof. The floor ii of u=(x−ox)/su = (x - o_x)/s is the only integer with i≤u<i+1i \le u < i + 1; multiply by s>0s > 0 and add oxo_x. □\square

So line L1 gives the only cell (i,j)(i, j) of the infinite lattice with (x,y)∈Qij(x, y) \in Q_{ij}, and line L2 returns it exactly when it is a cell of the grid. INDEX changes nothing.

Lemma 2 (update). UPDATE keeps (G). Proof. Line L3 maps (i,j)(i, j) with 0≤i<W0 \le i < W, 0≤j<H0 \le j < H to k=jW+ik = j W + i, and this map is a bijection onto {0,…,WH−1}\{0, \ldots, W H - 1\}: i=k mod Wi = k \bmod W and j=⌊k/W⌋j = \lfloor k / W \rfloor. So line L4 changes the entry of cell (i,j)(i, j) and no other entry, and part 1 and part 3 for the other cells hold. Line L4 applies the update rule to the old value, so part 3 holds for cell (i,j)(i, j), and the clamp puts the new value in [lmin⁡,lmax⁡][l_{\min}, l_{\max}], so part 2 holds. □\square

Without clamping (lmin⁡=−∞l_{\min} = -\infty, lmax⁡=+∞l_{\max} = +\infty), induction on the number of updates with Lemma 2 gives the closed form lij=l0+∑k(lk−l0)l_{ij} = l_0 + \sum_k (l_k - l_0) over the updates lkl_k of cell (i,j)(i, j). PROBABILITY returns 1−1/(1+el)=el/(1+el)1 - 1/(1 + e^{l}) = e^l / (1 + e^l), which is the inverse of p↦log⁡(p/(1−p))p \mapsto \log(p / (1 - p)), so it returns the probability that the log odds encode.

The traversal. Let a≠ba \ne b be two points, d=b−ad = b - a and p(t)=a+tdp(t) = a + t d for t∈[0,1]t \in [0, 1]. Let (ia,ja)(i_a, j_a) and (ib,jb)(i_b, j_b) be their cells. Call the segment generic if no p(t)p(t) with t∈[0,1]t \in [0, 1] lies on a vertical and a horizontal cell edge at once (it passes through no corner), and aa and bb lie on no cell edge.

Lemma 3 (crossings). Let dx>0d_x > 0. The times t∈(0,1]t \in (0, 1] at which p(t)p(t) lies on a vertical edge x=ox+ksx = o_x + k s are τk=(ox+ks−ax)/dx\tau_k = (o_x + k s - a_x) / d_x for k=ia+1,…,ibk = i_a + 1, \ldots, i_b, and there are ib−iai_b - i_a of them, in increasing order. For dx<0d_x < 0 the same holds with k=ia,ia−1,…,ib+1k = i_a, i_a - 1, \ldots, i_b + 1, and there are ia−ibi_a - i_b of them. For dx=0d_x = 0 there is none, and ia=ibi_a = i_b. Proof. For dx>0d_x > 0, x(t)x(t) increases from axa_x to bxb_x, so it meets the edge ox+kso_x + k s exactly when ax<ox+ks≤bxa_x < o_x + k s \le b_x. By Lemma 1, ox+ias≤ax<ox+(ia+1)so_x + i_a s \le a_x < o_x + (i_a + 1) s and the same for bb, so these are the kk with ia+1≤k≤ibi_a + 1 \le k \le i_b. The case dx<0d_x < 0 is symmetric (in a generic segment aa is on no edge, so the edge ox+ias<axo_x + i_a s < a_x is met), and dx=0d_x = 0 is clear. □\square

Claim. For a generic segment, CELLS-ON-SEGMENT ends after n=∣ib−ia∣+∣jb−ja∣n = |i_b - i_a| + |j_b - j_a| steps, returns n+1n + 1 distinct cells c0,…,cnc_0, \ldots, c_n with c0=(ia,ja)c_0 = (i_a, j_a) and cn=(ib,jb)c_n = (i_b, j_b), each step moves to a cell that shares an edge with the previous one, and {c0,…,cn}\{c_0, \ldots, c_n\} is exactly the set of cells whose open square meets the segment.

Proof. By Lemma 3, the ∣ib−ia∣|i_b - i_a| vertical crossing times and the ∣jb−ja∣|j_b - j_a| horizontal crossing times are all in (0,1)(0, 1) (generic: bb is on no edge), and no vertical crossing time equals a horizontal one (no corner). Merge them into one increasing list 0<σ1<⋯<σn<10 < \sigma_1 < \cdots < \sigma_n < 1, and set σ0=0\sigma_0 = 0, σn+1=1\sigma_{n+1} = 1.

On each open interval (σm,σm+1)(\sigma_m, \sigma_{m+1}), p(t)p(t) is on no edge, so it stays in one open square Qc∘Q^\circ_{c}; call this cell eme_m. At σm+1\sigma_{m+1} the point crosses one edge, vertical or horizontal, so em+1e_{m+1} differs from eme_m by ±1\pm 1 in one index: by sign⁡(dx)\operatorname{sign}(d_x) in ii at a vertical crossing, and by sign⁡(dy)\operatorname{sign}(d_y) in jj at a horizontal one. Also e0=(ia,ja)e_0 = (i_a, j_a), since aa lies in the interior of its cell.

Invariant of the loop, before step m+1m + 1 (for m=0,…,nm = 0, \ldots, n): the current cell is (i,j)=em(i, j) = e_m, the cells e0,…,eme_0, \ldots, e_m have been output, txt_x is the first vertical crossing time after σm\sigma_m (or +∞+\infty if none is left), and tyt_y is the first horizontal one.

Initialization. Line L6 sets (i,j)=(ia,ja)=e0(i, j) = (i_a, j_a) = e_0, line L8 outputs it, and line L7 sets txt_x to the time of the next vertical edge in the direction of dxd_x, which is τia+1\tau_{i_a + 1} (or τia\tau_{i_a} for dx<0d_x < 0), the first vertical crossing; the same for tyt_y.

Maintenance. The next crossing time σm+1\sigma_{m+1} is min⁡(tx,ty)\min(t_x, t_y). If i=ibi = i_b, all vertical crossings are done, because each of them moves ii one step from iai_a towards ibi_b; then the next crossing is horizontal. If j=jbj = j_b, it is vertical. If neither holds, both kinds remain, and the smaller of txt_x and tyt_y is the next one; they are not equal (no corner). So line L10 or line L11 makes the same move as the crossing at σm+1\sigma_{m+1}, and (i,j)(i, j) becomes em+1e_{m+1}. Consecutive crossing times of one kind differ by exactly s/∣dx∣s / |d_x| (or s/∣dy∣s / |d_y|), because consecutive edges are ss apart, so adding Δtx\Delta t_x (or Δty\Delta t_y) gives the next crossing time of that kind. Line L12 outputs em+1e_{m+1}.

Termination. The loop runs exactly nn times, and then (i,j)=en(i, j) = e_n, the cell of the last interval (σn,1)(\sigma_n, 1), which holds the points just before bb; since bb is in the interior of its cell, en=(ib,jb)e_n = (i_b, j_b).

Each step changes one index by ±1\pm 1 in a fixed direction per axis, so the indices are monotone, and no cell is output twice. Each output cell eme_m contains p(t)p(t) for tt in the open interval (σm,σm+1)(\sigma_m, \sigma_{m+1}), so its open square meets the segment. Conversely, if Qc∘Q^\circ_c meets the segment at p(t)p(t), then tt is no crossing time (a point of an open square is on no edge), so tt lies in some interval (σm,σm+1)(\sigma_m, \sigma_{m+1}), or t∈{0,1}t \in \{0, 1\} inside e0e_0 or ene_n, and c=emc = e_m. □\square

INSERT-RAY. It calls UPDATE on cells of the grid only (the tests of lines L13 and L14), so by Lemma 2 it keeps (G). By the claim, it updates each cell that the beam crosses once: with lfreel_{\mathrm{free}} for the cells before the end cell, and with loccl_{\mathrm{occ}} or lfreel_{\mathrm{free}} for the cell of the end point.

Non-generic segments and rounding. If the segment passes through a corner, then at that time tx=tyt_x = t_y, and line L10 steps in yy first; the extra cell meets the segment only at the corner. All other parts of the proof hold. In floating-point arithmetic, txt_x and tyt_y carry rounding errors, so for two crossings that are very close, the order can swap and the output can contain a corner cell instead of its neighbor. The tests j=jbj = j_b and i≠ibi \ne i_b of line L10 still force exactly ∣ib−ia∣|i_b - i_a| steps in ii and ∣jb−ja∣|j_b - j_a| steps in jj, so the output always starts at the cell of aa, ends at the cell of bb, moves by edge neighbors, and the loop always stops after nn steps. ■\blacksquare

Complexity

The model is the word RAM, with one step for each arithmetic operation on a floating-point log odds value held in one word, and for the floor, exp and comparison of line L1, L5 and L10.

operation time case
index O(1)O(1) worst
update O(1)O(1) worst
probability O(1)O(1) worst
cells_on_segment O(1+L/s)O(1 + L / s) worst
insert_ray O(1+L/s)O(1 + L / s) worst
space O(g)O(g) total

A segment of length LL crosses at most ∣dx∣/s+1|d_x| / s + 1 vertical and ∣dy∣/s+1|d_y| / s + 1 horizontal edges, and ∣dx∣+∣dy∣≤2 L|d_x| + |d_y| \le \sqrt 2\, L, so it visits O(1+L/s)O(1 + L / s) cells.

The space is the real cost. A floor of 100 m by 100 m at s=0.05s = 0.05 m has 2000×2000=4⋅1062000 \times 2000 = 4 \cdot 10^6 cells, which is 16 MB with 4-byte floats. A volume of 100 m by 100 m by 10 m at the same resolution has 8⋅1088 \cdot 10^8 cells, which is 3.2 GB, mostly free or unknown space. That is why 3D maps use an octree occupancy map.

Variants

  • Bytes instead of floats. Store each cell as a small integer. The ROS message nav_msgs/OccupancyGrid stores one signed byte per cell, a probability in percent from 0 to 100, or −1-1 for unknown, in row-major order.
  • Clamping. Bounds on the log odds keep the map able to change when the world changes, and make a fully certain cell recognizable. The OctoMap software uses this in 3D.
  • Growing grids. Store the grid in fixed-size tiles in a hash table, keyed by the tile index, and create a tile when a ray first reaches it. The robot can then explore without a size known in advance.
  • Multi-resolution grids. A quadtree in 2D or the octree occupancy map in 3D merges large regions with the same value.
  • Other cell contents. A cell can hold counts of hits and misses, a height (an elevation map), or the distance to the nearest occupied cell (a distance transform, used by the likelihood field model).
  • Coverage maps. Some variants store the fraction of a cell that is filled, a value between 0 and 1, instead of the probability of a binary state. This handles cells that are half wall and half free space.

When to use it

Use an occupancy grid map for a 2D map of a building or a site for a ground robot. It gives constant time lookups for planning and for sensor models, a simple update from range sensors, and an explicit notion of free and unknown space, which frontier-based exploration needs. It handles any shape of obstacle at the chosen resolution. Use an octree in 3D or for large mostly empty volumes, a feature map with landmarks when the world has few distinct objects, and a topological map when only the connections between places matter.

Pitfalls

  • Treating the cells as independent. The map is a product of independent cells. Two cells of one wall, or the cells behind a door, are clearly dependent. The probabilities in the grid are therefore too confident, and the grid is not a sample from any real map distribution.
  • Resolution. A thin obstacle such as a table leg can fall between two beams or occupy only part of a cell, and a cell that is half wall and half free space has no correct binary value. Halving ss multiplies the memory by 4 in 2D and by 8 in 3D.
  • Row-major against column-major. Image libraries, ROS messages and textbooks differ in the order of (i,j)(i, j) and in where the origin is. A wrong order mirrors the map along a diagonal; check with an asymmetric test map.
  • Points on cell edges. Use half-open cells and floor, not rounding, in INDEX. With int() instead of floor, negative coordinates are rounded towards zero, and the cells −1-1 and 00 are merged.
  • Unknown against probability 0.5. A cell at exactly l0l_0 can be unknown or have balanced evidence. Planners that treat unknown cells as free need a separate flag.
  • Clamping changes the result. With clamping, the order of updates matters, as the example shows. Tests that compare a clamped map with a closed-form sum must take this into account.

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_map.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/occupancy-grid-map/. The authors are listed in prov/MJFAZ4.jsonl.

"""A 2D occupancy grid map that stores log odds, with optional clamping.

The grid has W by H square cells of side res. Cell (i, j) covers the
half-open square [ox + i res, ox + (i + 1) res) x [oy + j res, oy + (j + 1) res).
The log odds are kept in one flat list in row-major order, at index j W + i.
"""

import math

import robest


class OccupancyGridMap:
    """A grid of log odds values l = log(p / (1 - p)), one per cell.

    p_prior is the prior occupancy probability of every cell. If p_min and
    p_max are given, every update clamps the log odds to
    [logodds(p_min), logodds(p_max)].
    """

    def __init__(self, ox, oy, res, width, height, p_prior=0.5, p_min=None, p_max=None):
        if res <= 0 or width <= 0 or height <= 0:
            raise ValueError("the grid must have a positive size")
        self.ox, self.oy, self.res = float(ox), float(oy), float(res)
        self.width, self.height = int(width), int(height)
        self.l0 = robest.logodds(p_prior)
        self.l_min = robest.logodds(p_min) if p_min is not None else -math.inf
        self.l_max = robest.logodds(p_max) if p_max is not None else math.inf
        if not self.l_min <= self.l0 <= self.l_max:
            raise ValueError("the prior must lie between the clamping bounds")
        self.l = [self.l0] * (self.width * self.height)

    def check_invariant(self):
        """Raise AssertionError unless there is one value per cell, inside the bounds."""
        assert len(self.l) == self.width * self.height
        assert all(self.l_min <= v <= self.l_max for v in self.l)

    # ------------------------------------------------------------ geometry

    def cell_of(self, x, y):
        """Return the integer indices (i, j) of the cell that holds (x, y).

        The indices may lie outside the grid; use inside() to check them.
        """
        i = math.floor((x - self.ox) / self.res)  # @line L1
        j = math.floor((y - self.oy) / self.res)
        return i, j

    def inside(self, i, j):
        return 0 <= i < self.width and 0 <= j < self.height  # @line L2

    def index(self, x, y):
        """Return the cell (i, j) that holds the point (x, y), or None outside the grid."""
        i, j = self.cell_of(x, y)
        return (i, j) if self.inside(i, j) else None

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

    # ------------------------------------------------------------ values

    def log_odds(self, i, j):
        return self.l[j * self.width + i]

    def probability(self, i, j):
        return robest.prob_from_logodds(self.l[j * self.width + i])  # @line L5

    def update(self, i, j, l_meas):
        """Add the log odds l_meas of one inverse model value to cell (i, j)."""
        k = j * self.width + i  # @line L3
        v = self.l[k] + l_meas - self.l0  # @line L4
        self.l[k] = min(self.l_max, max(self.l_min, v))

    # ------------------------------------------------------------ rays

    def cells_on_segment(self, a, b):
        """Return the cells that the segment from a to b crosses, in order.

        This is the traversal of Amanatides and Woo (1987) on the infinite
        lattice of cells: it starts in the cell of a, ends in the cell of b,
        and each step moves to a cell that shares an edge with the last one.
        """
        ax, ay = a
        bx, by = b
        i, j = self.cell_of(ax, ay)  # @line L6
        ib, jb = self.cell_of(bx, by)
        dx, dy = bx - ax, by - ay
        step_i = 1 if dx > 0 else -1
        step_j = 1 if dy > 0 else -1
        if dx != 0:  # @line L7
            edge = self.ox + (i + (1 if dx > 0 else 0)) * self.res
            t_max_i, t_delta_i = (edge - ax) / dx, self.res / abs(dx)
        else:
            t_max_i, t_delta_i = math.inf, math.inf
        if dy != 0:
            edge = self.oy + (j + (1 if dy > 0 else 0)) * self.res
            t_max_j, t_delta_j = (edge - ay) / dy, self.res / abs(dy)
        else:
            t_max_j, t_delta_j = math.inf, math.inf
        cells = [(i, j)]  # @line L8
        for _ in range(abs(ib - i) + abs(jb - j)):  # @line L9
            if j == jb or (i != ib and t_max_i < t_max_j):  # @line L10
                i += step_i
                t_max_i += t_delta_i
            else:  # @line L11
                j += step_j
                t_max_j += t_delta_j
            cells.append((i, j))  # @line L12
        return cells

    def insert_ray(self, a, b, hit, l_occ=None, l_free=None):
        """Update the cells of one beam from the sensor at a to the end point b.

        The cells before the end cell get l_free. The end cell gets l_occ if
        hit is true (the beam stopped at an obstacle) and l_free if not (a
        max range reading). Cells outside the grid are skipped. The default
        values are the log odds of 0.7 and 0.4, which are rules of thumb.
        """
        if l_occ is None:
            l_occ = robest.logodds(0.7)
        if l_free is None:
            l_free = robest.logodds(0.4)
        cells = self.cells_on_segment(a, b)
        for i, j in cells[:-1]:  # @line L13
            if self.inside(i, j):
                self.update(i, j, l_free)
        i, j = cells[-1]
        if self.inside(i, j):  # @line L14
            self.update(i, j, l_occ if hit else l_free)
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_map.py 194 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/occupancy-grid-map/. The authors are listed in prov/MJFAZ4.jsonl.

import math
import random

import pytest

import robest
from occupancy_grid_map import OccupancyGridMap

L_OCC = robest.logodds(0.7)
L_FREE = robest.logodds(0.4)


def open_cell_meets_segment(g, i, j, a, b):
    """Brute force: does the open square of cell (i, j) meet the segment ab?"""
    lo, hi = 0.0, 1.0
    for k, (c0, c1) in enumerate(
        [(g.ox + i * g.res, g.ox + (i + 1) * g.res), (g.oy + j * g.res, g.oy + (j + 1) * g.res)]
    ):
        p, d = a[k], b[k] - a[k]
        if d == 0:
            if not c0 < p < c1:
                return False
            continue
        t0, t1 = sorted(((c0 - p) / d, (c1 - p) / d))
        lo, hi = max(lo, t0), min(hi, t1)
    return lo < hi


def test_index_and_center():
    g = OccupancyGridMap(-1.0, 2.0, 0.25, 8, 4)
    assert g.index(-1.0, 2.0) == (0, 0)
    assert g.index(-0.76, 2.24) == (0, 0)
    assert g.index(-0.75, 2.25) == (1, 1)  # cells are half-open
    assert g.index(0.99, 2.99) == (7, 3)
    assert g.index(1.0, 2.5) is None
    assert g.index(-1.01, 2.5) is None
    for i in range(8):
        for j in range(4):
            assert g.index(*g.center(i, j)) == (i, j)


def test_prior_and_check_values():
    g = OccupancyGridMap(0.0, 0.0, 1.0, 3, 3)
    assert g.l0 == 0.0 and g.probability(1, 1) == 0.5
    g.update(1, 1, L_OCC)
    assert g.log_odds(1, 1) == pytest.approx(0.84730, abs=1e-5)
    assert g.probability(1, 1) == pytest.approx(0.7, abs=1e-12)
    g.update(2, 0, robest.logodds(0.6))
    assert g.log_odds(2, 0) == pytest.approx(0.40547, abs=1e-5)
    assert g.log_odds(0, 2) == 0.0


def test_updates_without_clamping_equal_the_closed_form_sum():
    rng = random.Random(11)
    g = OccupancyGridMap(0.0, 0.0, 0.5, 6, 5, p_prior=0.3)
    total = [[g.l0] * 5 for _ in range(6)]
    for _ in range(400):
        i, j = rng.randrange(6), rng.randrange(5)
        v = rng.choice([L_OCC, L_FREE, robest.logodds(rng.uniform(0.05, 0.95))])
        g.update(i, j, v)
        total[i][j] += v - g.l0
    for i in range(6):
        for j in range(5):
            assert g.log_odds(i, j) == pytest.approx(total[i][j], abs=1e-9)


def test_clamping_keeps_bounds_and_makes_the_order_matter():
    def run(seq):
        g = OccupancyGridMap(0.0, 0.0, 1.0, 1, 1, p_min=0.12, p_max=0.97)
        for v in seq:
            g.update(0, 0, v)
            assert g.l_min <= g.log_odds(0, 0) <= g.l_max
        return g.log_odds(0, 0)

    g = OccupancyGridMap(0.0, 0.0, 1.0, 1, 1, p_min=0.12, p_max=0.97)
    assert g.l_max == pytest.approx(3.476, abs=1e-3)
    assert g.l_min == pytest.approx(-1.992, abs=1e-3)
    a = run([L_OCC] * 5 + [L_FREE])
    b = run([L_FREE] + [L_OCC] * 5)
    assert a == pytest.approx(g.l_max + L_FREE, abs=1e-12)
    assert b == pytest.approx(g.l_max, abs=1e-12)
    assert run([L_FREE] * 20) == pytest.approx(g.l_min, abs=1e-12)


def test_random_operations_against_a_dict_model():
    rng = random.Random(23)
    for _ in range(5):
        w, h = rng.randint(1, 7), rng.randint(1, 7)
        g = OccupancyGridMap(rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(0.1, 1.0), w, h,
                             p_prior=0.4, p_min=0.1, p_max=0.95)
        model = {}
        lo, hi = robest.logodds(0.1), robest.logodds(0.95)
        for _ in range(500):
            i, j = rng.randrange(w), rng.randrange(h)
            if rng.random() < 0.7:
                v = rng.choice([L_OCC, L_FREE, rng.uniform(-3.0, 3.0)])
                g.update(i, j, v)
                model[(i, j)] = min(hi, max(lo, model.get((i, j), g.l0) + v - g.l0))
            got = g.probability(i, j)
            want = 1.0 / (1.0 + math.exp(-model.get((i, j), g.l0)))
            assert got == pytest.approx(want, abs=1e-12)
            g.check_invariant()
        for i in range(w):
            for j in range(h):
                assert g.log_odds(i, j) == pytest.approx(model.get((i, j), g.l0), abs=1e-12)


def test_prior_outside_the_clamping_bounds_is_rejected():
    with pytest.raises(ValueError):
        OccupancyGridMap(0.0, 0.0, 1.0, 2, 2, p_prior=0.05, p_min=0.12, p_max=0.97)


def test_cells_on_segment_against_brute_force():
    rng = random.Random(5)
    g = OccupancyGridMap(-0.3, 0.7, 0.2, 10, 10)
    for _ in range(300):
        a = (rng.uniform(-2.0, 2.0), rng.uniform(-1.0, 3.0))
        b = (rng.uniform(-2.0, 2.0), rng.uniform(-1.0, 3.0))
        cells = g.cells_on_segment(a, b)
        assert cells[0] == g.cell_of(*a)
        assert cells[-1] == g.cell_of(*b)
        for (i0, j0), (i1, j1) in zip(cells, cells[1:]):
            assert abs(i1 - i0) + abs(j1 - j0) == 1
        assert len(set(cells)) == len(cells)
        ia, ja = g.cell_of(*a)
        ib, jb = g.cell_of(*b)
        want = {
            (i, j)
            for i in range(min(ia, ib), max(ia, ib) + 1)
            for j in range(min(ja, jb), max(ja, jb) + 1)
            if open_cell_meets_segment(g, i, j, a, b)
        }
        assert set(cells) == want


def test_cells_on_axis_parallel_segments():
    g = OccupancyGridMap(0.0, 0.0, 1.0, 10, 10)
    assert g.cells_on_segment((0.5, 2.5), (4.5, 2.5)) == [(i, 2) for i in range(5)]
    assert g.cells_on_segment((3.5, 4.5), (3.5, 1.5)) == [(3, j) for j in range(4, 0, -1)]
    assert g.cells_on_segment((2.2, 2.7), (2.8, 2.1)) == [(2, 2)]


def test_page_example():
    g = OccupancyGridMap(0.0, 0.0, 1.0, 5, 3)
    a = (0.5, 0.5)
    assert g.cells_on_segment(a, (3.7, 2.4)) == [(0, 0), (1, 0), (1, 1), (2, 1), (3, 1), (3, 2)]
    for b in [(3.7, 2.4), (4.5, 0.5), (3.7, 2.4)]:
        g.insert_ray(a, b, hit=True)
        g.check_invariant()
    want = {
        (3, 2): 2 * L_OCC,
        (1, 1): 2 * L_FREE, (2, 1): 2 * L_FREE, (3, 1): 2 * L_FREE,
        (0, 0): 3 * L_FREE, (1, 0): 3 * L_FREE, (2, 0): L_FREE, (3, 0): L_FREE, (4, 0): L_OCC,
    }
    for i in range(5):
        for j in range(3):
            assert g.log_odds(i, j) == pytest.approx(want.get((i, j), 0.0), abs=1e-12)
    assert g.probability(3, 2) == pytest.approx(0.49 / 0.58, abs=1e-12)
    assert g.probability(0, 0) == pytest.approx(8 / 35, abs=1e-12)


def test_insert_ray_hit_and_max_range():
    g = OccupancyGridMap(0.0, 0.0, 1.0, 10, 3)
    g.insert_ray((0.5, 1.5), (4.5, 1.5), hit=True)
    assert [g.log_odds(i, 1) for i in range(6)] == [L_FREE] * 4 + [L_OCC, 0.0]
    g.insert_ray((0.5, 0.5), (4.5, 0.5), hit=False)
    assert [g.log_odds(i, 0) for i in range(6)] == [L_FREE] * 5 + [0.0]
    assert all(g.log_odds(i, 2) == 0.0 for i in range(10))


def test_insert_ray_skips_cells_outside_the_grid():
    g = OccupancyGridMap(0.0, 0.0, 1.0, 4, 4)
    g.insert_ray((2.5, 2.5), (7.5, 2.5), hit=True)
    assert [g.log_odds(i, 2) for i in range(4)] == [0.0, 0.0, L_FREE, L_FREE]
    g.insert_ray((-3.5, 0.5), (1.5, 0.5), hit=True)
    assert [g.log_odds(i, 0) for i in range(4)] == [L_FREE, L_OCC, 0.0, 0.0]


def test_storage_is_row_major():
    g = OccupancyGridMap(0.0, 0.0, 1.0, 5, 3)
    g.update(4, 1, L_OCC)
    assert g.l[1 * 5 + 4] == L_OCC
    assert sum(1 for v in g.l if v != 0.0) == 1
    assert len(g.l) == 15


def test_invalid_grid():
    with pytest.raises(ValueError):
        OccupancyGridMap(0.0, 0.0, 0.0, 5, 5)
    with pytest.raises(ValueError):
        OccupancyGridMap(0.0, 0.0, 1.0, 0, 5)

History

Moravec and Elfes (1985) used a grid of cells to combine many wide angle sonar readings on the robots of the Carnegie Mellon Mobile Robot Laboratory. Each reading made the cells of its cone more likely to be empty and the cells near its arc more likely to be occupied. Elfes (1989) described the occupancy grid as a random field of cell states with stochastic estimates, updated by Bayes' rule, and used it for path planning and navigation. Thrun, Burgard and Fox (2005) present the log odds form and the binary Bayes filter per cell that most software uses today. The traversal of cells along a beam is the voxel traversal of Amanatides and Woo (1987), first written for ray tracing.

References

  1. Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 9, Section 9.2 (the grid of binary cells, the factorization of the map posterior over cells and the log odds form), 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 that holds the evidence of sonar readings for empty and occupied space
  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 multidimensional random field of cell states with stochastic estimates
  4. John Amanatides and Andrew Woo, A fast voxel traversal algorithm for ray tracing, Eurographics 1987, the traversal of the cells that a ray crosses, with the next crossing parameters tMaxX and tMaxY and the steps tDeltaX and tDeltaY

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.cells_on_segment
  • a full proof of time.index
  • a full proof of time.insert_ray
  • a full proof of time.probability
  • a full proof of time.update
  • 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)
WritingW4 complete
  • a review of the text: no review record reviews/MJFAZ4/text.yaml