Algorithmadvanced
TreePM method
Also called tree particle-mesh method.
Splits gravity into a long-range part solved on a mesh by FFT and a short-range part summed with a Barnes-Hut tree; GADGET-2 and other cosmological codes use it.
- Time
- Θ(N^2) worstΘ(N log N + M^2 log M) average · best
- Space
- Θ(N + M^2) extra
- Where
- M = the number of mesh points per side; N = the number of particles
- Model
- Real RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jasjeet S. Bagla, 2002
The TreePM method computes the gravitational forces of particles in a periodic box. Like the P3M method, it splits each pair force into a long-range part and a short-range part. The long-range part is smooth, and a particle-mesh solver computes it for all particles at once with the fast Fourier transform. The short-range part is zero beyond a cutoff of a few mesh cells, and TreePM computes it with a Barnes-Hut tree instead of a sum over all close pairs. The tree treats a far group of particles as one mass, so the work stays near when the particles cluster, which is where P3M slows down to . Bagla described the method in 2002, and GADGET-2 and other cosmological codes use it.
In plain words
Gravity pulls every particle toward every other one. TreePM cuts each pull into a near piece and a far piece.
The far piece changes slowly over space. So you spread the particles onto a regular grid, find the far pull of the whole grid with a fast wave method, and read it back at each particle.
The near piece is strong only close to a particle. To add it up, you put the particles in a tree of nested squares. For each particle, you walk the tree. You skip the squares that are out of range. You treat a small square that is far enough away as one heavy point at its center of mass. You open the other squares and look inside. A dense cluster then costs little more than an empty region.
The problem
The input is masses at positions in the periodic unit square, a mesh size (a power of 2), a split scale , a cutoff factor with , and an opening angle . The output is an approximation of the force on each particle,
the force of the 2D gravitational potential over all periodic images, defined by Ewald summation; the prime omits , . Cosmological codes use the 3D law and add gravitational softening; the method is the same.
The algorithm
The potential is split in Fourier space. With ,
This is the Gaussian split of Ewald summation with . In real space, the short-range pair force is the Newtonian force times ; in 3D the factor is . Both factors fall off like a Gaussian, so the short-range force is cut at . Write for the short-range force of a mass at displacement .
TREEPM(m, x, M, r_s, c, θ)- 1
F^long ← particle-mesh forces with the filter e^{-k² r_s²} (TSC assignment, deconvolution, FFT, ik derivative, TSC interpolation) - 2
build a quadtree of the particles; each node stores its total mass and its center of mass - 3
for each particle i: walk the tree from the root with a stack, and F_i^short ← 0 - 4
skip a node if its minimum image distance from x_i is at least r_cut = c r_s - 5
if the node is a leaf: add f_s(x_i - x_j) for each j ≠ i in it with |x_i - x_j| < r_cut - 6
else if its side s < θ d, with d the distance to its center of mass: add f_s for its total mass at that center; else push its children - 7
return F^long + F^short
Line L1 is a particle-mesh solver whose kernel is smooth on the mesh, because is small at the Nyquist wave number when is a mesh cell or more. Lines L2 to L6 are the Barnes-Hut algorithm with two changes: the pair force has the factor , and the nodes out of range are skipped. Line L6 is the simple opening criterion . The code uses monopoles only, which is enough because all masses are positive.
Example
Take particles of mass : 100 in a Gaussian cluster of width 0.03 around and 100 uniform in the unit square (seed 7). The mesh is and . The reference is an Ewald sum. The table gives the relative error of the forces in the 2-norm, and the number of particle and node interactions of the short-range walk:
| in mesh cells | |||||
|---|---|---|---|---|---|
| 0.75 | , 11376 | , 10867 | , 8929 | , 7175 | , 5516 |
| 1.25 | , 14304 | , 13134 | , 11088 | , 9320 | , 7278 |
| 2 | , 21518 | , 18460 | , 16125 | , 13619 | , 9443 |
| 2.5 | , 29944 | , 23563 | , 20172 | , 15708 | , 10161 |
These are measurements. The column is the exact cut-off sum, so its error is the error of the mesh and of the cutoff; it falls fast as grows, because the filter is smaller at the Nyquist wave number. A larger puts more particles in range and needs more interactions. A larger saves interactions and adds the error of the tree, which soon dominates. The direct sum needs 39800 ordered pairs.
For 200 uniform particles (seed 21) with and cells, the errors are , and on meshes of 16, 32 and 64 points per side, with 21060, 6808 and 1728 interactions. A finer mesh shrinks and moves the work from the tree to the mesh. For two unit masses at distance 0.02, TreePM gives the force 49.904 and Ewald summation 49.937.
Correctness
The proof file is partial. It proves that the Fourier split is exact and is the Ewald split with (Lemma 1). It proves that the pruning of line L4 never drops a particle in range (Lemma 2), and that with the walk adds the short-range force of every pair closer than exactly once (Lemma 3). The omitted part beyond the cutoff is (Lemma 4). A node accepted at line L6 with has an error of relative to its force, because the dipole term vanishes about the center of mass (Lemma 5). With , the total force is zero. The proof does not bound the error of the mesh part; the example measures it.
Proof: The TreePM split is exact, the exact tree walk finds every close pair, and an accepted node has a relative error of order theta squaredpartial
We use exact arithmetic. The masses are in the periodic unit square, the split scale is , and the cutoff is . The exact force on particle is , where the prime omits , ; it is the force of the potential over all images, defined as the limit of the Ewald sums. For a displacement write , so the short-range force of on is .
Lemma 1 (the split). Let . Then , and , where and is the force of the potential with the Fourier coefficients , , .
Proof. This is Lemma 1 of the P3M proof with and the sign of gravity: , the second term is the field of a Gaussian cloud of density , and the Fourier transform of that cloud is .
Line L1 approximates on the mesh. Lines L2 to L6 approximate .
Lemma 2 (pruning is safe). Let a node be the square of side and center , and let with , where , and the same for . For every point , the minimum image distance from to is at least .
Proof. The periodic distance on the circle of length 1 satisfies the triangle inequality, so , and it is also . So each component of the minimum image displacement is at least the corresponding component of in absolute value.
Lemma 3 (the exact walk). If , lines L3 to L6 add for every ordered pair whose minimum image displacement has , exactly once, and add nothing else.
Proof. The tree build puts each index into exactly one child, so the leaves partition the particles. With the test of line L6 never holds, so every node that is not pruned at line L4 is opened, and every leaf that is not pruned is summed at line L5. By Lemma 2, a pruned node holds no particle within of . Line L5 keeps exactly the particles with . Since , an image at distance below is the minimum image, and it is unique, so no image is counted twice.
Lemma 4 (the cutoff). The images omitted by Lemma 3 change by at most , where bounds the sum of the Gaussian tails over the lattice and tends to 1 as grows.
Proof. Each omitted image is at distance , and is decreasing, with the value at . The farther images of a pair are at distances with growing like the lattice, so their sum is a convergent Gaussian series dominated by its first term.
Lemma 5 (one accepted node). Let a node hold the masses at in a square of side , with total mass and center of mass , and let in the frame where all and are taken in one image. If with , then
where is an absolute constant. Relative to the size of the node's Newtonian force, the error is .
Proof. Write . Then , and each second derivative of in is times a sum of terms with polynomials . Since is bounded on for each , . Expand about with the Taylor formula with remainder. The constant terms give ; the linear terms give , by the definition of the center of mass. Both and lie in the square, so , and every point of the segment between them is at distance at least from . The remainder is then at most , and gives the bound.
Theorem. With exact arithmetic, the TreePM force on particle is , where is the error of line L1 against , is bounded by Lemma 4, and is the sum, over the nodes accepted at line L6, of the errors of Lemma 5. If , then .
Proof. By Lemma 1, . The walk visits disjoint sets of particles: an accepted node is not opened, and the leaves partition the particles. So the short-range output equals the exact cut-off sum of Lemma 3 plus, for each accepted node, the difference bounded in Lemma 5. Lemma 4 bounds the difference between the cut-off sum and .
Momentum. If , the short-range part obeys Newton's third law pair by pair, because and Lemma 3 adds both ordered pairs. The mesh part sums to zero by Lemma 3 of the P3M proof, because the code uses the same TSC weights for assignment and interpolation, a real even filter and the zero derivative at the Nyquist index. So the total force is zero. If , the force of node on particle and the force of the node that contains on the particles of are not the same approximation, and the total force is not zero in general.
What is not proved here. We do not bound . The mesh solver deconvolves the TSC assignment and interpolation by , which is not the optimal influence function, and its error depends on how fast decays before the Nyquist wave number , where it is , and on aliasing. The page measures this error against an Ewald sum. Lemma 5 also assumes that the node and its center of mass are seen from in one image; the code takes the minimum image of the center of mass, which is the same thing when the node is small and far from the half-period distance.
Complexity
The model is the real RAM.
- Mesh part (theorem). Line L1 costs for the assignment and the interpolation and for the FFTs.
- Tree build. Line L2 costs for a tree of depth . The depth is about for evenly spread particles, and the code caps it at 40.
- Walk (typical, not a theorem). Each walk visits the nodes on the paths toward the region within , and inside that region about nodes per level. For a fixed and a fixed number of mesh cells in , this is nodes per particle, so the time is even with clusters. With , a cluster of particles within costs , as in P3M.
- Worst case. If many particles sit at the same point, a leaf at the depth cap holds them all, and line L5 costs .
- Space. .
Properties
- Exact split. The two parts add up to the exact force law. The errors come from the mesh, the cutoff and the tree, and the three are set by , and .
- Insensitive to clustering. The short-range work grows like per particle in a cluster, not like the number of neighbours.
- No Newton's third law for . The force of a node on a particle and the force of that particle's node on the node's particles are different approximations. In the example, with cells, the total force is 0.09 times the root mean square force for , and times it for .
- Periodic. The mesh makes the long-range part periodic, and the short-range part uses the minimum image. Both suit cosmological boxes.
- Deterministic. The result depends on the particles, not on their order, up to rounding.
Variants and improvements
- TPM. The TPM method of Xu (1995) splits space, not the force: it uses a tree for the particles in dense regions and a particle-mesh solver for the rest.
- 3D and softening. Production codes work in 3D with the erfc factor above, and add softening to the short-range force.
- Better trees. Higher multipoles, the relative opening criterion and the hashed oct-tree improve the short-range part; a fast multipole method can replace the tree.
- Zoom meshes. A second, finer mesh over a high-resolution region adds an intermediate scale to the split.
- Individual time steps. The long-range force changes slowly, so codes compute it less often than the short-range force of fast particles.
When to use it
Use TreePM for large periodic gravitational simulations in which the particles cluster strongly, as in cosmology at late times. If the particles stay fairly even, P3M or a pure mesh method is simpler. For a non-periodic system, use a Barnes-Hut tree or a fast multipole method alone. For small , direct summation with Ewald sums is simpler.
Pitfalls
- Cutoff past half the box. The short-range part uses only the minimum image, so must stay below , or the nearest images beyond the cutoff are missed; the code raises an error.
- Split scale too small. If is below about one mesh cell, the long-range kernel is not smooth on the mesh, and aliasing dominates the error whatever is.
- Split scale too large. A large puts many particles in range and makes the tree do most of the work.
- Opening angle too large. In the example, gives errors near for every . Choose for the target error, not for speed alone.
- No deconvolution. As in P3M, the mesh force must be divided by the transform of the assignment and interpolation windows, or the short wavelengths are too weak.
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/treepm-method/. The authors are listed in prov/BKG2W0.jsonl.
"""TreePM gravity in the periodic unit square, in 2D.
N masses m[i] > 0 at positions pos[i] = (x, y) attract by the 2D law: the
potential of a pair is m_i m_j log r and the force on i is
-m_i m_j (x_i - x_j) / r^2, summed over all periodic images.
The potential is split in Fourier space with a Gaussian filter of scale r_s:
phi_long(k) = phi(k) exp(-k^2 r_s^2), phi(k) = 2 pi / k^2,
so the short-range pair force is the Newtonian force times
exp(-r^2 / (4 r_s^2)). The long-range part is computed on an M x M mesh
(TSC assignment, deconvolution, FFT, ik differentiation, interpolation).
The short-range part is computed with a Barnes-Hut quadtree: a node of
side s at distance d from the particle is used as one point mass if
s < theta d, and nodes farther than r_cut = cut * r_s are skipped.
"""
import cmath
import math
from typing import Optional, Sequence
Point = tuple[float, float]
def fft(a: Sequence[complex], inverse: bool = False) -> list[complex]:
"""Radix-2 FFT without normalization."""
n = len(a)
if n == 1:
return [complex(a[0])]
even = fft(a[0::2], inverse)
odd = fft(a[1::2], inverse)
sign = 1 if inverse else -1
out = [0j] * n
for k in range(n // 2):
w = cmath.exp(sign * 2j * math.pi * k / n) * odd[k]
out[k] = even[k] + w
out[k + n // 2] = even[k] - w
return out
def fft2(grid: list[list[complex]], inverse: bool = False) -> list[list[complex]]:
rows = [fft(r, inverse) for r in grid]
cols = [fft([rows[i][j] for i in range(len(rows))], inverse) for j in range(len(rows))]
return [[cols[j][i] for j in range(len(cols))] for i in range(len(rows))]
def tsc(x: float, m: int) -> list[tuple[int, float]]:
"""Triangular shaped cloud weights for one coordinate."""
u = x * m
g = round(u)
t = u - g
return [((g - 1) % m, 0.5 * (0.5 - t) ** 2), (g % m, 0.75 - t * t), ((g + 1) % m, 0.5 * (0.5 + t) ** 2)]
def pm_forces(mass: Sequence[float], pos: Sequence[Point], m: int, r_s: float) -> list[list[float]]:
"""Long-range forces on the mesh with the filter exp(-k^2 r_s^2)."""
w = [(tsc(x, m), tsc(y, m)) for x, y in pos]
rho = [[0j] * m for _ in range(m)]
for i, mi in enumerate(mass):
for gx, wx in w[i][0]:
for gy, wy in w[i][1]:
rho[gx][gy] += mi * wx * wy
rho_k = fft2(rho)
h = 1.0 / m
def sinc(z: float) -> float:
return 1.0 if z == 0 else math.sin(z) / z
ex_k = [[0j] * m for _ in range(m)]
ey_k = [[0j] * m for _ in range(m)]
for i in range(m):
for j in range(m):
if i == 0 and j == 0:
continue
kx = 2 * math.pi * (i - m if i >= m // 2 else i)
ky = 2 * math.pi * (j - m if j >= m // 2 else j)
k2 = kx * kx + ky * ky
u2 = (sinc(kx * h / 2) * sinc(ky * h / 2)) ** 6
g = 2 * math.pi / k2 * math.exp(-k2 * r_s * r_s) / u2
dx = 0.0 if i == m // 2 else kx
dy = 0.0 if j == m // 2 else ky
ex_k[i][j] = 1j * dx * g * rho_k[i][j]
ey_k[i][j] = 1j * dy * g * rho_k[i][j]
ex = fft2(ex_k, inverse=True)
ey = fft2(ey_k, inverse=True)
out = []
for i, mi in enumerate(mass):
fx = fy = 0.0
for gx, wx in w[i][0]:
for gy, wy in w[i][1]:
fx += wx * wy * ex[gx][gy].real
fy += wx * wy * ey[gx][gy].real
out.append([mi * fx, mi * fy])
return out
class Node:
"""A square of the quadtree: center, side, total mass, center of mass, and children or a bucket."""
__slots__ = ("cx", "cy", "size", "mass", "mx", "my", "children", "idx")
def __init__(self, cx: float, cy: float, size: float):
self.cx, self.cy, self.size = cx, cy, size
self.mass = self.mx = self.my = 0.0
self.children: list["Node"] = []
self.idx: list[int] = []
def build_tree(mass: Sequence[float], pos: Sequence[Point], leaf_size: int = 4) -> Node:
"""Quadtree of the unit square; leaves hold at most leaf_size particles (or are at depth 40)."""
def build(idx: list[int], cx: float, cy: float, size: float, depth: int) -> Node:
node = Node(cx, cy, size)
node.mass = sum(mass[i] for i in idx)
node.mx = sum(mass[i] * pos[i][0] for i in idx) / node.mass
node.my = sum(mass[i] * pos[i][1] for i in idx) / node.mass
if len(idx) <= leaf_size or depth >= 40:
node.idx = idx
return node
quads: list[list[int]] = [[], [], [], []]
for i in idx:
quads[(pos[i][0] >= cx) * 2 + (pos[i][1] >= cy)].append(i)
q = size / 4
for k, sub in enumerate(quads):
if sub:
node.children.append(build(sub, cx + (q if k >= 2 else -q), cy + (q if k % 2 else -q), size / 2, depth + 1))
return node
return build(list(range(len(mass))), 0.5, 0.5, 1.0, 0)
def wrap(d: float) -> float:
return d - round(d)
def tree_short_range(mass: Sequence[float], pos: Sequence[Point], root: Node, r_s: float, theta: float,
cut: float = 6.0) -> tuple[list[list[float]], int]:
"""Short-range forces by a tree walk for each particle. Returns (forces, interactions)."""
r_cut = cut * r_s
a = 1.0 / (4 * r_s * r_s)
out = []
count = 0
for i, (xi, yi) in enumerate(pos): # @line L3
fx = fy = 0.0
stack = [root]
while stack:
node = stack.pop()
bx = max(0.0, abs(wrap(xi - node.cx)) - node.size / 2)
by = max(0.0, abs(wrap(yi - node.cy)) - node.size / 2)
if bx * bx + by * by >= r_cut * r_cut: # @line L4
continue
if not node.children: # @line L5
for j in node.idx:
if j == i:
continue
dx, dy = wrap(xi - pos[j][0]), wrap(yi - pos[j][1])
r2 = dx * dx + dy * dy
if r2 < r_cut * r_cut:
c = -mass[i] * mass[j] * math.exp(-a * r2) / r2
fx += c * dx
fy += c * dy
count += 1
continue
dx, dy = wrap(xi - node.mx), wrap(yi - node.my)
r2 = dx * dx + dy * dy
if node.size * node.size < theta * theta * r2: # @line L6
c = -mass[i] * node.mass * math.exp(-a * r2) / r2
fx += c * dx
fy += c * dy
count += 1
else:
stack.extend(node.children)
out.append([fx, fy])
return out, count
def treepm_forces(mass: Sequence[float], pos: Sequence[Point], m: int = 32, r_s: Optional[float] = None,
theta: float = 0.5, cut: float = 6.0, leaf_size: int = 4):
"""TreePM forces. r_s defaults to 1.25 mesh cells. Returns (forces, stats).
The cutoff cut * r_s must be at most 1/2, so that the minimum image is the only image in range.
"""
if r_s is None:
r_s = 1.25 / m
if cut * r_s > 0.5:
raise ValueError("cut * r_s must be at most 1/2")
if not mass:
return [], {"interactions": 0}
long = pm_forces(mass, pos, m, r_s) # @line L1
root = build_tree(mass, pos, leaf_size) # @line L2
short, count = tree_short_range(mass, pos, root, r_s, theta, cut)
out = [(a[0] + b[0], a[1] + b[1]) for a, b in zip(long, short)] # @line L7
return out, {"interactions": count}
def ewald_forces(mass: Sequence[float], pos: Sequence[Point], alpha: float = 8.0, kmax: int = 14) -> list[Point]:
"""Reference forces by Ewald summation: real space over 3 x 3 images, Fourier space up to |n| <= kmax."""
n = len(mass)
f = [[0.0, 0.0] for _ in range(n)]
for i in range(n):
for j in range(n):
for ix in (-1, 0, 1):
for iy in (-1, 0, 1):
if i == j and ix == 0 and iy == 0:
continue
rx = pos[i][0] - pos[j][0] + ix
ry = pos[i][1] - pos[j][1] + iy
r2 = rx * rx + ry * ry
c = -mass[i] * mass[j] * math.exp(-alpha * alpha * r2) / r2
f[i][0] += c * rx
f[i][1] += c * ry
for a in range(-kmax, kmax + 1):
for b in range(-kmax, kmax + 1):
if a == 0 and b == 0:
continue
kx, ky = 2 * math.pi * a, 2 * math.pi * b
k2 = kx * kx + ky * ky
coef = 2 * math.pi / k2 * math.exp(-k2 / (4 * alpha * alpha))
s = sum(mj * cmath.exp(-1j * (kx * x + ky * y)) for mj, (x, y) in zip(mass, pos))
for i, (x, y) in enumerate(pos):
im = (s * cmath.exp(1j * (kx * x + ky * y))).imag
f[i][0] -= mass[i] * coef * kx * im
f[i][1] -= mass[i] * coef * ky * im
return [(a, b) for a, b in f]
test_treepm_method.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/treepm-method/. The authors are listed in prov/BKG2W0.jsonl.
"""Tests for TreePM: the pieces, the tree, the short-range walk, and the forces against Ewald summation."""
import cmath
import math
import random
import unittest
from treepm_method import build_tree, ewald_forces, fft, tree_short_range, treepm_forces, tsc
def rms_err(f, ref):
num = sum((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 for a, b in zip(f, ref))
den = sum(b[0] ** 2 + b[1] ** 2 for b in ref)
return math.sqrt(num / den)
def uniform(n, seed):
rng = random.Random(seed)
return [1.0 / n] * n, [(rng.random(), rng.random()) for _ in range(n)]
def clustered(n, seed):
rng = random.Random(seed)
pos = []
for i in range(n):
if i % 2 == 0:
pos.append(((0.3 + rng.gauss(0, 0.03)) % 1.0, (0.6 + rng.gauss(0, 0.03)) % 1.0))
else:
pos.append((rng.random(), rng.random()))
return [1.0 / n] * n, pos
class TestPieces(unittest.TestCase):
def test_fft_matches_dft(self):
rng = random.Random(1)
a = [complex(rng.random(), rng.random()) for _ in range(16)]
for inverse, sign in ((False, -1), (True, 1)):
b = fft(a, inverse)
for k in range(16):
d = sum(a[g] * cmath.exp(sign * 2j * math.pi * k * g / 16) for g in range(16))
self.assertAlmostEqual(abs(b[k] - d), 0.0, places=12)
def test_tsc_conserves_mass_and_center(self):
rng = random.Random(2)
m = 16
for _ in range(30):
x = rng.uniform(0.1, 0.9)
w = tsc(x, m)
self.assertAlmostEqual(sum(v for _, v in w), 1.0, places=14)
center = sum(v * g for g, v in w)
self.assertAlmostEqual(center, x * m, places=12)
def test_tree_partitions_the_particles(self):
mass, pos = clustered(150, 3)
root = build_tree(mass, pos, leaf_size=4)
seen = []
def walk(node):
if not node.children:
self.assertLessEqual(len(node.idx), 4)
for i in node.idx:
self.assertLessEqual(abs(pos[i][0] - node.cx), node.size / 2)
self.assertLessEqual(abs(pos[i][1] - node.cy), node.size / 2)
seen.extend(node.idx)
return node.mass
total = sum(walk(c) for c in node.children)
self.assertAlmostEqual(total, node.mass, places=12)
return node.mass
self.assertAlmostEqual(walk(root), 1.0, places=12)
self.assertEqual(sorted(seen), list(range(150)))
def test_exact_walk_matches_brute_force(self):
mass, pos = clustered(120, 4)
r_s, cut = 0.04, 6.0
f, count = tree_short_range(mass, pos, build_tree(mass, pos), r_s, theta=0.0, cut=cut)
pairs = 0
for i in range(120):
fx = fy = 0.0
for j in range(120):
if i == j:
continue
rx = pos[i][0] - pos[j][0]
ry = pos[i][1] - pos[j][1]
rx -= round(rx)
ry -= round(ry)
r2 = rx * rx + ry * ry
if r2 < (cut * r_s) ** 2:
c = -mass[i] * mass[j] * math.exp(-r2 / (4 * r_s * r_s)) / r2
fx += c * rx
fy += c * ry
pairs += 1
self.assertAlmostEqual(f[i][0], fx, places=12)
self.assertAlmostEqual(f[i][1], fy, places=12)
self.assertEqual(count, pairs)
def test_ewald_does_not_depend_on_alpha(self):
mass, pos = uniform(60, 5)
self.assertLess(rms_err(ewald_forces(mass, pos, alpha=6.0, kmax=12), ewald_forces(mass, pos)), 1e-10)
def test_bad_input(self):
self.assertEqual(treepm_forces([], [])[0], [])
with self.assertRaises(ValueError):
treepm_forces([1.0], [(0.5, 0.5)], m=16, r_s=0.1, cut=6.0)
class TestTreePM(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.mass, cls.pos = uniform(200, 21)
cls.ref = ewald_forces(cls.mass, cls.pos)
cls.cmass, cls.cpos = clustered(200, 7)
cls.cref = ewald_forces(cls.cmass, cls.cpos)
def test_accuracy_against_ewald(self):
for m in (16, 32, 64):
f, _ = treepm_forces(self.mass, self.pos, m=m, theta=0.3)
self.assertLess(rms_err(f, self.ref), 1.5e-3)
f, _ = treepm_forces(self.cmass, self.cpos, m=32, theta=0.3)
self.assertLess(rms_err(f, self.cref), 2e-3)
def test_theta_trades_accuracy_for_work(self):
prev_err, prev_work = 0.0, 10 ** 9
for theta in (0.0, 0.5, 1.0):
f, st = treepm_forces(self.cmass, self.cpos, m=32, theta=theta)
e = rms_err(f, self.cref)
self.assertGreater(e, prev_err)
self.assertLess(st["interactions"], prev_work)
prev_err, prev_work = e, st["interactions"]
def test_split_scale_trades_mesh_error_for_pairs(self):
prev_err, prev_work = 1.0, 0
for cells in (0.75, 1.25, 2.0):
f, st = treepm_forces(self.cmass, self.cpos, m=32, r_s=cells / 32, theta=0.0)
e = rms_err(f, self.cref)
self.assertLess(e, prev_err)
self.assertGreater(st["interactions"], prev_work)
prev_err, prev_work = e, st["interactions"]
def test_total_force_with_exact_walk(self):
f, _ = treepm_forces(self.cmass, self.cpos, m=32, theta=0.0)
scale = math.sqrt(sum(a * a + b * b for a, b in self.cref) / len(self.cref))
self.assertLess(abs(sum(a for a, _ in f)), 1e-10 * scale)
self.assertLess(abs(sum(b for _, b in f)), 1e-10 * scale)
single, _ = treepm_forces([1.0], [(0.3, 0.6)], m=32)
self.assertLess(math.hypot(*single[0]), 1e-12)
def test_pair_force(self):
for d in (0.02, 0.05, 0.2, 0.4):
pos2 = [(0.3, 0.5), (0.3 + d, 0.5)]
f, _ = treepm_forces([1.0, 1.0], pos2, m=32)
r = ewald_forces([1.0, 1.0], pos2)
self.assertLess(abs(f[0][0] - r[0][0]), 0.01 * abs(r[0][0]))
self.assertGreater(f[0][0], 0.0)
if __name__ == "__main__":
unittest.main()
History
Hockney and Eastwood's P3M method of the 1980s already split the force into a mesh part and a short-range part. Xu (1995) combined a tree with a particle-mesh solver in the TPM method, but split the box into dense and sparse regions. Bagla (2002) described TreePM, which splits the force with a Gaussian filter in Fourier space and uses the tree for the short-range part everywhere. Springel's GADGET-2 (2005) used the same TreePM scheme for large cosmological simulations, and many later codes follow it.
References
- J. S. Bagla, TreePM: A code for cosmological N-body simulations, Journal of Astrophysics and Astronomy 23, 2002, 185-196, the split of the force with a Gaussian filter, the short-range force from the tree with a cutoff, and the errors of the method
- Guohong Xu, A new parallel N-body gravity solver: TPM, The Astrophysical Journal Supplement Series 98, 1995, 355-366, the TPM method, which uses a tree in the dense regions and a particle-mesh solver for the rest
- Volker Springel, The cosmological simulation code GADGET-2, Monthly Notices of the Royal Astronomical Society 364, 2005, 1105-1134, the TreePM force computation of GADGET-2, with the long-range force on a mesh and the short-range force from the tree
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 BKG2W0 Edit this page History Report an error Markdown