Algorithm Search⌘K

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
Properties
deterministic
Origin
Josh Barnes, Piet Hut, 1986

The Barnes-Hut algorithm computes approximate gravitational forces on NN 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, s/d<θs / d < \theta 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 θ\theta, each walk visits O(log⁡N)O(\log N) cells, so a force step costs O(Nlog⁡N)O(N \log N) instead of the Θ(N2)\Theta(N^2) of direct summation. The opening angle θ\theta sets the trade between speed and accuracy: θ=0\theta = 0 gives direct summation, and θ≈0.5\theta \approx 0.5 to 0.70.7 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 NN masses mi>0m_i > 0, positions xi∈R3\mathbf{x}_i \in \mathbb{R}^3, GG (G=1G = 1 in code units), a softening parameter ϵ≥0\epsilon \ge 0 and an opening angle θ≥0\theta \ge 0. The output is an approximation a~i\tilde{\mathbf{a}}_i of each acceleration

ai=G∑j≠imjxj−xi(∣xj−xi∣2+ϵ2)3/2,\mathbf{a}_i = G \sum_{j \ne i} m_j \frac{\mathbf{x}_j - \mathbf{x}_i}{\left(|\mathbf{x}_j - \mathbf{x}_i|^2 + \epsilon^2\right)^{3/2}},

with the error measured against direct summation as ∣a~i−ai∣/∣ai∣|\tilde{\mathbf{a}}_i - \mathbf{a}_i| / |\mathbf{a}_i|. The error is controlled by θ\theta, not bounded by a given tolerance.

The algorithm

  1. BARNES-HUT(m, x, theta, epsilon, G)
  2. 1root ← the smallest cube that holds all bodies
  3. 2for i ← 1 to N do INSERT(root, i)
  4. INSERT(C, i):
  5. 3if C is a leaf with no body then store i in C; return
  6. 4if C is a leaf with body k then split C into 8 children; move k to its child
  7. 5INSERT(the child of C whose cube holds x_i, i)
  8. 6for each cell C, children first do M_C ← total mass; z_C ← center of mass
  9. for i ← 1 to N do a_i ← 0; WALK(root):
  10. 7if C is a leaf then add the pair force of each body j ≠ i in C to a_i
  11. 8else if s_C / |z_C - x_i| < theta and x_i is not in C then
  12. add G M_C (z_C - x_i) / (|z_C - x_i|² + epsilon²)^{3/2} to a_i
  13. 9else WALK each child of C
  14. 10return 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 "xi\mathbf{x}_i is not in CC" of line L8 stops a cell from acting on a body inside it, which the bare s/ds / d test allows for θ>1/3\theta > 1/\sqrt{3}. The code stops splitting at a fixed depth, so bodies at the same point share one leaf.

Example

Take N=300N = 300 bodies with masses uniform in [0.5,1.5][0.5, 1.5] and positions uniform in the cube [−1,1]3[-1, 1]^3 (seed 1), G=1G = 1 and ϵ=0\epsilon = 0. Direct summation uses 300⋅299=89700300 \cdot 299 = 89700 pair interactions (each ordered pair once). The walk of this implementation gives:

θ\theta interactions median relative force error largest relative force error
1.0 10417 4.0×10−24.0 \times 10^{-2} 1.31
0.7 20143 1.6×10−21.6 \times 10^{-2} 0.17
0.5 34319 5.7×10−35.7 \times 10^{-3} 0.038
0.3 61433 9.7×10−49.7 \times 10^{-4} 0.018
0 89700 6×10−166 \times 10^{-16} 3×10−153 \times 10^{-15}

These are measurements. The median error falls by a factor of about 40 from θ=1\theta = 1 to θ=0.3\theta = 0.3, faster than θ2\theta^2, 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 θ=0\theta = 0 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 ii contributes exactly once, either directly or through the monopole of exactly one accepted cell (Lemma 3). With θ=0\theta = 0 no cell is accepted, and the result is the direct sum (Theorem 1). For an accepted cell with all bodies within b<db < d of the center of mass, the error of the monopole potential is at most GMb2/(d2(d−b))G M b^2 / (d^2 (d - b)), because the dipole term about the center of mass is zero (Theorem 2). In 3D, b≤3 sb \le \sqrt{3}\, s, so for θ<1/3\theta < 1/\sqrt{3} the relative error of each accepted cell is below (3 θ)2/(1−3 θ)(\sqrt{3}\,\theta)^2 / (1 - \sqrt{3}\,\theta). For larger θ\theta no bound in terms of θ\theta 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 mj>0m_j > 0 and positions xj∈RD\mathbf{x}_j \in \mathbb{R}^D. A cell CC is a closed cube of side sCs_C; B(C)B(C) is the set of bodies stored in the leaves below CC, MC=∑j∈B(C)mjM_C = \sum_{j \in B(C)} m_j and zC=1MC∑j∈B(C)mjxj\mathbf{z}_C = \frac{1}{M_C} \sum_{j \in B(C)} m_j \mathbf{x}_j.

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 CC, the sets B(C′)B(C') of its children C′C' are disjoint and their union is B(C)B(C).

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. □\square

The depth limit of line L3 makes each insertion stop: a path has at most MAX-DEPTH+1\text{MAX-DEPTH} + 1 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 MCM_C and the center of mass zC\mathbf{z}_C of B(C)B(C).

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 ∑C′∑j∈B(C′)mj=MC\sum_{C'} \sum_{j \in B(C')} m_j = M_C, and similarly for the first moment. □\square

Lemma 3 (each body is counted once). For a target xi\mathbf{x}_i, let A\mathcal{A} be the set of cells accepted at line L8 and L\mathcal{L} the set of leaves reached at line L7. The sets B(C)B(C) for C∈A∪LC \in \mathcal{A} \cup \mathcal{L} 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 CC by its children keeps the sets BB 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. □\square

Theorem 1 (exactness for theta = 0). With θ=0\theta = 0 the walk returns the direct sum ∑j≠iGmj(xj−xi)/(∣xj−xi∣2+ϵ2)3/2\sum_{j \ne i} G m_j (\mathbf{x}_j - \mathbf{x}_i) / (|\mathbf{x}_j - \mathbf{x}_i|^2 + \epsilon^2)^{3/2}.

Proof. The test sC<θds_C < \theta d is false for θ=0\theta = 0, so no cell is accepted, A\mathcal{A} is empty, and by Lemma 3 every body is reached in exactly one leaf. Line L7 adds the pair term of each body j≠ij \ne i of the leaf. □\square

Theorem 2 (monopole error of an accepted cell). Let CC be a cell, x\mathbf{x} a point, d=∣x−zC∣d = |\mathbf{x} - \mathbf{z}_C| and b=max⁡j∈B(C)∣xj−zC∣b = \max_{j \in B(C)} |\mathbf{x}_j - \mathbf{z}_C|, with d>bd > b. Then, for ϵ=0\epsilon = 0,

∣−G∑j∈B(C)mj∣x−xj∣+GMCd∣≤GMC b2d2(d−b).\left| -G \sum_{j \in B(C)} \frac{m_j}{|\mathbf{x} - \mathbf{x}_j|} + \frac{G M_C}{d} \right| \le \frac{G M_C\, b^2}{d^2 (d - b)}.

Proof. Put the origin at zC\mathbf{z}_C and let yj=xj−zC\mathbf{y}_j = \mathbf{x}_j - \mathbf{z}_C, so ∣yj∣≤b<d|\mathbf{y}_j| \le b < d. The Legendre series 1∣x−y∣=∑l≥0∣y∣ldl+1Pl(cos⁡γ)\frac{1}{|\mathbf{x} - \mathbf{y}|} = \sum_{l \ge 0} \frac{|\mathbf{y}|^l}{d^{l+1}} P_l(\cos\gamma) converges absolutely. The term l=0l = 0 summed over B(C)B(C) is MC/dM_C / d. The term l=1l = 1 is 1d3x⋅∑jmjyj=0\frac{1}{d^3} \mathbf{x} \cdot \sum_j m_j \mathbf{y}_j = 0, because zC\mathbf{z}_C is the center of mass. With ∣Pl∣≤1|P_l| \le 1 and mj>0m_j > 0, the rest is at most ∑jmj∑l≥2bl/dl+1=MCb2d2(d−b)\sum_j m_j \sum_{l \ge 2} b^l / d^{l+1} = M_C \frac{b^2}{d^2 (d - b)}. □\square

Corollary (a bound in terms of theta). In dimension 3, the bodies of CC and their center of mass lie in the cube of CC, so b≤3 sCb \le \sqrt{3}\, s_C. If line L8 accepts CC, then sC<θds_C < \theta d, so b/d<3 θb / d < \sqrt{3}\, \theta. If 3 θ<1\sqrt{3}\, \theta < 1, the relative error of the potential of the cell is less than (3 θ)21−3 θ\frac{(\sqrt{3}\,\theta)^2}{1 - \sqrt{3}\,\theta}; for θ=0.3\theta = 0.3 this is 0.560.56, a loose worst case, and the error of a typical cell is much smaller. For θ≥1/3\theta \ge 1/\sqrt{3} there is no such bound in terms of θ\theta alone: the bodies of the cell can be arbitrarily close to the target. The test "the target is not inside CC" of line L8 removes the worst of these cases but does not give a bound. □\square

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 2D2^D. For bodies that are not all at one point, the depth limit bounds the number of cells by N⋅(MAX-DEPTH+1)N \cdot (\text{MAX-DEPTH} + 1). The O(Nlog⁡N)O(N \log N) cost for well-spread distributions is an estimate, discussed on the main page.

Complexity

The model is the real RAM, with NN bodies in 3D.

  • Tree build. Each insertion walks down one path, so the build costs O(N⋅depth)O(N \cdot \text{depth}). For bodies with a bounded ratio of the largest to the smallest distance, the depth is O(log⁡N)O(\log N) (theorem for this case), and line L6 costs O(number of cells)=O(N⋅depth)O(\text{number of cells}) = O(N \cdot \text{depth}).
  • Walk, uniform case (argument, not a theorem). At a level with cells of side ss, the cells that the target must open lie within distance about s/θs / \theta of it, and there are O(θ−3)O(\theta^{-3}) of them. Each opened cell has at most 8 children, so each level costs O(θ−3)O(\theta^{-3}), and the walk costs O(θ−3log⁡N)O(\theta^{-3} \log N). Over all targets this is O(Nlog⁡N)O(N \log N) for a fixed θ\theta (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 N=125N = 125, 250250 and 500500 at θ=0.7\theta = 0.7 (measurement).
  • Worst case. Bodies with very different scales make a deep tree: for example, bodies at 2−k2^{-k} for k=1,…,Nk = 1, \ldots, N along a line give depth Θ(N)\Theta(N), and the build costs Θ(N2)\Theta(N^2). The walk is also at most Θ(N2)\Theta(N^2) in total, since each target visits each cell at most once.
  • Space. Θ(N)\Theta(N) cells when the depth is O(log⁡N)O(\log N), with one mass and one center of mass each.

Properties

  • Not symmetric. The force of a cell on body ii and the force of body ii 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. θ\theta 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 O(Nlog⁡N)O(N \log N) like the walk.

Variants and improvements

  • Quadrupole moments. Storing the traceless quadrupole of each cell removes the leading error term and allows a larger θ\theta 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 O(N)O(N) for a fixed accuracy.

When to use it

Use Barnes-Hut for collisionless systems with 10410^4 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 NN and for collisional systems, where every encounter matters, and the fast multipole method when a guaranteed accuracy or O(N)O(N) cost is needed.

Pitfalls

  • Large opening angles. For θ>1/3\theta > 1/\sqrt{3} 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 θ\theta 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.

barnes_hut_algorithm.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. Sverre J. Aarseth, Gravitational N-Body Simulations, Tools and Algorithms, Cambridge University Press, 2003, Chapter 6 (tree codes), Section 6.2 (basic formulation)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
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)
WritingW2 basic
  • a scene preset for the example