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
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
- 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 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 .
- build(points): the tree in which a cell is split while it holds more than points and is above level .
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 and a depth (at most 21 in 3D, so that keys fit in 64 bits). A cell at level has integer coordinates . Its key is the bit 1 followed by octal digits; the digit of level is , from the highest bits of the coordinates to the lowest. So:
- the root has the key ;
- the children of the key are for , and the parent is ;
- the level of is ;
- 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 , and each stored cell holds the range of the sorted bodies that lie in it, or its moments.
Operations
KEY(p) ▷ key of the level-L cell that holds p- 1
(i, j, k) ← ⌊2^L (p - lo) / S⌋, coordinate by coordinate - 2
K ← 1 - 3
for b ← L - 1 downto 0 do K ← 8K + 4 k_b + 2 j_b + i_b - 4
return K BUILD(points)- 5
sort the points by KEY - 6
push (1, all points) on a stack while the stack is not empty do pop (K, R)- 7
T[K] ← R ▷ T is the hash table - 8
if |R| > B and level(K) < L then split R into runs by the next octal digit of the keys; push (8K + c, run c) for each runLOOKUP(K)- 9
return T[K] PARENT(K)- 10
return 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- key of the point and tests its prefixes for until one is missing from the table. A binary search over also works, because the stored prefixes of a point form an initial segment of the levels.
Example
Take the unit cube, , 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 , , , so the digits are , then , then . 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- cell that holds a point is a prefix of the point's level- 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 , 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 and the root cube . A cell at level , , is the cube with integers . Write and the same for and . The key of the cell is the integer with binary digits , as in lines L2 to L4.
Lemma 1 (keys are one to one). The map from to the key is one to one, and its inverse is computed from the key alone.
Proof. The key has bits, with a leading , so . The remaining bits are the digits in a fixed order, so they give , and .
Lemma 2 (parent and children). The parent of the cell , the cell of level whose cube contains it, has the key . The eight children have the keys , .
Proof. The parent cube has the coordinates , whose binary digits are those of , , 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 .
Lemma 3 (prefixes). Let and let be its key at level (line L1 and lines L2 to L4). For each , the key of the cell of level whose cube contains is .
Proof. Line L1 sets . The cell of level that contains has coordinates , the integers without their last digits. Applying Lemma 2 times gives the claim.
Lemma 4 (cells are intervals). After line L5 the keys of the bodies are sorted. For each cell of level , the bodies in the cube of are those with , and they form one contiguous range of positions.
Proof. The first statement is Lemma 3. All keys of level have the same bit length, so is a nondecreasing function of , and the set of positions where it equals a given value is an interval.
Theorem (the table). After the build, the table holds the keys of exactly the cells that the octree with leaves of at most bodies (the leaf_size) has, except that splitting stops at level . 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 names a nonempty cell , and positions to are the bodies of . It holds for the root, which holds all bodies. Line L7 stores the entry. If line L8 splits (more than bodies and level below ), it groups the positions to by the digit . By Lemma 4 applied at level , each group is contiguous, and by Lemma 3 it is the set of bodies of the child with key . 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.
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 keys of bits; on the word RAM with at most the word size, this costs by comparison sorting, or by a radix sort on the octal digits. Each body lies in at most stored cells, and the scans of line L8 touch each body once per level, so the build costs after sorting. The table holds at most keys. For well-spread bodies most cells have several nonempty children, and the number of keys is . With a hash table that has expected time per access, a lookup costs expected time.
Complexity
In the word RAM model with keys of bits:
- Build: sorting keys costs , or with a radix sort by octal digits; the splits touch each body once per level, .
- Lookup: one hash access, expected time. Parent and children: a shift, and 8 lookups for the children.
- Find-leaf: expected time by testing prefixes from the root, or lookups by binary search over the levels.
- Space: at most cells; 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 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, . Bodies closer than get the same key and must share a leaf.
- Points on the far face. A point with gives the coordinate , 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 4795RQ Edit this page History Report an error Markdown