Algorithm Search⌘K

Data structureadvanced

Octree occupancy map

Also called OctoMap.

A probabilistic 3D occupancy map stored in an octree with log odds, clamping and pruning so free and unknown space are compact.

Time
O(R D (1 + L / s)) insert_scanO(D) search · updateO(1 + L / s) voxels_on_segment
Space
O(1 + K D) total
Where
D = the depth of the tree; K = the number of leaves; L = the length of the longest beam in meters; R = the number of end points in a scan; s = the side of a voxel in meters
Origin
Armin Hornung, Kai M. Wurm, Maren Bennewitz, Cyrill Stachniss, Wolfram Burgard, 2013

An octree occupancy map stores a 3D occupancy grid map in an octree. Each leaf holds the log odds l=log⁡(p/(1−p))l = \log(p / (1 - p)) that its cube of space is occupied, and the update of a voxel is the same binary Bayes filter in log odds as in a 2D grid. Three choices make the tree small. Unknown space has no nodes at all. The log odds of each voxel are clamped to a range [lmin⁡,lmax⁡][l_{\min}, l_{\max}], so that a voxel seen free many times reaches exactly lmin⁡l_{\min}. And when the eight children of a node are leaves with one equal value, they are pruned into one leaf. Large free volumes and large walls then cost few nodes. The design is that of OctoMap by Hornung, Wurm, Bennewitz, Stachniss and Burgard (2013), an open source library that is also available in ROS.

In plain words

Think of a big cube of space that holds a building. Cut it into eight smaller cubes, cut each of those into eight, and so on, until the cubes are a few centimeters wide. A robot with a laser only writes into the small cubes that its beams touch. A small cube that a beam passes through becomes more likely to be empty; a small cube where a beam stops becomes more likely to hold something. After enough agreement, a cube is "sure" and stops changing much. When all eight parts of a cube are sure in the same way, the map forgets the parts and keeps only the big cube. Parts of space that no beam ever reached are not stored at all. To read the map at a coarse size, look at a big cube: it says "occupied" as soon as one of its parts is.

The abstract type

The map is a partial function from the voxels of a cube of 2D2^D voxels on each side to log odds values in [lmin⁡,lmax⁡][l_{\min}, l_{\max}]. A voxel without a value is unknown. The operations are:

  • key(point): the integer key (kx,ky,kz)(k_x, k_y, k_z) of the voxel that holds a point, or none outside the map.
  • update(k, l_meas): set the value of voxel kk to min⁡(lmax⁡,max⁡(lmin⁡,l+lmeas))\min(l_{\max}, \max(l_{\min}, l + l_{\mathrm{meas}})), where ll is its old value, or 0 (the prior probability 0.5) if it was unknown.
  • search(k, d): the value of the block of depth dd that holds kk: the maximum of the values of its known voxels, or unknown if it has none. Depth DD gives the value of the voxel itself.
  • insert_scan(s, Z): integrate one scan from the sensor origin ss with the end points ZZ.

The maximum in search is the conservative choice of Hornung et al.: a coarse block is as occupied as its most occupied part. The mean of the children is the other choice that they describe.

Representation

  • The depth DD, the voxel side ss in meters and the origin oo of the map. Voxel kk is the half-open cube with the lowest corner o+sko + s k, and the map covers a cube of side 2Ds2^D s.
  • A node of depth dd covers a block of 2D−d2^{D - d} voxels on each side. Child number cc of a node of depth dd holds the voxels whose bit D−1−dD - 1 - d of kxk_x, kyk_y and kzk_z form cc (one bit per axis). The key of a voxel is the path from the root, so nodes store no coordinates.
  • A leaf stores one log odds value. A leaf of depth DD is one voxel; a leaf of depth d<Dd < D is a pruned block, all of whose voxels have its value.
  • An inner node stores 8 child slots, each empty or a node, and the maximum of the values of its children.
  • The values loccl_{\mathrm{occ}} and lfreel_{\mathrm{free}} of the inverse sensor model, and the clamping bounds.

Invariant (T). (1) Inner nodes have depth below DD, and each inner node except the root has at least one child. (2) A voxel is known if and only if the descent along its key reaches a leaf, and then its value is the value of that leaf. (3) An inner node holds the maximum of its children's values. (4) Leaf values are in [lmin⁡,lmax⁡][l_{\min}, l_{\max}]. (5) No inner node has 8 children that are leaves with one equal value.

Part 5 makes the tree canonical: for each map there is exactly one tree that satisfies (T), so the number of nodes depends only on the values, not on the order of the updates.

Operations

  1. UPDATE(T, k, l_meas) ▷ k = (k_x, k_y, k_z), each in [0, 2^D)
  2. 1n ← T.root; P ← empty stack
  3. 2for d ← 0 to D - 1:
  4. 3if n is a leaf then give n 8 leaf children with the value of n ▷ expand a pruned block
  5. 4c ← bit (D-1-d) of k_x + 2 · bit (D-1-d) of k_y + 4 · bit (D-1-d) of k_z
  6. 5if child c of n is empty then create it: a leaf with value 0 if d = D - 1, else an inner node with no children
  7. 6push n on P; n ← child c of n
  8. 7n.value ← min(l_max, max(l_min, n.value + l_meas))
  9. 8while P is not empty:
  10. 9q ← pop P
  11. 10if q has 8 children that are leaves with one equal value v then make q a leaf with value v ▷ prune
  12. 11else q.value ← the maximum of the values of the children of q

The descent creates the missing nodes on the way to the voxel and expands a pruned block that the update must split. Line L7 is the log odds form of the binary Bayes filter with the clamping rule L←max⁡(min⁡(L+lmeas,lmax⁡),lmin⁡)L \leftarrow \max(\min(L + l_{\mathrm{meas}}, l_{\max}), l_{\min}), which Hornung et al. take from Yguel et al. (2007). The ascent restores the maxima and prunes. A new inner node of line L5 has no children for a moment, but the next step of the descent gives it one.

  1. SEARCH(T, k, d_q) ▷ the value of the block of depth d_q that holds k, or unknown
  2. 1n ← T.root; d ← 0
  3. 2while d < d_q and n is not a leaf:
  4. 3n ← child c(k, d) of n; d ← d + 1
  5. 4if n is empty then return unknown
  6. 5return n.value ▷ unknown for a root with no children

A search that reaches a leaf above depth dqd_q returns the value of the pruned block, which is the value of every voxel inside it.

  1. INSERT-SCAN(T, s, Z) ▷ sensor origin s, end points Z, every beam a hit
  2. 1F ← empty set; O ← empty set
  3. 2for each end point z in Z:
  4. 3V ← the voxels that the segment from s to z crosses, in order
  5. 4add all voxels of V except the last to F; add the last voxel of V to O
  6. 5for each voxel k in F - O inside the map: UPDATE(T, k, l_free)
  7. 6for each voxel k in O inside the map: UPDATE(T, k, l_occ)

Line L19 is the 3D form of the Amanatides-Woo traversal that the occupancy grid map page describes in 2D, with three next-crossing parameters instead of two. Lines L21 and L22 update each voxel of the scan once, and an end voxel gets loccl_{\mathrm{occ}} even when another beam of the same scan passes through it. Hornung et al. use this rule because a laser that sweeps over a flat surface at a shallow angle otherwise clears voxels that an earlier beam of the same sweep marked occupied, and leaves holes in the surface. The implementation sorts the two sets only to get a fixed order; the result does not depend on the order.

Example

Pruning and expansion. Take D=2D = 2, a cube of 4×4×4=644 \times 4 \times 4 = 64 voxels, with the values of the paper: locc=0.85l_{\mathrm{occ}} = 0.85, lfree=−0.4l_{\mathrm{free}} = -0.4, lmin⁡=−2l_{\min} = -2 and lmax⁡=3.5l_{\max} = 3.5. A full tree of depth 2 has 1+8+64=731 + 8 + 64 = 73 nodes.

  1. Update every voxel 5 times with lfreel_{\mathrm{free}}. Each voxel goes −0.4,−0.8,−1.2,−1.6,−2.0-0.4, -0.8, -1.2, -1.6, -2.0 and reaches lmin⁡l_{\min}. During the last round, each group of 8 voxels prunes into its parent as soon as its last voxel reaches −2-2, and the last update prunes the 8 children of the root. The tree is one node: the root, a leaf with the value −2-2 (probability 0.1192) for the whole cube.
  2. Update voxel (1,2,3)(1, 2, 3) once with loccl_{\mathrm{occ}}. Its child numbers are c=0+2⋅1+4⋅1=6c = 0 + 2 \cdot 1 + 4 \cdot 1 = 6 at depth 0 (the high bits 0, 1, 1) and c=1+0+4=5c = 1 + 0 + 4 = 5 at depth 1 (the low bits 1, 0, 1). Line L3 expands the root into 8 leaves of value −2-2, then expands child 6 into 8 voxels. The voxel gets −2+0.85=−1.15-2 + 0.85 = -1.15 (probability 0.2405). The tree has 1+8+8=171 + 8 + 8 = 17 nodes. SEARCH at depth 0 or at depth 1 in child 6 returns −1.15-1.15, the maximum; SEARCH of (3,0,0)(3, 0, 0) at depth 1 returns −2-2 from a pruned leaf.
  3. Update voxel (1,2,3)(1, 2, 3) three times with lfreel_{\mathrm{free}}: −1.55-1.55, −1.95-1.95, then −2.35-2.35, clamped to −2-2. Now the 8 children of child 6 are equal, line L10 prunes them, then the 8 children of the root are equal, and the tree is one node again.

Without clamping, the voxel of step 3 would end at −2.35-2.35, its 63 neighbors at −2-2, and the tree would keep 17 nodes. Clamping is what makes such blocks equal.

One scan. Take D=4D = 4, s=0.1s = 0.1 m and the origin at 0. The sensor is at (0.05,0.05,0.05)(0.05, 0.05, 0.05), in voxel (0,0,0)(0, 0, 0), and the scan has two end points on the xx axis: (0.55,0.05,0.05)(0.55, 0.05, 0.05) in voxel 5 and (0.35,0.05,0.05)(0.35, 0.05, 0.05) in voxel 3 (only kxk_x is written). Then O={3,5}O = \{3, 5\} and F={0,1,2,3,4}F = \{0, 1, 2, 3, 4\}, so INSERT-SCAN gives:

kxk_x 0 1 2 3 4 5 6
log odds -0.4 -0.4 -0.4 0.85 -0.4 0.85 unknown
probability 0.4013 0.4013 0.4013 0.7006 0.4013 0.7006

Voxel 3 lies on the first beam, but it holds an end point, so it gets one update with loccl_{\mathrm{occ}}. Inserting the two beams one by one would give it −0.4+0.85=0.45-0.4 + 0.85 = 0.45 (0.6106) and voxels 0 to 2 the value −0.8-0.8.

Correctness

The abstract value of the tree is the partial map from voxels to log odds that part 2 of (T) defines. The empty tree, a root with no children, is the empty map. The descent of UPDATE changes only the representation: an expansion replaces a pruned leaf by 8 leaves with the same value over the same voxels, and a new inner node makes no voxel known. Line L7 then applies the abstract update to the leaf of kk. The ascent goes up from depth D−1D - 1, and at each node the subtrees of its children already satisfy (T), so the node either prunes into a leaf whose block is uniform or takes the maximum of its children. By induction from the leaves, the value of an inner node is the maximum over the known voxels of its block, which is what SEARCH must return; a missing child means that its whole octant is unknown. Part 5 forces a node to be a leaf exactly when its block is uniform, which makes the tree unique for each map. INSERT-SCAN calls UPDATE once per voxel, and updates of different voxels commute. The full proof is in the correctness proof.

Proof: The octree occupancy map represents the clamped voxel map exactly, and its shape depends only on that mapfull

We use the names of the pseudocode. The map has depth D≥1D \ge 1, so the voxel keys are the triples k=(kx,ky,kz)k = (k_x, k_y, k_z) with 0≤kx,ky,kz<2D0 \le k_x, k_y, k_z < 2^D. For a depth d≤Dd \le D and a key kk, the block Bd(k)B_d(k) is the set of keys that agree with kk in the dd highest bits of each coordinate; it has 2D−d2^{D - d} voxels on each side, B0(k)B_0(k) is the whole map and BD(k)={k}B_D(k) = \{k\}. The eight blocks of depth d+1d + 1 inside a block of depth dd are its octants, and the octant that holds kk has the number c(k,d)c(k, d) of line L4, made of bit D−1−dD - 1 - d of each coordinate. We assume exact arithmetic for the values; the clamp of line L7 and the comparisons of line L10 are exact in floating point too, so the only rounding is in the sums of line L7, and it is the same rounding as in a direct per-voxel computation.

The abstract map. The abstract value is a partial map MM from keys to log odds: M(k)M(k) is undefined (the voxel is unknown) or a number in [lmin⁡,lmax⁡][l_{\min}, l_{\max}]. The empty map has every voxel unknown. The operation UPDATE(k,l)\mathrm{UPDATE}(k, l) sets M(k)←min⁡(lmax⁡,max⁡(lmin⁡,M0(k)+l))M(k) \leftarrow \min(l_{\max}, \max(l_{\min}, M_0(k) + l)), where M0(k)=M(k)M_0(k) = M(k) if it is defined and 00 (the log odds of the prior 0.50.5) if not. SEARCH(k,d)\mathrm{SEARCH}(k, d) asks for max⁡{M(v):v∈Bd(k),M(v) defined}\max\{M(v) : v \in B_d(k), M(v) \text{ defined}\}, or "unknown" if the block has no known voxel.

Invariant (T). Each node nn has a depth d(n)d(n) and a block B(n)B(n); the root has depth 0 and the whole map as its block, and child number cc of a node of depth dd has depth d+1d + 1 and the octant number cc of its parent's block.

  1. Shape. A node is a leaf or an inner node with 8 child slots. Inner nodes have depth below DD. Every inner node other than the root has at least one child.
  2. Abstraction. A voxel kk is known in MM if and only if the descent from the root along the octants of kk reaches a leaf nn (with k∈B(n)k \in B(n)); then M(k)M(k) is the value of that leaf. So every voxel of the block of a leaf is known with the value of the leaf.
  3. Inner values. The value of an inner node with children is the maximum of the values of its children. The value of the root with no children is "unknown".
  4. Bounds. Every leaf value is in [lmin⁡,lmax⁡][l_{\min}, l_{\max}].
  5. Fully pruned. No inner node has 8 children that are all leaves with one equal value.

Lemma 1 (block maxima). Under parts 1 to 3, the value of every inner node nn with children is max⁡{M(v):v∈B(n) known}\max\{M(v) : v \in B(n) \text{ known}\}, and every node other than an empty root has at least one known voxel in its block. Proof. By induction from the leaves up. A leaf has all voxels of its block known with its value (part 2). An inner node nn has at least one child (part 1), the known voxels of B(n)B(n) are the union of the known voxels of the blocks of its children (part 2: a voxel in an octant without a child is unknown), and the maximum of the children's block maxima is the block maximum of nn (part 3). □\square

Lemma 2 (search). Under (T), SEARCH(k,dq)(k, d_q) returns the answer of the abstract map. Proof. Lines L12 to L14 descend along the octants of kk, one depth per step, and stop at depth dqd_q, at a leaf, or at a missing child. If a child is missing at depth d≤dqd \le d_q, then by part 2 every voxel of that octant is unknown, so Bdq(k)B_{d_q}(k), which lies inside it, has no known voxel: line L15 answers "unknown", which is right. If the descent stops at a leaf nn of depth d≤dqd \le d_q, then Bdq(k)⊆B(n)B_{d_q}(k) \subseteq B(n), all its voxels are known with the value of nn (part 2), so the block maximum is that value. If it stops at an inner node of depth dqd_q, Lemma 1 gives the block maximum, and for the empty root part 3 gives "unknown". The loop runs at most dq≤Dd_q \le D times. □\square

With dq=Dd_q = D this returns M(k)M(k), the value of the voxel.

Lemma 3 (the descent of UPDATE). After lines L1 to L6, the path PP holds the nodes of depth 0,…,D−10, \ldots, D - 1 on the way to kk, nn is a leaf of depth DD with B(n)={k}B(n) = \{k\}, and its value is M0(k)M_0(k). The abstract map is unchanged, except that kk may now be known with the value 00 if it was unknown. Proof. Line L3 replaces a leaf nn of depth d<Dd < D by an inner node with 8 leaf children that carry its value. The blocks of the children cover B(n)B(n), so by part 2 the abstract map does not change. Line L5 creates a missing child. At depth d+1<Dd + 1 < D it is an inner node with no children, which makes no voxel known; at depth DD it is a leaf with the value 0, which makes exactly the voxel kk known with the value 0=M0(k)0 = M_0(k). Since the descent follows the octants of kk, at depth DD the node nn is the leaf of the single voxel kk. If kk was known before, the descent reached its leaf, possibly through expansions, and that leaf (or the copy of its value made by line L3) holds M(k)=M0(k)M(k) = M_0(k). □\square

During the descent, part 1 can fail for a moment (a new inner node has no children yet), and parts 3 and 5 can fail on the path. Line L7 then sets the value of the leaf of kk to the new abstract value min⁡(lmax⁡,max⁡(lmin⁡,M0(k)+lmeas))\min(l_{\max}, \max(l_{\min}, M_0(k) + l_{\mathrm{meas}})), so part 2 holds for the updated map and part 4 holds for this leaf.

Lemma 4 (the ascent of UPDATE). After lines L8 to L11, (T) holds for the new map. Proof. Only the nodes on the path differ from a state where (T) held, and the path is processed from depth D−1D - 1 up to the root. Claim: when line L9 pops a node qq of depth dd, all nodes below depth dd (the subtrees of the children of qq) satisfy parts 1 to 5. This holds for d=D−1d = D - 1, since the children of qq are leaves of depth DD in the bounds. For the step, consider qq. Each child of qq is either the child on the path, which the previous iteration fixed, or a node off the path, which no line touched since (T) last held, or a leaf created by line L3 with a value in the bounds. So the claim holds for the subtrees of the children. If line L10 finds 8 children that are leaves with one value vv, it makes qq a leaf with value vv: the blocks of the children cover B(q)B(q), all their voxels are known with vv, so part 2 holds for qq, and part 4 holds since vv is a child's value. Otherwise line L11 sets the value of qq to the maximum of its children, which exist (the child on the path does), so parts 1 and 3 hold at qq, and part 5 holds at qq because the test of line L10 failed. After the root is processed, (T) holds everywhere. □\square

The child on the path is always present when line L10 runs: it was created or kept by the descent, and a pruning one level lower turns it into a leaf, it does not remove it. So line L11 never takes the maximum of an empty set.

Theorem 1 (correctness). Starting from the empty map and applying any sequence of UPDATE calls, the tree satisfies (T) for the abstract map of the same sequence of updates, and SEARCH answers as the abstract map. Proof. The empty tree (a root with no children and the value "unknown") satisfies (T) for the empty map. Lemmas 3 and 4 show that each UPDATE keeps (T) for the updated abstract map, and Lemma 2 gives the answers. □\square

Theorem 2 (canonical shape). For each abstract map MM there is exactly one tree that satisfies (T): a node exists for a block if and only if the block has a known voxel and its parent block is not uniform, and a node is a leaf if and only if all voxels of its block are known with one value. So the number of nodes and the shape of the tree depend only on MM, not on the order of the updates that produced it. Proof. Let a block be uniform if all its voxels are known with one value. By part 2, the block of a leaf is uniform. Conversely, let nn be an inner node with a uniform block. Its children cover the block, so all 8 exist (a missing child means unknown voxels); take one of the deepest inner nodes in the subtree of nn whose block is uniform. Its 8 children have uniform blocks and are leaves, since they are deeper. They carry the same value, against part 5. So a node is a leaf if and only if its block is uniform. A node of a block exists if and only if its parent node exists and is an inner node, and has a child there; by part 1 and Lemma 1 a child exists exactly when its octant has a known voxel. By induction from the root, the set of nodes is the set of blocks with a known voxel whose ancestors are not uniform. □\square

Termination. The loop of lines L2 to L6 runs DD times, and the loop of lines L8 to L11 pops the DD nodes of the path, with constant work per node (8 children). SEARCH runs at most DD times.

INSERT-SCAN. Lines L17 to L20 build the set OO of end voxels and the set FF of the other voxels that the beams cross; the traversal of each beam is the 3D form of the traversal proved on the occupancy grid map, with three kinds of crossings instead of two, and it returns, for a beam through no edge or corner of a voxel, exactly the voxels whose open cube meets the beam. Lines L21 and L22 call UPDATE once for each voxel of F∖OF \setminus O with lfreel_{\mathrm{free}} and once for each voxel of OO with loccl_{\mathrm{occ}}, only for keys inside the map. The abstract UPDATE of one voxel does not change any other voxel, so updates of different voxels commute, and the result does not depend on the order of the two loops or of the sets. So after INSERT-SCAN, by Theorem 1, every voxel of the scan has received exactly one clamped update, and the end voxels have received loccl_{\mathrm{occ}} even when another beam of the same scan crossed them. ■\blacksquare

Complexity

The model is the word RAM with keys of DD bits per axis in one word, so line L4 is a constant number of shifts and masks, and one step per operation on a floating-point log odds value.

operation time case
key O(1)O(1) worst
update O(D)O(D) worst
search O(D)O(D) worst
voxels_on_segment O(1+L/s)O(1 + L / s) worst
insert_scan O(RD(1+L/s))O(R D (1 + L / s)) expected, with hash sets
space O(1+KD)O(1 + K D) total

UPDATE does constant work at each of DD levels on the way down and on the way up, since a node has 8 child slots. Each beam crosses O(1+L/s)O(1 + L / s) voxels, and INSERT-SCAN calls UPDATE at most once per voxel. Every node is a leaf or an ancestor of a leaf, and a leaf has at most DD ancestors, so a tree with KK leaves has at most 1+KD1 + K D nodes; it never has more than the full tree, (8D+1−1)/7(8^{D + 1} - 1) / 7 nodes.

The fixed depth makes the per-voxel cost a constant compared with a 3D array: OctoMap uses D=16D = 16, which covers 216⋅0.01=655.362^{16} \cdot 0.01 = 655.36 m at 1 cm, and says the implementation can be extended to 32 levels. Hornung et al. report measurements on a 32-bit system of 40 bytes per inner node and 8 bytes per leaf, with the children of a node in one array that exists only for inner nodes; 80 to 85 percent of the nodes in their datasets were leaves, and this layout saved 60 to 65 percent of memory against eight child pointers in every node. They also report that clamping with pruning compressed their maps by up to 44 percent. These are measurements on their datasets, not bounds.

Variants

  • Mean of the children. Store the average of the children's log odds in inner nodes instead of the maximum. A coarse query then answers how occupied a block is on average, and a small obstacle can disappear at a coarse depth.
  • Maximum likelihood maps. Set every voxel to lmin⁡l_{\min} or lmax⁡l_{\max} by a threshold and then prune. This is lossy but gives much smaller trees; Hornung et al. attribute the threshold idea to Fairfield et al. (2007).
  • Compact files. A maximum likelihood tree can be written as a stream of 2 bits per child (unknown, occupied, free, or inner node with more data), so 16 bits per inner node, with no coordinates, since the order of the stream encodes the positions.
  • Rich voxels. A node can store more data, such as a color or a terrain class, if there is a rule to combine measurements and children.
  • Hierarchies of maps. A tree of submaps, each an octree with its own resolution, for example a table at fine resolution and the room around it at coarse resolution.
  • Other layouts. Some systems store fixed-size blocks of voxels in a hash table keyed by the block index, or order voxels on a Z-order curve; these keep constant time access without a fixed depth. A quadtree is the 2D form of the same map.

When to use it

Use an octree occupancy map for 3D maps from laser scanners or depth cameras when the robot must tell free space from unknown space, for example for collision checking of a drone or a manipulator, or for frontier-based exploration in 3D. It saves memory over a dense 3D occupancy grid map when large parts of the volume are unknown or uniform, and it supports coarse queries at no extra cost. For a ground robot in a building, a 2D grid is simpler and faster. For dense surface reconstruction, where the surface itself matters more than free space, other representations such as distance fields are common. When the map is small and fully observed, a plain 3D array is faster, because a lookup costs one index computation and not DD pointer steps.

Pitfalls

  • The maximum hides free space and unknown space. A coarse block is occupied as soon as one voxel is, and a block with known free voxels and unknown voxels returns the free value; the maximum ignores unknown voxels. A planner that needs to stay out of unknown space must check for it separately.
  • Clamping loses information. Near the bounds, the values no longer count the evidence, and the order of the updates matters. The bounds are a trade-off between confidence and how fast the map adapts to change; the values −2-2 and 3.53.5 were found to work by experiment in the paper, and they are a heuristic.
  • Pruning needs exactly equal values. Without clamping, two voxels with the same evidence in a different order can differ in the last bit, and the tree never prunes. Compare floats exactly, as line L10 does, so that pruning stays lossless.
  • One update per scan. Inserting the beams of a sweeping scanner one by one can clear the occupied voxels of a flat surface seen at a shallow angle. Collect a sweep into one scan and let occupied win, as INSERT-SCAN does.
  • The map has a fixed extent. A tree of depth DD covers 2Ds2^D s per axis around a fixed origin. A point outside has no key, so check the result of key before an update.
  • Deep recursion and many small objects. In a language with costly objects, millions of small nodes take far more memory than the paper's numbers. Real implementations allocate the child array only for inner nodes and keep nodes small.

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.

octree_occupancy_map.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/octree-occupancy-map/. The authors are listed in prov/34SSST.jsonl.

"""A 3D occupancy map in an octree of log odds, with clamping and pruning.

This follows the design of OctoMap (Hornung et al. 2013). The map covers a
cube of 2^D voxels on each side. A voxel has the integer key (kx, ky, kz),
each in [0, 2^D), and covers the half-open cube of side res whose lowest
corner is origin + res * key. A node at depth d covers a block of
2^(D - d) voxels on each side; the root has depth 0 and the voxels depth D.

A voxel that no update has reached is unknown: no node holds it. A leaf
above depth D is a pruned node: all voxels of its block are known and have
its value. An inner node holds the maximum of the values of its children.
The prior occupancy probability of a voxel is 0.5, so its prior log odds
is 0.
"""

import math

import robest


class _Node:
    __slots__ = ("value", "children")

    def __init__(self, value, inner):
        self.value = value
        self.children = [None] * 8 if inner else None


class OctreeOccupancyMap:
    """An octree of depth D over the voxel keys [0, 2^D)^3.

    l_occ and l_free are the log odds of the inverse sensor model for a
    voxel with an end point and for a voxel that a beam passes through.
    l_min and l_max clamp every voxel value. The defaults are the values
    of Hornung et al. (2013): 0.85, -0.4, -2 and 3.5, the log odds of about
    0.7, 0.4, 0.12 and 0.97. Use None for a bound to switch it off.
    """

    def __init__(self, depth, res=1.0, origin=(0.0, 0.0, 0.0),
                 l_occ=0.85, l_free=-0.4, l_min=-2.0, l_max=3.5):
        if depth < 1 or res <= 0:
            raise ValueError("the depth must be at least 1 and res positive")
        self.depth = int(depth)
        self.size = 1 << self.depth
        self.res = float(res)
        self.origin = tuple(float(v) for v in origin)
        self.l_occ, self.l_free = float(l_occ), float(l_free)
        self.l_min = -math.inf if l_min is None else float(l_min)
        self.l_max = math.inf if l_max is None else float(l_max)
        if not self.l_min <= 0.0 <= self.l_max:
            raise ValueError("the clamping bounds must contain the prior log odds 0")
        self.root = _Node(None, inner=True)

    # ------------------------------------------------------------ invariant

    def check_invariant(self):
        """Raise AssertionError unless the tree is a valid, fully pruned octree."""
        root = self.root
        if root.children is not None and all(c is None for c in root.children):
            assert root.value is None  # the empty map
            return
        self._check(root, 0)

    def _check(self, n, d):
        if n.children is None:
            assert d <= self.depth
            assert self.l_min <= n.value <= self.l_max
            return
        assert d < self.depth and len(n.children) == 8
        kids = [c for c in n.children if c is not None]
        assert kids, "an inner node below the root has no children"
        for c in kids:
            self._check(c, d + 1)
        assert n.value == max(c.value for c in kids)
        same = len(kids) == 8 and all(c.children is None for c in kids)
        assert not (same and all(c.value == kids[0].value for c in kids)), "a node can be pruned"

    # ------------------------------------------------------------ keys

    def key_of(self, point):
        """Return the integer key of the voxel that holds point; it may lie outside the map."""
        return tuple(math.floor((p - o) / self.res) for p, o in zip(point, self.origin))

    def inside(self, key):
        return all(0 <= k < self.size for k in key)

    def key(self, point):
        """Return the key of the voxel that holds point, or None outside the map."""
        k = self.key_of(point)
        return k if self.inside(k) else None

    def _child_index(self, key, d):
        """The child of a node of depth d that holds the voxel key: one bit per axis."""
        b = self.depth - 1 - d
        return ((key[0] >> b) & 1) | (((key[1] >> b) & 1) << 1) | (((key[2] >> b) & 1) << 2)

    # ------------------------------------------------------------ update and search

    def update(self, key, l_meas):
        """Add the log odds l_meas to the voxel key, clamp it, and prune on the way up."""
        if not self.inside(key):
            raise ValueError("the key is outside the map")
        n = self.root  # @line L1
        path = []
        for d in range(self.depth):  # @line L2
            if n.children is None:  # @line L3
                n.children = [_Node(n.value, inner=False) for _ in range(8)]
            c = self._child_index(key, d)  # @line L4
            if n.children[c] is None:  # @line L5
                leaf = d == self.depth - 1
                n.children[c] = _Node(0.0 if leaf else None, inner=not leaf)
            path.append(n)  # @line L6
            n = n.children[c]
        n.value = min(self.l_max, max(self.l_min, n.value + l_meas))  # @line L7
        while path:  # @line L8
            q = path.pop()  # @line L9
            kids = q.children
            first = kids[0]
            if (first is not None and first.children is None
                    and all(c is not None and c.children is None and c.value == first.value
                            for c in kids)):  # @line L10
                q.value = first.value
                q.children = None
            else:  # @line L11
                q.value = max(c.value for c in kids if c is not None)

    def search(self, key, depth=None):
        """Return the log odds of the node of the given depth that holds key, or None if unknown.

        With depth = D (the default) this is the value of the voxel. With a
        smaller depth it is the value of the block of that depth: the
        maximum over the known voxels of the block.
        """
        d_q = self.depth if depth is None else depth
        n = self.root  # @line L12
        d = 0
        while d < d_q and n.children is not None:  # @line L13
            n = n.children[self._child_index(key, d)]  # @line L14
            d += 1
            if n is None:  # @line L15
                return None
        return n.value  # @line L16

    def probability(self, key, depth=None):
        """Return the occupancy probability of search(key, depth), or None if unknown."""
        v = self.search(key, depth)
        return None if v is None else robest.prob_from_logodds(v)

    # ------------------------------------------------------------ rays and scans

    def voxels_on_segment(self, a, b):
        """Return the keys of the voxels that the segment from a to b crosses, in order.

        This is the 3D traversal of Amanatides and Woo (1987) on the infinite
        lattice of voxels. It takes |kb - ka| steps per axis, and each step
        moves to a voxel that shares a face with the last one.
        """
        k = list(self.key_of(a))
        kb = self.key_of(b)
        step, t_max, t_delta = [0] * 3, [math.inf] * 3, [math.inf] * 3
        for ax in range(3):
            dv = b[ax] - a[ax]
            if dv != 0:
                step[ax] = 1 if dv > 0 else -1
                edge = self.origin[ax] + (k[ax] + (1 if dv > 0 else 0)) * self.res
                t_max[ax] = (edge - a[ax]) / dv
                t_delta[ax] = self.res / abs(dv)
        out = [tuple(k)]
        for _ in range(sum(abs(kb[ax] - k[ax]) for ax in range(3))):
            ax = min((t_max[i], i) for i in range(3) if k[i] != kb[i])[1]
            k[ax] += step[ax]
            t_max[ax] += t_delta[ax]
            out.append(tuple(k))
        return out

    def insert_scan(self, sensor, points):
        """Insert one scan: beams from sensor to each end point, all of them hits.

        Every voxel is updated at most once per scan. A voxel that holds an
        end point gets l_occ, even if another beam of the scan passes
        through it. Voxels outside the map are skipped.
        """
        free, occupied = set(), set()  # @line L17
        for z in points:  # @line L18
            cells = self.voxels_on_segment(sensor, z)  # @line L19
            free.update(cells[:-1])  # @line L20
            occupied.add(cells[-1])
        for k in sorted(free - occupied):  # @line L21
            if self.inside(k):
                self.update(k, self.l_free)
        for k in sorted(occupied):  # @line L22
            if self.inside(k):
                self.update(k, self.l_occ)

    # ------------------------------------------------------------ inspection

    def num_nodes(self):
        """Return the number of nodes, the root included."""
        count, stack = 0, [self.root]
        while stack:
            n = stack.pop()
            count += 1
            if n.children is not None:
                stack.extend(c for c in n.children if c is not None)
        return count

    def leaves(self):
        """Return a list of (key of the lowest voxel, side in voxels, value) for each leaf."""
        out = []
        stack = [(self.root, 0, (0, 0, 0))]
        while stack:
            n, d, low = stack.pop()
            if n.children is None:
                out.append((low, 1 << (self.depth - d), n.value))
                continue
            half = 1 << (self.depth - d - 1)
            for c, child in enumerate(n.children):
                if child is not None:
                    off = (low[0] + (c & 1) * half, low[1] + ((c >> 1) & 1) * half,
                           low[2] + ((c >> 2) & 1) * half)
                    stack.append((child, d + 1, off))
        return sorted(out)
rbm.py 482 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.

Conventions (Lynch and Park, Modern Robotics, 2017):
- A matrix is a list of rows. A vector is a flat list.
- hat3(w) is the skew-symmetric matrix [w], so that [w] x = w x x.
- A twist or screw is a 6-vector (omega, v), angular part first.
  hat6(V) is the 4x4 matrix [[[omega], v], [0, 0]].
- A pose T is the 4x4 matrix [[R, p], [0, 1]].
- so3_exp and so3_log use exponential coordinates w = omega_hat * theta,
  with theta = |w| in [0, pi] for so3_log.
- se3_exp and se3_log use 6-vectors (w, v) = S * theta.
- Quaternions are Hamilton, scalar first: q = (w, x, y, z), with i j = k.
- Angles are in radians.

The helper holds no algorithm of a robotics page except the four maps
so3_exp, so3_log, se3_exp and se3_log. The pages so3-logarithm-map and
se3-exponential-map hold their own complete versions with comments.
"""

import math

# Below this angle, the coefficient functions of the exponential and the
# logarithm are evaluated by their Taylor series. The first omitted term
# of each series is of order theta^6 and is below 3e-16 for theta < 1e-2;
# it also multiplies [w] or [w]^2, which are small. Above the threshold,
# the closed forms such as (1 - cos(theta)) / theta^2 lose at most about
# 1e-16 / theta^2 to cancellation, which [w] or [w]^2 brings to 1e-14.
SERIES_THETA = 1e-2

# Above pi - NEAR_PI, so3_log takes the axis from the symmetric part of R
# (which is (R + I) / 2 at theta = pi) and not from the skew part.
NEAR_PI = 1e-2

# A pivot whose magnitude is at most PIVOT_TOL times the largest entry of
# the matrix makes solve, inv and pinv_right raise ValueError.
PIVOT_TOL = 1e-12


# ---------------------------------------------------------------- matrices


def zeros(n, m):
    """Return the n by m zero matrix."""
    return [[0.0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, s):
    """Return s * a for a vector or a matrix a and a number s."""
    if _is_matrix(a):
        return [[s * x for x in row] for row in a]
    return [s * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def mul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x, y):
    """Return the dot product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(x):
    """Return the Euclidean norm of a vector."""
    return math.sqrt(dot(x, x))


def cross(a, b):
    """Return the cross product a x b of two 3-vectors."""
    return [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]


def _max_abs(a):
    return max((abs(x) for row in a for x in row), default=0.0)


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    a is a square matrix. b is a vector or a matrix with one column per
    right-hand side; the result has the same shape as b. Raise ValueError
    if a pivot is at most PIVOT_TOL times the largest entry of a.
    """
    n = len(a)
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    m = [list(map(float, row)) + list(map(float, r)) for row, r in zip(a, rhs)]
    k = len(rhs[0]) if rhs else 0
    tol = PIVOT_TOL * _max_abs(a)
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[piv][c]) <= tol or m[piv][c] == 0.0:
            raise ValueError("matrix is singular to working precision")
        m[c], m[piv] = m[piv], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            if f != 0.0:
                row_r, row_c = m[r], m[c]
                for j in range(c, n + k):
                    row_r[j] -= f * row_c[j]
    x = [[0.0] * k for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(k):
            s = m[r][n + j] - sum(m[r][i] * x[i][j] for i in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def inv(a):
    """Return the inverse of the square matrix a (see solve for errors)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a by elimination."""
    n = len(a)
    m = [list(map(float, row)) for row in a]
    d = 1.0
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[piv][c] == 0.0:
            return 0.0
        if piv != c:
            m[c], m[piv] = m[piv], m[c]
            d = -d
        d *= m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for j in range(c, n):
                m[r][j] -= f * m[c][j]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T.

    a must be symmetric positive definite. Raise ValueError if a diagonal
    entry of the factor is not positive.
    """
    n = len(a)
    low = zeros(n, n)
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
            if i == j:
                if s <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = math.sqrt(s)
            else:
                low[i][j] = s / low[j][j]
    return low


def pinv_right(j):
    """Return the right pseudoinverse J^T (J J^T)^(-1) of a J with full row rank."""
    jt = transpose(j)
    return mul(jt, inv(mul(j, jt)))


# ---------------------------------------------------------------- hat and vee


def hat3(w):
    """Return the 3x3 skew-symmetric matrix [w] of a 3-vector w."""
    return [
        [0.0, -w[2], w[1]],
        [w[2], 0.0, -w[0]],
        [-w[1], w[0], 0.0],
    ]


def vee3(m):
    """Return the 3-vector w of a skew-symmetric matrix m = [w]."""
    return [m[2][1], m[0][2], m[1][0]]


def hat6(v):
    """Return the 4x4 matrix [V] = [[[omega], v], [0, 0]] of V = (omega, v)."""
    w = hat3(v[:3])
    return [
        [w[0][0], w[0][1], w[0][2], v[3]],
        [w[1][0], w[1][1], w[1][2], v[4]],
        [w[2][0], w[2][1], w[2][2], v[5]],
        [0.0, 0.0, 0.0, 0.0],
    ]


def vee6(m):
    """Return the 6-vector (omega, v) of a 4x4 matrix [V]."""
    return [m[2][1], m[0][2], m[1][0], m[0][3], m[1][3], m[2][3]]


# ---------------------------------------------------------------- rotations


def rot_x(a):
    """Return the rotation by a radians about the x axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a):
    """Return the rotation by a radians about the y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a):
    """Return the rotation by a radians about the z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def rpy(roll, pitch, yaw):
    """Return R = Rz(yaw) Ry(pitch) Rx(roll)."""
    return mul(rot_z(yaw), mul(rot_y(pitch), rot_x(roll)))


def so3_exp(w):
    """Return exp([w]) for exponential coordinates w = omega_hat * theta.

    Rodrigues' formula in the form I + A [w] + B [w]^2 with
    A = sin(theta) / theta and B = (1 - cos(theta)) / theta^2.
    """
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
    else:
        a = math.sin(t) / t
        b = (1.0 - math.cos(t)) / (t * t)
    k = hat3(w)
    k2 = mul(k, k)
    return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]


def so3_log(r):
    """Return w = omega_hat * theta with exp([w]) = r and theta in [0, pi].

    theta = atan2(|s|, c), where c = (trace(r) - 1) / 2 = cos(theta) and
    s = vee(r - r^T) / 2 = sin(theta) omega_hat. For theta below
    SERIES_THETA, w = s (1 + theta^2 / 6 + 7 theta^4 / 360). For theta
    above pi - NEAR_PI, the axis comes from the symmetric part
    ((r + r^T) / 2 - c I) / (1 - c) = omega_hat omega_hat^T, and its sign
    from s. At theta = pi both signs are valid; the sign is then chosen so
    that the largest component of the axis is positive.
    """
    c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
    c = max(-1.0, min(1.0, c))
    s = [(r[2][1] - r[1][2]) / 2.0, (r[0][2] - r[2][0]) / 2.0, (r[1][0] - r[0][1]) / 2.0]
    sn = norm(s)
    t = math.atan2(sn, c)
    if t < SERIES_THETA:
        t2 = t * t
        f = 1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0
        return [f * x for x in s]
    if t <= math.pi - NEAR_PI:
        return [t / sn * x for x in s]
    b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
    # b = (1 - c) omega_hat omega_hat^T. Its column k with the largest
    # diagonal entry is (1 - c) omega_k omega_hat, with omega_k^2 >= 1/3.
    k = max(range(3), key=lambda i: b[i][i])
    col = [b[i][k] for i in range(3)]
    axis = [x / norm(col) for x in col]
    if dot(axis, s) < 0.0 or (dot(axis, s) == 0.0 and axis[k] < 0.0):
        axis = [-x for x in axis]
    return [t * x for x in axis]


# ---------------------------------------------------------------- poses


def make_T(r, p):
    """Return the 4x4 pose [[r, p], [0, 1]]."""
    return [
        [r[0][0], r[0][1], r[0][2], p[0]],
        [r[1][0], r[1][1], r[1][2], p[1]],
        [r[2][0], r[2][1], r[2][2], p[2]],
        [0.0, 0.0, 0.0, 1.0],
    ]


def _rp(t):
    return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]


def T_inv(t):
    """Return the inverse [[R^T, -R^T p], [0, 1]] of a pose t."""
    r, p = _rp(t)
    rt = transpose(r)
    return make_T(rt, [-x for x in matvec(rt, p)])


def T_apply(t, x):
    """Return R x + p, the image of the point x under the pose t."""
    r, p = _rp(t)
    return add(matvec(r, x), p)


def se3_exp(xi):
    """Return exp([xi]) for a 6-vector xi = (w, v) = S * theta.

    The rotation is so3_exp(w). The translation is G v with
    G = I + B [w] + C [w]^2, B = (1 - cos(theta)) / theta^2 and
    C = (theta - sin(theta)) / theta^3, theta = |w|. For w = 0 this is a
    translation by v.
    """
    w, v = xi[:3], xi[3:]
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
        c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
    else:
        b = (1.0 - math.cos(t)) / (t * t)
        c = (t - math.sin(t)) / (t * t * t)
    k = hat3(w)
    k2 = mul(k, k)
    g = [[(1.0 if i == j else 0.0) + b * k[i][j] + c * k2[i][j] for j in range(3)] for i in range(3)]
    return make_T(so3_exp(w), matvec(g, v))


def se3_log(t):
    """Return the 6-vector xi = (w, v) with se3_exp(xi) = t and |w| in [0, pi].

    w = so3_log(R) and v = G^(-1) p with
    G^(-1) = I - [w] / 2 + D [w]^2, D = (1 - (theta / 2) cot(theta / 2)) / theta^2.
    """
    r, p = _rp(t)
    w = so3_log(r)
    th = norm(w)
    if th < SERIES_THETA:
        t2 = th * th
        d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
    else:
        half = th / 2.0
        d = (1.0 - half * math.cos(half) / math.sin(half)) / (th * th)
    k = hat3(w)
    k2 = mul(k, k)
    gi = [[(1.0 if i == j else 0.0) - 0.5 * k[i][j] + d * k2[i][j] for j in range(3)] for i in range(3)]
    return w + matvec(gi, p)


def adjoint(t):
    """Return the 6x6 adjoint [[R, 0], [[p] R, R]] of a pose t."""
    r, p = _rp(t)
    pr = mul(hat3(p), r)
    out = zeros(6, 6)
    for i in range(3):
        for j in range(3):
            out[i][j] = r[i][j]
            out[i + 3][j + 3] = r[i][j]
            out[i + 3][j] = pr[i][j]
    return out


# ---------------------------------------------------------------- quaternions


def quat_mul(q, r):
    """Return the Hamilton product q r of quaternions (w, x, y, z)."""
    a1, b1, c1, d1 = q
    a2, b2, c2, d2 = r
    return [
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    ]


def quat_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return [q[0], -q[1], -q[2], -q[3]]


def quat_to_rot(q):
    """Return the rotation matrix of the quaternion q, so that (0, R v) = q (0, v) q*.

    q need not be of unit length; the result is the rotation of q / |q|.
    """
    w, x, y, z = q
    n = w * w + x * x + y * y + z * z
    s = 2.0 / n
    return [
        [1.0 - s * (y * y + z * z), s * (x * y - w * z), s * (x * z + w * y)],
        [s * (x * y + w * z), 1.0 - s * (x * x + z * z), s * (y * z - w * x)],
        [s * (x * z - w * y), s * (y * z + w * x), 1.0 - s * (x * x + y * y)],
    ]


def quat_from_axis_angle(axis, angle):
    """Return (cos(angle / 2), sin(angle / 2) axis / |axis|).

    A zero axis is allowed only with angle 0 (the identity); otherwise
    raise ValueError.
    """
    n = norm(axis)
    if n == 0.0:
        if angle == 0.0:
            return [1.0, 0.0, 0.0, 0.0]
        raise ValueError("zero axis with a nonzero angle")
    s = math.sin(angle / 2.0) / n
    return [math.cos(angle / 2.0), s * axis[0], s * axis[1], s * axis[2]]


# ---------------------------------------------------------------- derivatives


def num_jacobian(f, x, h=1e-6):
    """Return the Jacobian of f at x by central differences with step h.

    f maps a list of n numbers to a list of m numbers; the result is m by n.
    """
    cols = []
    for i in range(len(x)):
        xp = list(x)
        xm = list(x)
        xp[i] += h
        xm[i] -= h
        fp, fm = f(xp), f(xm)
        cols.append([(a - b) / (2.0 * h) for a, b in zip(fp, fm)])
    return transpose(cols)


# ---------------------------------------------------------------- self-test


def self_test():
    """Check the area check values; return True or raise AssertionError."""
    r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
    want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
    w = so3_log(want)
    assert abs(norm(w) - 2.0943951) < 1e-7
    assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
    t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
    want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
    assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
    return True
robest.py 149 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small estimation helpers for the localization and SLAM pages.

Vectors are lists of floats and matrices are lists of rows, as in rbm.py.
The notation follows Thrun, Burgard and Fox, Probabilistic Robotics (2005).

  wrap_angle(a)                       a wrapped to [-pi, pi)
  gauss_sample(rng, mean, cov)        one draw of N(mean, cov), by a Cholesky factor
  gauss_pdf(x, mean, cov)             the density of N(mean, cov) at x
  mahalanobis2(x, mean, cov)          (x - mean)^T cov^(-1) (x - mean)
  low_variance_resample(rng, w)       indices of a systematic (low variance) resample
  logodds(p), prob_from_logodds(l)    l = log(p / (1 - p)) and its inverse
  CHI2[(dof, level)]                  chi-square quantiles for gates, dof 1 to 3

gauss_pdf and mahalanobis2 also take plain numbers: then cov is a variance.
This module holds no filter, no SLAM back end and no planner.
"""

import math

import rbm

CHI2 = {
    (1, 0.95): 3.841,
    (1, 0.99): 6.635,
    (2, 0.95): 5.991,
    (2, 0.99): 9.210,
    (3, 0.95): 7.815,
    (3, 0.99): 11.345,
}

_TWO_PI = 2.0 * math.pi


def wrap_angle(a):
    """Return a + 2 pi k in [-pi, pi), with ((a + pi) mod 2 pi) - pi.

    An angle that is already in [-pi, pi) comes back unchanged, so that
    small angles keep all their digits.
    """
    if -math.pi <= a < math.pi:
        return float(a)
    w = math.fmod(a + math.pi, _TWO_PI)
    if w < 0.0:
        w += _TWO_PI
    w -= math.pi
    if w >= math.pi:  # rounding can give exactly pi
        w -= _TWO_PI
    return w


def _as_vector(x):
    if isinstance(x, (int, float)):
        return [float(x)], True
    return [float(v) for v in x], False


def _as_matrix(cov, scalar):
    if scalar:
        if isinstance(cov, (int, float)):
            return [[float(cov)]]
        return [[float(cov[0][0])]]
    return [[float(v) for v in row] for row in cov]


def gauss_sample(rng, mean, cov):
    """Draw x = mean + L z, with cov = L L^T and z standard normal.

    rng is a random.Random. cov must be symmetric positive definite.
    A number for mean (with a variance for cov) gives a number.
    """
    mu, scalar = _as_vector(mean)
    if scalar:
        var = float(cov) if isinstance(cov, (int, float)) else float(cov[0][0])
        if var < 0.0:
            raise ValueError("negative variance")
        return mu[0] + math.sqrt(var) * rng.gauss(0.0, 1.0)
    L = rbm.cholesky(_as_matrix(cov, False))
    z = [rng.gauss(0.0, 1.0) for _ in mu]
    return [mu[i] + sum(L[i][j] * z[j] for j in range(i + 1)) for i in range(len(mu))]


def mahalanobis2(x, mean, cov):
    """Return the squared Mahalanobis distance (x - mean)^T cov^(-1) (x - mean)."""
    xv, scalar = _as_vector(x)
    mv, _ = _as_vector(mean)
    if len(xv) != len(mv):
        raise ValueError("x and mean differ in size")
    d = [a - b for a, b in zip(xv, mv)]
    S = _as_matrix(cov, scalar)
    if len(d) == 1:
        return d[0] * d[0] / S[0][0]
    y = rbm.solve(S, d)
    return sum(a * b for a, b in zip(d, y))


def gauss_pdf(x, mean, cov):
    """Return the density of N(mean, cov) at x."""
    xv, scalar = _as_vector(x)
    S = _as_matrix(cov, scalar)
    k = len(xv)
    det = S[0][0] if k == 1 else rbm.det(S)
    if det <= 0.0:
        raise ValueError("covariance is not positive definite")
    m2 = mahalanobis2(xv, mean if not scalar else [mean], S)
    return math.exp(-0.5 * m2) / math.sqrt((_TWO_PI ** k) * det)


def low_variance_resample(rng, weights):
    """Return len(weights) indices drawn by the low variance sampler.

    This is systematic resampling (Thrun et al. 2005, Table 4.4): one
    uniform offset r in [0, 1/N), and the N points r + m / N select the
    indices through the cumulative weights. The weights need not sum to 1.
    """
    n = len(weights)
    if n == 0:
        return []
    total = float(sum(weights))
    if total <= 0.0 or any(w < 0.0 for w in weights):
        raise ValueError("weights must be nonnegative with a positive sum")
    r = rng.random() / n
    c = weights[0] / total
    i = 0
    out = []
    for m in range(n):
        u = r + m / n
        while u > c and i < n - 1:
            i += 1
            c += weights[i] / total
        out.append(i)
    return out


def logodds(p):
    """Return log(p / (1 - p)) for p in (0, 1)."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    return math.log(p / (1.0 - p))


def prob_from_logodds(l):
    """Return p = 1 - 1 / (1 + exp(l)), the inverse of logodds, without overflow."""
    if l >= 0.0:
        return 1.0 / (1.0 + math.exp(-l))
    e = math.exp(l)
    return e / (1.0 + e)
test_octree_occupancy_map.py 219 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/octree-occupancy-map/. The authors are listed in prov/34SSST.jsonl.

import itertools
import random

import pytest

import robest
from octree_occupancy_map import OctreeOccupancyMap


def clamp(v, lo, hi):
    return min(hi, max(lo, v))


def block_max(model, key, side):
    """The value of the block of the given side that holds key: max over its known voxels."""
    low = [k - k % side for k in key]
    vals = [model[v] for v in itertools.product(*(range(c, c + side) for c in low)) if v in model]
    return max(vals) if vals else None


def canonical_nodes(model, low, side):
    """The number of nodes of the fully pruned octree of the block, from the dense model."""
    keys = list(itertools.product(*(range(c, c + side) for c in low)))
    known = [model[k] for k in keys if k in model]
    if not known:
        return 0
    if len(known) == len(keys) and all(v == known[0] for v in known):
        return 1
    h = side // 2
    return 1 + sum(
        canonical_nodes(model, (low[0] + dx, low[1] + dy, low[2] + dz), h)
        for dx in (0, h) for dy in (0, h) for dz in (0, h)
    )


def open_box_meets_segment(t, key, a, b):
    """Brute force: does the open cube of voxel key meet the segment ab?"""
    lo, hi = 0.0, 1.0
    for ax in range(3):
        c0 = t.origin[ax] + key[ax] * t.res
        c1 = c0 + t.res
        p, d = a[ax], b[ax] - a[ax]
        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 brute_voxels(t, a, b):
    ka, kb = t.key_of(a), t.key_of(b)
    rng = [range(min(ka[ax], kb[ax]), max(ka[ax], kb[ax]) + 1) for ax in range(3)]
    return {k for k in itertools.product(*rng) if open_box_meets_segment(t, k, a, b)}


def test_keys():
    t = OctreeOccupancyMap(3, res=0.5, origin=(-1.0, 0.0, 2.0))
    assert t.size == 8
    assert t.key((-1.0, 0.0, 2.0)) == (0, 0, 0)
    assert t.key((-0.51, 0.49, 2.5)) == (0, 0, 1)
    assert t.key((2.99, 3.99, 5.99)) == (7, 7, 7)
    assert t.key((3.0, 1.0, 3.0)) is None
    assert t.key_of((-1.2, 0.0, 2.0)) == (-1, 0, 0)


def test_paper_values():
    assert robest.logodds(0.7) == pytest.approx(0.85, abs=3e-3)
    assert robest.logodds(0.4) == pytest.approx(-0.4, abs=6e-3)
    assert robest.logodds(0.12) == pytest.approx(-2.0, abs=1e-2)
    assert robest.logodds(0.97) == pytest.approx(3.5, abs=3e-2)
    t = OctreeOccupancyMap(2)
    for n in range(1, 6):
        t.update((0, 0, 0), t.l_occ)
        t.update((3, 3, 3), t.l_free)
        if n == 4:
            assert t.search((0, 0, 0)) < t.l_max and t.search((3, 3, 3)) > t.l_min
    assert t.search((0, 0, 0)) == 3.5  # five agreeing hits reach the bound
    assert t.search((3, 3, 3)) == -2.0
    assert t.search((1, 1, 1)) is None


def test_empty_map():
    t = OctreeOccupancyMap(3)
    t.check_invariant()
    assert t.num_nodes() == 1
    assert t.search((1, 2, 3)) is None and t.search((1, 2, 3), 0) is None
    assert t.probability((1, 2, 3)) is None


def test_pruning_and_expansion():
    t = OctreeOccupancyMap(2)
    for _ in range(5):
        for k in itertools.product(range(4), repeat=3):
            t.update(k, t.l_free)
    t.check_invariant()
    assert t.num_nodes() == 1
    assert t.leaves() == [((0, 0, 0), 4, -2.0)]
    t.update((1, 2, 3), t.l_occ)
    t.check_invariant()
    assert t.num_nodes() == 17
    assert t.search((1, 2, 3)) == pytest.approx(-1.15, abs=1e-12)
    assert t.search((0, 0, 0)) == -2.0
    assert t.search((1, 2, 3), 1) == t.search((1, 2, 3))
    assert t.search((3, 0, 0), 1) == -2.0
    assert t.search((3, 3, 3), 0) == t.search((1, 2, 3))
    for _ in range(3):
        t.update((1, 2, 3), t.l_free)
    t.check_invariant()
    assert t.num_nodes() == 1


def test_partial_block_is_not_pruned():
    t = OctreeOccupancyMap(1)
    keys = list(itertools.product(range(2), repeat=3))
    for k in keys[:7]:
        for _ in range(5):
            t.update(k, t.l_occ)
    t.check_invariant()
    assert t.num_nodes() == 8
    assert t.search(keys[7]) is None
    assert t.search(keys[7], 0) == 3.5
    for _ in range(5):
        t.update(keys[7], t.l_occ)
    assert t.num_nodes() == 1


def test_random_operations_against_a_dense_model():
    rng = random.Random(31)
    for clamped in (True, False):
        t = OctreeOccupancyMap(3) if clamped else OctreeOccupancyMap(3, l_min=None, l_max=None)
        model = {}
        pruned_seen = False
        for step in range(1500):
            hot = rng.random() < 0.6
            if hot:  # a block of 2 x 2 x 2 voxels that gets mostly free updates, so that it is pruned
                key = (4 + rng.randrange(2), rng.randrange(2), 2 + rng.randrange(2))
            else:
                key = tuple(rng.randrange(8) for _ in range(3))
            if rng.random() < 0.65:
                if hot:
                    v = t.l_free if rng.random() < 0.9 else t.l_occ
                else:
                    v = rng.choice([t.l_occ, t.l_free, rng.uniform(-1.0, 1.0)])
                t.update(key, v)
                model[key] = clamp(model.get(key, 0.0) + v, t.l_min, t.l_max)
            d = rng.randrange(4)
            assert t.search(key, d) == block_max(model, key, 1 << (3 - d))
            if step % 50 == 0:
                t.check_invariant()
                want = max(1, canonical_nodes(model, (0, 0, 0), 8))
                assert t.num_nodes() == want
                pruned_seen = pruned_seen or any(side > 1 for _, side, _ in t.leaves())
        t.check_invariant()
        for k in itertools.product(range(8), repeat=3):
            assert t.search(k) == model.get(k)
        if clamped:
            assert pruned_seen


def test_voxels_on_segment_against_brute_force():
    rng = random.Random(7)
    t = OctreeOccupancyMap(3, res=0.3, origin=(-0.4, 0.2, -1.0))
    for _ in range(200):
        a = tuple(rng.uniform(-1.0, 1.5) for _ in range(3))
        b = tuple(rng.uniform(-1.0, 1.5) for _ in range(3))
        cells = t.voxels_on_segment(a, b)
        assert cells[0] == t.key_of(a) and cells[-1] == t.key_of(b)
        for p, q in zip(cells, cells[1:]):
            assert sum(abs(x - y) for x, y in zip(p, q)) == 1
        assert len(set(cells)) == len(cells)
        assert set(cells) == brute_voxels(t, a, b)


def test_insert_scan_updates_each_voxel_once_and_occupied_wins():
    t = OctreeOccupancyMap(4, res=0.1)
    s = (0.05, 0.05, 0.05)
    t.insert_scan(s, [(0.55, 0.05, 0.05), (0.35, 0.05, 0.05)])
    t.check_invariant()
    got = [t.search((i, 0, 0)) for i in range(7)]
    assert got == [-0.4, -0.4, -0.4, 0.85, -0.4, 0.85, None]
    assert t.search((0, 1, 0)) is None


def test_insert_scan_against_a_dense_model():
    rng = random.Random(13)
    t = OctreeOccupancyMap(4, res=0.25, origin=(-0.5, -0.5, -0.5))
    model = {}
    for _ in range(10):
        s = tuple(rng.uniform(0.0, 3.0) for _ in range(3))
        pts = [tuple(c + rng.uniform(-1.0, 1.0) for c in s) for _ in range(20)]
        free, occ = set(), set()
        for z in pts:
            end = t.key_of(z)
            occ.add(end)
            free |= brute_voxels(t, s, z) - {end}
        t.insert_scan(s, pts)
        for k in free - occ:
            if t.inside(k):
                model[k] = clamp(model.get(k, 0.0) + t.l_free, t.l_min, t.l_max)
        for k in occ:
            if t.inside(k):
                model[k] = clamp(model.get(k, 0.0) + t.l_occ, t.l_min, t.l_max)
        t.check_invariant()
    for k in itertools.product(range(16), repeat=3):
        assert t.search(k) == model.get(k)


def test_invalid_arguments():
    with pytest.raises(ValueError):
        OctreeOccupancyMap(0)
    with pytest.raises(ValueError):
        OctreeOccupancyMap(2, l_min=0.5)
    with pytest.raises(ValueError):
        OctreeOccupancyMap(2).update((4, 0, 0), 0.85)

History

Octrees as a hierarchical subdivision of 3D space go back to the early 1980s (Hornung et al. cite Meagher, 1982), and probabilistic occupancy grids to Moravec and Elfes (1985). Hornung, Wurm, Bennewitz, Stachniss and Burgard (2013) combined the two in the OctoMap framework, after an earlier workshop version in 2010. Their paper credits the clamping update to Yguel et al. (2007), the choice between the mean and the maximum of the children to Kraetzschmar et al. (2004), and the threshold compression to Fairfield et al. (2007). The key step of their design is that clamping makes many neighboring voxels exactly equal, so lossless pruning becomes effective on probabilistic maps.

References

  1. Armin Hornung, Kai M. Wurm, Maren Bennewitz, Cyrill Stachniss and Wolfram Burgard, OctoMap: an efficient probabilistic 3D mapping framework based on octrees, Autonomous Robots 34(3), 2013, pages 189 to 206, Section 3.1 to 3.4 (octrees, the log odds update, the clamping update of Eq. 4, the mean and maximum of the children in Eq. 5 and 6, pruning of stable nodes), Section 4.1 and 4.2 (node memory and the depth limit of 16), Section 5.1 (sensor model values and the update of each voxel at most once per scan)
  2. Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 9, Section 9.2 (occupancy grid mapping in log odds form)
  3. John Amanatides and Andrew Woo, A fast voxel traversal algorithm for ray tracing, Eurographics 1987, the traversal of the voxels that a ray crosses

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.insert_scan
  • a full proof of time.search
  • a full proof of time.update
  • a full proof of time.voxels_on_segment
  • 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/34SSST/text.yaml