Algorithmcore
Barnes-Hut algorithm
Also called Barnes-Hut tree code, Barnes-Hut simulation.
Builds an octree of the particles and treats each far cell as one pseudo-particle at its center of mass; a force step costs O(N log N) for non-pathological distributions.
- Time
- Θ(N^2) worstΘ(N log N) average · best
- Space
- Θ(N) extra
- Where
- N = the number of particles
- Model
- Real RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Josh Barnes, Piet Hut, 1986
The Barnes-Hut algorithm computes approximate gravitational forces on bodies with a tree. It puts the bodies in an octree (a quadtree in 2D), stores in each cell the total mass and the center of mass, and for each body walks the tree from the root. A cell that is small compared with its distance, by the multipole acceptance criterion, acts as one body at its center of mass; a cell that is too close is opened, and its children are tested. For well-spread distributions and a fixed , each walk visits cells, so a force step costs instead of the of direct summation. The opening angle sets the trade between speed and accuracy: gives direct summation, and to gives force errors of about one percent. It is the base of most collisionless tree codes for galaxies and cosmology.
In plain words
To find the pull of a distant group of stars, you do not need each star. The group pulls almost like one heavy star at its center. A group that is close needs more detail.
So put all bodies in a box, and cut the box into eight smaller boxes, and cut again, until each box holds at most one body. Each box remembers its total weight and its center. To find the pull on one body, start with the biggest box. If a box looks small from where the body is, use it as one heavy star. If it looks big, look inside it at its smaller boxes. Far away, big boxes are enough, so each body needs far fewer steps than one for each other body.
The problem
The input is masses , positions , ( in code units), a softening parameter and an opening angle . The output is an approximation of each acceleration
with the error measured against direct summation as . The error is controlled by , not bounded by a given tolerance.
The algorithm
BARNES-HUT(m, x, theta, epsilon, G)- 1
root ← the smallest cube that holds all bodies - 2
for i ← 1 to N do INSERT(root, i) INSERT(C, i):- 3
if C is a leaf with no body then store i in C; return - 4
if C is a leaf with body k then split C into 8 children; move k to its child - 5
INSERT(the child of C whose cube holds x_i, i) - 6
for each cell C, children first do M_C ← total mass; z_C ← center of mass for i ← 1 to N do a_i ← 0; WALK(root):- 7
if C is a leaf then add the pair force of each body j ≠ i in C to a_i - 8
else if s_C / |z_C - x_i| < theta and x_i is not in C then add G M_C (z_C - x_i) / (|z_C - x_i|² + epsilon²)^{3/2} to a_i- 9
else WALK each child of C - 10
return a
Lines L1 to L5 build the tree by insertion. A leaf holds one body; when a second body arrives, line L4 splits the leaf and moves the first body down, so the tree is as deep as needed to separate the bodies. Line L6 fills in the monopole of each cell from its children in one pass from the leaves up. Lines L7 to L9 are the walk for one target. The test " is not in " of line L8 stops a cell from acting on a body inside it, which the bare test allows for . The code stops splitting at a fixed depth, so bodies at the same point share one leaf.
Example
Take bodies with masses uniform in and positions uniform in the cube (seed 1), and . Direct summation uses pair interactions (each ordered pair once). The walk of this implementation gives:
| interactions | median relative force error | largest relative force error | |
|---|---|---|---|
| 1.0 | 10417 | 1.31 | |
| 0.7 | 20143 | 0.17 | |
| 0.5 | 34319 | 0.038 | |
| 0.3 | 61433 | 0.018 | |
| 0 | 89700 |
These are measurements. The median error falls by a factor of about 40 from to , faster than , which is the size of the quadrupole term of the multipole expansion relative to the monopole. The largest error is much larger than the median: a few bodies have a small total force, and a large relative error. At the result agrees with direct summation up to rounding.
Correctness
By Lemma 1 of the proof file, the tree puts each body in exactly one leaf, and the cells below any cell partition its bodies. The walk replaces a cell either by its monopole, by its bodies (at a leaf) or by its children, so each body other than contributes exactly once, either directly or through the monopole of exactly one accepted cell (Lemma 3). With no cell is accepted, and the result is the direct sum (Theorem 1). For an accepted cell with all bodies within of the center of mass, the error of the monopole potential is at most , because the dipole term about the center of mass is zero (Theorem 2). In 3D, , so for the relative error of each accepted cell is below . For larger no bound in terms of holds, which is why codes add refinements to the criterion.
Proof: The Barnes-Hut walk counts each body once, is exact for theta = 0, and has a bounded monopole error for small thetafull
We use exact real arithmetic. The bodies have masses and positions . A cell is a closed cube of side ; is the set of bodies stored in the leaves below , and .
Lemma 1 (the tree is a partition). After lines L1 to L5, each body is stored in exactly one leaf, and the leaf cube contains the body. For each internal cell , the sets of its children are disjoint and their union is .
Proof. Line L1 makes a cube that holds all bodies. An insertion at a cell either stores the body in a leaf at line L3, or passes it to exactly one child at line L5, chosen by comparing each coordinate with the middle of the cell, so the child cube contains the body. Line L4 moves the old bodies of a leaf to children by the same rule, and removes them from the leaf. So at each moment, each inserted body is in exactly one leaf, and on the path from the root to that leaf each cell contains it. The second statement follows, because the children of a cell are the only cells below it on these paths.
The depth limit of line L3 makes each insertion stop: a path has at most cells. Bodies at the same point end in one leaf at the depth limit.
Lemma 2 (the summaries). After line L6, each cell has the mass and the center of mass of .
Proof. By induction from the leaves up. A leaf sums its own bodies. An internal cell sums the masses of its children and takes the mass-weighted mean of their centers; by Lemma 1 and the induction hypothesis this is , and similarly for the first moment.
Lemma 3 (each body is counted once). For a target , let be the set of cells accepted at line L8 and the set of leaves reached at line L7. The sets for are pairwise disjoint, and their union is the set of all bodies.
Proof. The walk starts with the root. Each cell taken from the stack is either a leaf (line L7), accepted (line L8), or replaced by its children (line L9). By Lemma 1, replacing by its children keeps the sets of the stack and of the finished cells a partition of all bodies. The walk ends because the tree is finite, and then all cells are finished.
Theorem 1 (exactness for theta = 0). With the walk returns the direct sum .
Proof. The test is false for , so no cell is accepted, is empty, and by Lemma 3 every body is reached in exactly one leaf. Line L7 adds the pair term of each body of the leaf.
Theorem 2 (monopole error of an accepted cell). Let be a cell, a point, and , with . Then, for ,
Proof. Put the origin at and let , so . The Legendre series converges absolutely. The term summed over is . The term is , because is the center of mass. With and , the rest is at most .
Corollary (a bound in terms of theta). In dimension 3, the bodies of and their center of mass lie in the cube of , so . If line L8 accepts , then , so . If , the relative error of the potential of the cell is less than ; for this is , a loose worst case, and the error of a typical cell is much smaller. For there is no such bound in terms of alone: the bodies of the cell can be arbitrarily close to the target. The test "the target is not inside " of line L8 removes the worst of these cases but does not give a bound.
Cost of the walk. Each cell is taken from the stack at most once per target, so one walk costs at most the number of cells times . For bodies that are not all at one point, the depth limit bounds the number of cells by . The cost for well-spread distributions is an estimate, discussed on the main page.
Complexity
The model is the real RAM, with bodies in 3D.
- Tree build. Each insertion walks down one path, so the build costs . For bodies with a bounded ratio of the largest to the smallest distance, the depth is (theorem for this case), and line L6 costs .
- Walk, uniform case (argument, not a theorem). At a level with cells of side , the cells that the target must open lie within distance about of it, and there are of them. Each opened cell has at most 8 children, so each level costs , and the walk costs . Over all targets this is for a fixed (Barnes and Hut 1986). In this implementation, with the same kind of random bodies (seed 3), the count per body grows slowly: 48, 59 and 78 interactions per body for , and at (measurement).
- Worst case. Bodies with very different scales make a deep tree: for example, bodies at for along a line give depth , and the build costs . The walk is also at most in total, since each target visits each cell at most once.
- Space. cells when the depth is , with one mass and one center of mass each.
Properties
- Not symmetric. The force of a cell on body and the force of body on the bodies of that cell come from different approximations, so momentum is not conserved exactly. The momentum error is of the order of the force error.
- Controlled by one parameter. sets the error and the cost. The error is not bounded by a tolerance given in advance, unlike in the fast multipole method.
- Adaptive. The tree follows the mass, so dense regions get deep trees, and empty regions cost nothing.
- Rebuilt each step. The original algorithm rebuilds the tree at each step, which costs like the walk.
Variants and improvements
- Quadrupole moments. Storing the traceless quadrupole of each cell removes the leading error term and allows a larger for the same accuracy.
- Other criteria. The offset criterion, the error-bound criteria of Salmon and Warren, and the relative criterion of GADGET-2; see multipole acceptance criterion.
- Group walks. Bodies of one small cell share one walk and one interaction list, which is good for vector and GPU hardware.
- Parallel trees. The hashed oct-tree stores cells in a hash table with Morton keys, and the bodies are divided among processors by a space-filling curve.
- Hybrid codes. TreePM uses the tree only for the short-range part of the force and a mesh for the long-range part.
- Fast multipole method. The FMM adds cell-to-cell interactions with local expansions and reaches for a fixed accuracy.
When to use it
Use Barnes-Hut for collisionless systems with or more bodies, where force errors of 0.1 to 1 percent are acceptable, such as galaxies, dark matter halos and the formation of structure, with softening. Use it for open boundaries and very clustered mass, where a mesh is not efficient. Use direct summation for small and for collisional systems, where every encounter matters, and the fast multipole method when a guaranteed accuracy or cost is needed.
Pitfalls
- Large opening angles. For the bare test can accept a cell that contains the target, and the force error has no bound. Add the test of line L8 or the offset criterion.
- Measuring the error at one only. The error depends on the distribution. Measure it against direct summation on a sample of bodies for the actual problem.
- Ignoring the tail of the error distribution. The median error can be small while a few bodies have large errors. Report a high percentile as well.
- Coincident bodies. Without a depth limit or a bucket of several bodies per leaf, two bodies at the same point make the insertion run forever.
- Momentum drift. The forces are not symmetric, so the total momentum drifts. This is not an error of the integrator.
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/barnes-hut-algorithm/. The authors are listed in prov/RQH8DT.jsonl.
"""Barnes-Hut tree code for gravitational accelerations.
The bodies have masses m[i] and positions x[i] in dimension 2 (quadtree) or
3 (octree); any dimension works. Each cell is a cube with 2^dim children and
stores its total mass and center of mass (the monopole). A cell of side s
whose center of mass is at distance d from the target is accepted when
s / d < theta and the target is not inside the cell; otherwise it is opened.
theta = 0 opens every cell and gives direct summation.
Pair potential: -G m_i m_j / sqrt(r^2 + eps^2) (Plummer softening); G = 1
unless given.
"""
import math
from typing import Optional, Sequence
Vec = Sequence[float]
MAX_DEPTH = 48 # bodies closer than side / 2^48 share one leaf
class Cell:
__slots__ = ("lo", "side", "bodies", "children", "mass", "com")
def __init__(self, lo: list[float], side: float) -> None:
self.lo = lo
self.side = side
self.bodies: list[int] = []
self.children: Optional[list[Optional["Cell"]]] = None
self.mass = 0.0
self.com = [0.0] * len(lo)
def contains(self, p: Vec) -> bool:
return all(self.lo[k] <= p[k] <= self.lo[k] + self.side for k in range(len(p)))
def _child_index(cell: Cell, p: Vec) -> int:
half = cell.side / 2
idx = 0
for k in range(len(p)):
if p[k] >= cell.lo[k] + half:
idx |= 1 << k
return idx
def _insert(cell: Cell, i: int, x: Sequence[Vec], depth: int) -> None:
if cell.children is None:
if not cell.bodies or depth >= MAX_DEPTH: # @line L3
cell.bodies.append(i)
return
dim = len(x[i])
cell.children = [None] * (1 << dim) # @line L4
old = cell.bodies
cell.bodies = []
for k in old:
_insert_child(cell, k, x, depth)
_insert_child(cell, i, x, depth) # @line L5
def _insert_child(cell: Cell, i: int, x: Sequence[Vec], depth: int) -> None:
c = _child_index(cell, x[i])
assert cell.children is not None
if cell.children[c] is None:
half = cell.side / 2
lo = [cell.lo[k] + (half if (c >> k) & 1 else 0.0) for k in range(len(cell.lo))]
cell.children[c] = Cell(lo, half)
_insert(cell.children[c], i, x, depth + 1)
def _summarize(cell: Cell, m: Sequence[float], x: Sequence[Vec]) -> None:
dim = len(cell.lo)
parts: list[tuple[float, Vec]] = [(m[i], x[i]) for i in cell.bodies]
if cell.children is not None:
for ch in cell.children:
if ch is not None:
_summarize(ch, m, x)
parts.append((ch.mass, ch.com))
cell.mass = sum(w for w, _ in parts) # @line L6
cell.com = [sum(w * p[k] for w, p in parts) / cell.mass for k in range(dim)]
def build_tree(m: Sequence[float], x: Sequence[Vec]) -> Cell:
"""Build the 2^dim-ary tree and fill in the mass and center of mass of every cell."""
dim = len(x[0])
lo = [min(p[k] for p in x) for k in range(dim)]
side = max(max(p[k] for p in x) - lo[k] for k in range(dim)) or 1.0
root = Cell(lo, side * (1 + 1e-12)) # @line L1
for i in range(len(m)): # @line L2
_insert(root, i, x, 0)
_summarize(root, m, x)
return root
def _pull(a: list[float], g: float, src: Vec, p: Vec, e2: float) -> None:
d = [src[k] - p[k] for k in range(len(p))]
s = sum(c * c for c in d) + e2
if s == 0.0:
raise ValueError("two bodies at the same point with eps = 0")
w = g / (s * math.sqrt(s))
for k in range(len(p)):
a[k] += w * d[k]
def tree_force(root: Cell, i: int, m: Sequence[float], x: Sequence[Vec], theta: float,
eps: float = 0.0, G: float = 1.0) -> tuple[list[float], int]:
"""Acceleration of body i from the tree, and the number of interactions used."""
p = x[i]
e2 = eps * eps
a = [0.0] * len(p)
count = 0
stack = [root]
while stack:
c = stack.pop()
if c.children is None: # @line L7
for j in c.bodies:
if j != i:
_pull(a, G * m[j], x[j], p, e2)
count += 1
continue
d = math.dist(c.com, p)
if d > 0 and c.side < theta * d and not c.contains(p): # @line L8
_pull(a, G * c.mass, c.com, p, e2)
count += 1
continue
stack.extend(ch for ch in c.children if ch is not None) # @line L9
return a, count # @line L10
def barnes_hut(m: Sequence[float], x: Sequence[Vec], theta: float = 0.5, eps: float = 0.0,
G: float = 1.0) -> tuple[list[list[float]], int]:
"""Accelerations of all bodies and the total number of interactions."""
root = build_tree(m, x)
acc, total = [], 0
for i in range(len(m)):
a, c = tree_force(root, i, m, x, theta, eps, G)
acc.append(a)
total += c
return acc, total
def leaves(cell: Cell) -> list[Cell]:
if cell.children is None:
return [cell]
out = []
for ch in cell.children:
if ch is not None:
out.extend(leaves(ch))
return out
test_barnes_hut_algorithm.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/barnes-hut-algorithm/. The authors are listed in prov/RQH8DT.jsonl.
import math
import random
import pytest
from barnes_hut_algorithm import barnes_hut, build_tree, leaves
def direct(m, x, eps=0.0, G=1.0):
"""Reference: direct summation over all other bodies."""
n, dim = len(m), len(x[0])
out = []
for i in range(n):
a = [0.0] * dim
for j in range(n):
if j != i:
d = [x[j][k] - x[i][k] for k in range(dim)]
s = sum(c * c for c in d) + eps * eps
for k in range(dim):
a[k] += G * m[j] * d[k] / s ** 1.5
out.append(a)
return out
def bodies(n, dim, seed):
rng = random.Random(seed)
m = [rng.uniform(0.5, 1.5) for _ in range(n)]
x = [tuple(rng.uniform(-1.0, 1.0) for _ in range(dim)) for _ in range(n)]
return m, x
def rel_errors(a, b):
return [math.dist(p, q) / math.hypot(*q) for p, q in zip(a, b)]
@pytest.mark.parametrize("dim", [2, 3])
def test_theta_zero_is_direct_summation(dim):
m, x = bodies(120, dim, 5)
a, count = barnes_hut(m, x, theta=0.0, eps=0.01)
assert count == 120 * 119
for e in rel_errors(a, direct(m, x, eps=0.01)):
assert e < 1e-12
def test_error_falls_with_theta():
m, x = bodies(300, 3, 1)
ref = direct(m, x)
med = []
for theta in (1.0, 0.7, 0.5, 0.3):
a, _ = barnes_hut(m, x, theta=theta)
e = sorted(rel_errors(a, ref))
med.append(e[len(e) // 2])
assert med == sorted(med, reverse=True)
assert med[2] < 1e-2 # theta = 0.5: median relative force error below 1 percent
def test_fewer_interactions_than_direct():
m, x = bodies(400, 3, 2)
_, count = barnes_hut(m, x, theta=0.7)
assert count < 400 * 399 // 2
def test_tree_invariants():
m, x = bodies(200, 3, 9)
root = build_tree(m, x)
assert root.mass == pytest.approx(sum(m), rel=1e-14)
for k in range(3):
want = sum(mi * p[k] for mi, p in zip(m, x)) / sum(m)
assert root.com[k] == pytest.approx(want, abs=1e-14)
seen = []
for leaf in leaves(root):
for i in leaf.bodies:
assert leaf.contains(x[i])
seen.extend(leaf.bodies)
assert sorted(seen) == list(range(200))
def test_monopole_error_bound_for_accepted_cells():
# For theta < 1 / sqrt(3), each accepted cell obeys the a priori bound of the proof file.
m, x = bodies(200, 3, 4)
root = build_tree(m, x)
theta = 0.4
stack, checked = [root], 0
target = (3.0, 0.2, -0.1)
while stack:
c = stack.pop()
if c.children is None:
continue
d = math.dist(c.com, target)
if c.side < theta * d and not c.contains(target):
idx = [i for leaf in leaves(c) for i in leaf.bodies]
exact = -sum(m[i] / math.dist(x[i], target) for i in idx)
mono = -c.mass / d
b = max(math.dist(x[i], c.com) for i in idx)
assert abs(exact - mono) <= c.mass * b * b / (d * d * (d - b)) + 1e-15
checked += 1
else:
stack.extend(ch for ch in c.children if ch is not None)
assert checked > 0
def test_coincident_bodies_with_softening():
m = [1.0, 1.0, 1.0]
x = [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (1.0, 0.0, 0.0)]
a, _ = barnes_hut(m, x, theta=0.5, eps=0.1)
ref = direct(m, x, eps=0.1)
for e in rel_errors(a, ref):
assert e < 1e-12
History
Barnes and Hut published the algorithm in 1986, after earlier tree methods of Appel (1985) and others. Their octree is rebuilt at each step, uses monopoles (later quadrupoles), and has the opening angle criterion. Salmon and Warren (1994) showed that the criterion can give unbounded errors and gave error bounds, and Warren and Salmon built parallel codes with a hashed oct-tree. Tree codes such as GADGET-2 (Springel 2005) carry the method to cosmological simulations with billions of bodies.
References
- Josh Barnes and Piet Hut, A hierarchical O(N log N) force-calculation algorithm, Nature 324, 1986, 446-449, the tree construction, the opening criterion and the cost estimate
- John K. Salmon and Michael S. Warren, Skeletons from the treecode closet, Journal of Computational Physics 111(1), 1994, 136-155, the error analysis of the opening criterion
- Sverre J. Aarseth, Gravitational N-Body Simulations, Tools and Algorithms, Cambridge University Press, 2003, Chapter 6 (tree codes), Section 6.2 (basic formulation)
- Volker Springel, The cosmological simulation code GADGET-2, Monthly Notices of the Royal Astronomical Society 364(4), 2005, 1105-1134, Section 3.1 (the tree algorithm and its opening criteria)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 | W2 basic |
|
Tag RQH8DT Edit this page History Report an error Markdown