Algorithm Search⌘K

Data structureadvanced

Hashed oct-tree

Also called Warren-Salmon tree.

An octree whose cells sit in a hash table keyed by Morton codes, so a parallel tree code can find any cell and share cells across processors.

Implements
Spatial index
Time
O(N log N + N L) buildO(L) expected find_leafO(1) expected lookupO(1) parent
Space
O(N L) total
Where
B = the leaf capacity; L = the depth of the keys; N = the number of bodies
Origin
Michael S. Warren, John K. Salmon, 1993

A hashed oct-tree is an octree without pointers. Each cell is named by an integer key, built from the bits of its integer coordinates in the Z-order, with a leading 1 bit that marks its level. A hash table maps each key to the data of the cell. The parent and the children of a cell are found by shifting its key, and any cell is found by one table lookup, from its key alone. Warren and Salmon designed it for parallel tree codes: a processor can ask for a cell of another processor by its key, the bodies are divided among processors along the key order, and each processor stores only the cells it needs. It is close to a linear quadtree, which stores the leaf keys in sorted order; the hashed oct-tree stores all cells and uses hashing instead of search.

In plain words

An ordinary tree keeps, for each box, links to its smaller boxes. Here each box gets a number instead. The number of the big box is one. To get the number of a smaller box, write the number of its parent and add one digit from zero to seven that says which of the eight parts it is.

So from the number of a box you can find its parent and its children by simple steps, without any links. All boxes are kept in a table that finds a box from its number very fast. This is useful when many computers share one tree: a computer can ask another one for a box just by sending its number. Sorting bodies by the number of their smallest box also puts nearby bodies next to each other.

The abstract type

A hashed oct-tree stores a set of NN points in a cube and supports:

  • lookup(key): the cell with this key, or a report that it does not exist.
  • parent(key) and children(key): the keys of the neighbors in the tree.
  • bounds(key): the cube of a key.
  • find-leaf(p): the deepest stored cell whose cube holds the point pp.
  • build(points): the tree in which a cell is split while it holds more than BB points and is above level LL.

In a tree code each cell also stores the mass, the center of mass and the higher moments of its bodies, as for the Barnes-Hut algorithm.

Representation

Fix the root cube of side SS and a depth LL (at most 21 in 3D, so that keys fit in 64 bits). A cell at level ll has integer coordinates 0≤i,j,k<2l0 \le i, j, k < 2^l. Its key is the bit 1 followed by ll octal digits; the digit of level bb is 4kb+2jb+ib4 k_b + 2 j_b + i_b, from the highest bits of the coordinates to the lowest. So:

  • the root has the key 11;
  • the children of the key KK are 8K+c8K + c for c=0,…,7c = 0, \ldots, 7, and the parent is ⌊K/8⌋\lfloor K / 8 \rfloor;
  • the level of KK is (⌊log⁡2K⌋)/3(\lfloor \log_2 K \rfloor) / 3;
  • the keys of one level, in increasing order, follow the Z-order curve.

The leading 1 bit makes keys of different levels different: without it, the root and its child 0 would both have the key 0. The bodies are sorted by their keys at level LL, and each stored cell holds the range of the sorted bodies that lie in it, or its moments.

Operations

  1. KEY(p) ▷ key of the level-L cell that holds p
  2. 1(i, j, k) ← ⌊2^L (p - lo) / S⌋, coordinate by coordinate
  3. 2K ← 1
  4. 3for b ← L - 1 downto 0 do K ← 8K + 4 k_b + 2 j_b + i_b
  5. 4return K
  6. BUILD(points)
  7. 5sort the points by KEY
  8. 6push (1, all points) on a stack
  9. while the stack is not empty do pop (K, R)
  10. 7T[K] ← R ▷ T is the hash table
  11. 8if |R| > B and level(K) < L then
  12. split R into runs by the next octal digit of the keys; push (8K + c, run c) for each run
  13. LOOKUP(K)
  14. 9return T[K]
  15. PARENT(K)
  16. 10return K >> 3

Line L5 is what makes the split of line L8 easy: in the sorted order, the bodies of each cell are one run of consecutive positions. Find-leaf computes the level-LL key of the point and tests its prefixes K≫3(L−l)K \gg 3(L - l) for l=1,2,…l = 1, 2, \ldots until one is missing from the table. A binary search over ll also works, because the stored prefixes of a point form an initial segment of the levels.

Example

Take the unit cube, L=3L = 3, B=1B = 1 and four bodies.

body position level-3 coordinates key (octal)
B (0.1, 0.1, 0.1) (0, 0, 0) 1000
A (0.6, 0.3, 0.8) (4, 2, 6) 1560
D (0.65, 0.35, 0.85) (5, 2, 6) 1561
C (0.9, 0.9, 0.9) (7, 7, 7) 1777

For A, the coordinates in binary are i=100i = 100, j=010j = 010, k=110k = 110, so the digits are 4⋅1+2⋅0+1=54 \cdot 1 + 2 \cdot 0 + 1 = 5, then 4⋅1+2⋅1+0=64 \cdot 1 + 2 \cdot 1 + 0 = 6, then 00. Sorted by key, the order is B, A, D, C. The root (key 1) holds four bodies and splits into the cells 10 (B), 15 (A, D) and 17 (C). Cell 15 holds two bodies and splits; both are in its child 156, which splits again into 1560 (A) and 1561 (D). The table holds the seven keys 1, 10, 15, 17, 156, 1560 and 1561 (octal). The parent of 1561 is 156, its level is 3, and the lookup of 157 reports that the cell does not exist.

Correctness

Each key names one cell, because the bit length gives the level and the remaining bits give the coordinates (Lemma 1 of the proof file). Removing the last octal digit gives the key of the parent, because it removes the last bit of each coordinate (Lemma 2). So the key of the level-ll cell that holds a point is a prefix of the point's level-LL key (Lemma 3), and in the sorted order the bodies of each cell are consecutive (Lemma 4). The build keeps the invariant that each stack entry holds exactly the bodies of its cube; splitting by the next digit gives the runs of the children. So the table holds the cells of the octree with leaf capacity BB, each with its bodies.

Proof: Keys name cells one to one, and each stored cell holds exactly the bodies of its cubefull

Fix the depth LL and the root cube R=lo+[0,S)3R = \mathbf{lo} + [0, S)^3. A cell at level ll, 0≤l≤L0 \le l \le L, is the cube lo+S2−l([i,i+1)×[j,j+1)×[k,k+1))\mathbf{lo} + S 2^{-l} \left([i, i+1) \times [j, j+1) \times [k, k+1)\right) with integers 0≤i,j,k<2l0 \le i, j, k < 2^l. Write i=(il−1…i0)2i = (i_{l-1} \ldots i_0)_2 and the same for jj and kk. The key of the cell is the integer with binary digits 1 kl−1jl−1il−1 … k0j0i01\, k_{l-1} j_{l-1} i_{l-1}\, \ldots\, k_0 j_0 i_0, as in lines L2 to L4.

Lemma 1 (keys are one to one). The map from (l,i,j,k)(l, i, j, k) to the key is one to one, and its inverse is computed from the key alone.

Proof. The key has 3l+13l + 1 bits, with a leading 11, so l=(bit length−1)/3l = (\text{bit length} - 1)/3. The remaining 3l3l bits are the digits kbjbibk_b j_b i_b in a fixed order, so they give ii, jj and kk. □\square

Lemma 2 (parent and children). The parent of the cell (l,i,j,k)(l, i, j, k), the cell of level l−1l - 1 whose cube contains it, has the key key≫3\text{key} \gg 3. The eight children have the keys 8 key+c8\,\text{key} + c, c=0,…,7c = 0, \ldots, 7.

Proof. The parent cube has the coordinates (⌊i/2⌋,⌊j/2⌋,⌊k/2⌋)(\lfloor i/2 \rfloor, \lfloor j/2 \rfloor, \lfloor k/2 \rfloor), whose binary digits are those of ii, jj, kk without the last one. Removing the last digit of each removes the last three bits of the key. The children are the cells whose parent is the given cell, and by Lemma 1 and the first part these are the keys 8 key+c8\,\text{key} + c. □\square

Lemma 3 (prefixes). Let p∈R\mathbf{p} \in R and let KK be its key at level LL (line L1 and lines L2 to L4). For each l≤Ll \le L, the key of the cell of level ll whose cube contains p\mathbf{p} is K≫3(L−l)K \gg 3(L - l).

Proof. Line L1 sets qd=⌊2L(pd−lod)/S⌋q_d = \lfloor 2^L (p_d - lo_d) / S \rfloor. The cell of level ll that contains p\mathbf{p} has coordinates ⌊qd/2L−l⌋\lfloor q_d / 2^{L-l} \rfloor, the integers qdq_d without their last L−lL - l digits. Applying Lemma 2 L−lL - l times gives the claim. □\square

Lemma 4 (cells are intervals). After line L5 the keys K1≤K2≤…≤KNK_1 \le K_2 \le \ldots \le K_N of the bodies are sorted. For each cell QQ of level ll, the bodies in the cube of QQ are those with Kn≫3(L−l)=key(Q)K_n \gg 3(L - l) = \text{key}(Q), and they form one contiguous range of positions.

Proof. The first statement is Lemma 3. All keys of level LL have the same bit length, so K≫3(L−l)K \gg 3(L - l) is a nondecreasing function of KK, and the set of positions where it equals a given value is an interval. □\square

Theorem (the table). After the build, the table holds the keys of exactly the cells that the octree with leaves of at most BB bodies (the leaf_size) has, except that splitting stops at level LL. Each key maps to the range of the sorted bodies that lie in its cube.

Proof. Invariant of the stack of line L6: each entry (key,a,b)(\text{key}, a, b) names a nonempty cell QQ, and positions aa to b−1b - 1 are the bodies of QQ. It holds for the root, which holds all bodies. Line L7 stores the entry. If line L8 splits QQ (more than BB bodies and level below LL), it groups the positions aa to b−1b - 1 by the digit c=(K≫3(L−l−1)) & 7c = (K \gg 3(L - l - 1)) \,\&\, 7. By Lemma 4 applied at level l+1l + 1, each group is contiguous, and by Lemma 3 it is the set of bodies of the child with key 8 key+c8\,\text{key} + c. So the pushed entries satisfy the invariant, and only nonempty children are pushed. A cell is stored exactly when its parent was split, which is the rule of the octree. □\square

Consequences. A lookup of a key is one hash table access (line L9). The parent and the child keys are computed with shifts (line L10), with no pointers. The deepest stored cell that contains a point is found by testing the prefixes of the point's key from the root down, one hash access each.

Cost. Line L5 sorts NN keys of 3L+13L + 1 bits; on the word RAM with 3L+13L + 1 at most the word size, this costs O(Nlog⁡N)O(N \log N) by comparison sorting, or O(NL)O(N L) by a radix sort on the octal digits. Each body lies in at most L+1L + 1 stored cells, and the scans of line L8 touch each body once per level, so the build costs O(NL)O(N L) after sorting. The table holds at most N(L+1)N (L + 1) keys. For well-spread bodies most cells have several nonempty children, and the number of keys is O(N)O(N). With a hash table that has O(1)O(1) expected time per access, a lookup costs O(1)O(1) expected time. □\square

Complexity

In the word RAM model with keys of 3L+1≤w3L + 1 \le w bits:

  • Build: sorting NN keys costs O(Nlog⁡N)O(N \log N), or O(NL)O(N L) with a radix sort by octal digits; the splits touch each body once per level, O(NL)O(N L).
  • Lookup: one hash access, O(1)O(1) expected time. Parent and children: a shift, and 8 lookups for the children.
  • Find-leaf: O(L)O(L) expected time by testing prefixes from the root, or O(log⁡L)O(\log L) lookups by binary search over the levels.
  • Space: at most N(L+1)N(L + 1) cells; O(N)O(N) for well-spread bodies.

Variants

  • Hilbert keys. Keys from the Hilbert curve keep neighboring cells closer in the order, which gives better domains for the processors; the key arithmetic is more complex.
  • Linear octree. Store only the leaf keys in a sorted array and search it by binary search (linear quadtree).
  • Bodies in key order. The bodies themselves are stored in key order, so each cell is a range of an array, and the moments of a cell are sums over a range.
  • Parallel decomposition. Split the sorted keys into PP ranges of equal work, one per processor. Each processor builds the cells of its range and asks others for the cells that the acceptance criterion needs; replies are cached in the local table.
  • Two dimensions. With 2 bits per level, the same scheme gives a hashed quadtree.

When to use it

Use a hashed oct-tree in parallel tree codes and fast multipole methods on distributed memory, where pointers can not cross processors. Use it when cells must be found from their position, for example to find the neighbors of a cell by computing their keys. On a single processor with a tree that is built once and walked from the root, a pointer octree is simpler and about as fast.

Pitfalls

  • Forgetting the leading 1 bit. Without it, keys of different levels collide.
  • Too deep a key. In 3D with 64-bit keys, L≤21L \le 21. Bodies closer than S2−21S 2^{-21} get the same key and must share a leaf.
  • Points on the far face. A point with p=lo+Sp = lo + S gives the coordinate 2L2^L, which is out of range. Clamp it, or make the root cube slightly larger.
  • Bad hash functions. Keys of one region share their high bits. A hash that uses only the high bits, or a table size that is a power of 2 with the low bits of a key, can cluster; mix the bits.
  • Z-order is not distance. Most bodies with close keys are near each other, but two near bodies can have keys far apart when a boundary of a large cell lies between them.

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.

hashed_oct_tree.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hashed-oct-tree/. The authors are listed in prov/4795RQ.jsonl.
"""Hashed oct-tree: an octree whose cells live in a hash table keyed by Morton keys.

A cell at level l (the root is level 0) with integer coordinates (i, j, k),
0 <= i, j, k < 2^l, has the key 1 followed by the l octal digits of the
interleaved bits of (i, j, k). So the root key is 1, the children of key k are
8k + c for c = 0..7, the parent is k >> 3, and the level is
(bit_length(k) - 1) / 3. Bodies get keys at the deepest level L, the bodies
are sorted by key, and each cell owns a contiguous range of the sorted bodies.
The table maps a key to its cell (a Python dict is the hash table).
"""

from typing import Sequence

Vec = Sequence[float]


def interleave(i: int, j: int, k: int, level: int) -> int:
    """Key of the cell (i, j, k) at the given level, with the leading 1 bit."""
    key = 1  # @line L2
    for b in range(level - 1, -1, -1):  # @line L3
        key = (key << 3) | (((k >> b) & 1) << 2) | (((j >> b) & 1) << 1) | ((i >> b) & 1)
    return key  # @line L4


def deinterleave(key: int) -> tuple[int, int, int, int]:
    """Inverse of interleave: return (level, i, j, k)."""
    level = (key.bit_length() - 1) // 3
    i = j = k = 0
    for b in range(level):
        digit = (key >> (3 * b)) & 7
        i |= (digit & 1) << b
        j |= ((digit >> 1) & 1) << b
        k |= ((digit >> 2) & 1) << b
    return level, i, j, k


def parent(key: int) -> int:
    return key >> 3  # @line L10


def child(key: int, c: int) -> int:
    return (key << 3) | c


def level_of(key: int) -> int:
    return (key.bit_length() - 1) // 3


class HashedOctTree:
    def __init__(self, x: Sequence[Vec], leaf_size: int = 1, depth: int = 21) -> None:
        if not x:
            raise ValueError("no bodies")
        self.depth = depth
        self.leaf_size = leaf_size
        self.lo = [min(p[d] for p in x) for d in range(3)]
        side = max(max(p[d] for p in x) - self.lo[d] for d in range(3)) or 1.0
        self.side = side * (1 + 1e-9)
        keys = [self.body_key(p) for p in x]
        self.order = sorted(range(len(x)), key=lambda n: keys[n])  # @line L5
        self.keys = [keys[n] for n in self.order]
        self.table: dict[int, tuple[int, int]] = {}  # key -> (start, end) in self.order
        stack = [(1, 0, len(x))]  # @line L6
        while stack:
            key, start, end = stack.pop()
            self.table[key] = (start, end)  # @line L7
            lev = level_of(key)
            if end - start > leaf_size and lev < depth:  # @line L8
                shift = 3 * (depth - lev - 1)
                s = start
                while s < end:
                    c = (self.keys[s] >> shift) & 7
                    e = s
                    while e < end and (self.keys[e] >> shift) & 7 == c:
                        e += 1
                    stack.append((child(key, c), s, e))
                    s = e

    def body_key(self, p: Vec) -> int:
        n = 1 << self.depth
        q = [min(n - 1, int((p[d] - self.lo[d]) / self.side * n)) for d in range(3)]  # @line L1
        return interleave(q[0], q[1], q[2], self.depth)

    def lookup(self, key: int) -> list[int]:
        """Indices of the bodies in the cell with this key; KeyError if the cell does not exist."""
        start, end = self.table[key]  # @line L9
        return self.order[start:end]

    def children(self, key: int) -> list[int]:
        return [child(key, c) for c in range(8) if child(key, c) in self.table]

    def is_leaf(self, key: int) -> bool:
        return not self.children(key)

    def bounds(self, key: int) -> tuple[list[float], float]:
        """Lower corner and side of the cube of a key."""
        lev, i, j, k = deinterleave(key)
        s = self.side / (1 << lev)
        return [self.lo[0] + i * s, self.lo[1] + j * s, self.lo[2] + k * s], s

    def leaf_of(self, p: Vec) -> int:
        """Key of the deepest cell of the tree whose cube holds the point p."""
        bk = self.body_key(p)
        key = 1
        for lev in range(1, self.depth + 1):
            nxt = bk >> (3 * (self.depth - lev))
            if nxt not in self.table:
                break
            key = nxt
        return key
test_hashed_oct_tree.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hashed-oct-tree/. The authors are listed in prov/4795RQ.jsonl.
import random

import pytest

from hashed_oct_tree import HashedOctTree, child, deinterleave, interleave, level_of, parent


def points(n, seed, clustered=False):
    rng = random.Random(seed)
    if not clustered:
        return [tuple(rng.random() for _ in range(3)) for _ in range(n)]
    out = []
    for _ in range(n):
        c = rng.choice([(0.2, 0.2, 0.2), (0.7, 0.6, 0.8)])
        out.append(tuple(c[d] + rng.gauss(0, 0.02) for d in range(3)))
    return out


def inside(p, lo, s):
    return all(lo[d] <= p[d] < lo[d] + s for d in range(3))


def test_small_keys():
    assert interleave(0, 0, 0, 0) == 1
    assert [interleave(i, j, k, 1) for k in (0, 1) for j in (0, 1) for i in (0, 1)] == list(range(8, 16))
    assert interleave(1, 0, 0, 2) == 0o101  # 1, then digit 0 at level 1, digit 1 at level 2
    assert interleave(3, 3, 3, 2) == 0o177
    assert parent(0o177) == 0o17 and parent(0o17) == 1
    assert child(1, 5) == 13 and level_of(13) == 1


def test_key_round_trip():
    rng = random.Random(3)
    for _ in range(500):
        lev = rng.randint(0, 21)
        i, j, k = (rng.randrange(1 << lev) for _ in range(3))
        key = interleave(i, j, k, lev)
        assert deinterleave(key) == (lev, i, j, k)
        assert level_of(key) == lev
        if lev:
            assert deinterleave(parent(key)) == (lev - 1, i >> 1, j >> 1, k >> 1)


@pytest.mark.parametrize("clustered", [False, True])
@pytest.mark.parametrize("leaf_size", [1, 4])
def test_cells_match_brute_force(clustered, leaf_size):
    x = points(300, 11, clustered)
    t = HashedOctTree(x, leaf_size=leaf_size)
    for key in t.table:
        lo, s = t.bounds(key)
        want = sorted(n for n, p in enumerate(x) if inside(p, lo, s))
        assert sorted(t.lookup(key)) == want
        if key != 1:
            assert parent(key) in t.table
        kids = t.children(key)
        if kids:
            assert len(want) > leaf_size
            assert sorted(n for c in kids for n in t.lookup(c)) == want
        else:
            assert len(want) <= leaf_size


def test_leaf_of_and_missing_keys():
    x = points(200, 5)
    t = HashedOctTree(x, leaf_size=2)
    for n, p in enumerate(x):
        leaf = t.leaf_of(p)
        assert t.is_leaf(leaf)
        assert n in t.lookup(leaf)
    missing = next(child(k, c) for k in t.table for c in range(8)
                   if child(k, c) not in t.table and not t.is_leaf(k))
    with pytest.raises(KeyError):
        t.lookup(missing)


def test_sorted_order_is_z_order():
    x = points(100, 8)
    t = HashedOctTree(x)
    assert t.keys == sorted(t.keys)
    for key, (start, end) in t.table.items():
        assert end > start  # no empty cell is stored


def test_coincident_points_stop_at_depth():
    x = [(0.5, 0.5, 0.5)] * 3 + [(0.1, 0.9, 0.3)]
    t = HashedOctTree(x, leaf_size=1, depth=6)
    deep = [k for k in t.table if level_of(k) == 6]
    assert len(deep) == 1 and len(t.lookup(deep[0])) == 3

History

Morton described the interleaving of bits for a geographic database in 1966, and the linear quadtrees of the 1980s used such locational codes for image data. Warren and Salmon (1993) added the leading bit, put all cells in a hash table and used the key order to divide the bodies among the processors of a parallel computer. Their codes ran cosmological simulations with millions of bodies on parallel machines of the early 1990s.

References

  1. Michael S. Warren and John K. Salmon, A parallel hashed oct-tree N-body algorithm, Proceedings of Supercomputing 1993, 12-21, the keys of cells, the hash table from keys to cells and the parallel decomposition
  2. John K. Salmon and Michael S. Warren, Skeletons from the treecode closet, Journal of Computational Physics 111(1), 1994, 136-155, the error-bound acceptance criteria used with the tree
  3. Hanan Samet, Foundations of Multidimensional and Metric Data Structures, Morgan Kaufmann, 2006, Chapter 1, Multidimensional Point Data (linear quadtrees and locational codes)

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.build
  • a full proof of time.find_leaf
  • a full proof of time.lookup
  • a full proof of time.parent
  • 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/4795RQ/text.yaml