Algorithm Search⌘K

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
Properties
deterministic
Origin
Jasjeet S. Bagla, 2002

The TreePM method computes the gravitational forces of NN 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 O(Nlog⁡N)O(N \log N) when the particles cluster, which is where P3M slows down to O(N2)O(N^2). 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 NN masses mi>0m_i > 0 at positions xix_i in the periodic unit square, a mesh size MM (a power of 2), a split scale rsr_s, a cutoff factor cc with c rs≤12c \, r_s \le \frac12, and an opening angle θ≥0\theta \ge 0. The output is an approximation of the force on each particle,

Fi=−∑j∑n∈Z2′ mimjxi−xj+n∣xi−xj+n∣2,F_i = -\sum_j \sum_{n \in \mathbb{Z}^2}{}' \, m_i m_j \frac{x_i - x_j + n}{|x_i - x_j + n|^2},

the force of the 2D gravitational potential mimjlog⁡rm_i m_j \log r over all periodic images, defined by Ewald summation; the prime omits j=ij = i, n=0n = 0. 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 ϕ^(k)=2π/k2\hat\phi(k) = 2\pi / k^2,

ϕ^(k)=ϕ^(k) e−k2rs2⏟long range+ϕ^(k)(1−e−k2rs2)⏟short range.\hat\phi(k) = \underbrace{\hat\phi(k) \, e^{-k^2 r_s^2}}_{\text{long range}} + \underbrace{\hat\phi(k) \big(1 - e^{-k^2 r_s^2}\big)}_{\text{short range}}.

This is the Gaussian split of Ewald summation with α=1/(2rs)\alpha = 1 / (2 r_s). In real space, the short-range pair force is the Newtonian force times e−r2/(4rs2)e^{-r^2 / (4 r_s^2)}; in 3D the factor is erfc(r2rs)+rrsπe−r2/(4rs2)\mathrm{erfc}\big(\frac{r}{2 r_s}\big) + \frac{r}{r_s \sqrt\pi} e^{-r^2 / (4 r_s^2)}. Both factors fall off like a Gaussian, so the short-range force is cut at rcut=c rsr_{\text{cut}} = c \, r_s. Write fs(z)=−mimjz∣z∣2e−∣z∣2/(4rs2)f_s(z) = -m_i m_j \frac{z}{|z|^2} e^{-|z|^2 / (4 r_s^2)} for the short-range force of a mass mjm_j at displacement zz.

  1. TREEPM(m, x, M, r_s, c, θ)
  2. 1F^long ← particle-mesh forces with the filter e^{-k² r_s²} (TSC assignment, deconvolution, FFT, ik derivative, TSC interpolation)
  3. 2build a quadtree of the particles; each node stores its total mass and its center of mass
  4. 3for each particle i: walk the tree from the root with a stack, and F_i^short ← 0
  5. 4skip a node if its minimum image distance from x_i is at least r_cut = c r_s
  6. 5if 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
  7. 6else 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
  8. 7return F^long + F^short

Line L1 is a particle-mesh solver whose kernel is smooth on the mesh, because e−k2rs2e^{-k^2 r_s^2} is small at the Nyquist wave number when rsr_s is a mesh cell or more. Lines L2 to L6 are the Barnes-Hut algorithm with two changes: the pair force has the factor e−r2/(4rs2)e^{-r^2/(4 r_s^2)}, and the nodes out of range are skipped. Line L6 is the simple opening criterion s<θds < \theta d. The code uses monopoles only, which is enough because all masses are positive.

Example

Take N=200N = 200 particles of mass 1/2001/200: 100 in a Gaussian cluster of width 0.03 around (0.3,0.6)(0.3, 0.6) and 100 uniform in the unit square (seed 7). The mesh is 32×3232 \times 32 and c=6c = 6. 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:

rsr_s in mesh cells θ=0\theta = 0 θ=0.3\theta = 0.3 θ=0.5\theta = 0.5 θ=0.7\theta = 0.7 θ=1\theta = 1
0.75 3.4×10−33.4 \times 10^{-3}, 11376 3.4×10−33.4 \times 10^{-3}, 10867 5.5×10−35.5 \times 10^{-3}, 8929 1.1×10−21.1 \times 10^{-2}, 7175 2.4×10−22.4 \times 10^{-2}, 5516
1.25 7.6×10−47.6 \times 10^{-4}, 14304 9.0×10−49.0 \times 10^{-4}, 13134 3.3×10−33.3 \times 10^{-3}, 11088 7.3×10−37.3 \times 10^{-3}, 9320 1.8×10−21.8 \times 10^{-2}, 7278
2 1.6×10−41.6 \times 10^{-4}, 21518 5.5×10−45.5 \times 10^{-4}, 18460 2.4×10−32.4 \times 10^{-3}, 16125 5.8×10−35.8 \times 10^{-3}, 13619 1.5×10−21.5 \times 10^{-2}, 9443
2.5 7.4×10−57.4 \times 10^{-5}, 29944 5.7×10−45.7 \times 10^{-4}, 23563 2.3×10−32.3 \times 10^{-3}, 20172 5.7×10−35.7 \times 10^{-3}, 15708 1.5×10−21.5 \times 10^{-2}, 10161

These are measurements. The column θ=0\theta = 0 is the exact cut-off sum, so its error is the error of the mesh and of the cutoff; it falls fast as rsr_s grows, because the filter is smaller at the Nyquist wave number. A larger rsr_s puts more particles in range and needs more interactions. A larger θ\theta 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 θ=0.5\theta = 0.5 and rs=1.25r_s = 1.25 cells, the errors are 4.1×10−34.1 \times 10^{-3}, 5.6×10−45.6 \times 10^{-4} and 5.3×10−45.3 \times 10^{-4} on meshes of 16, 32 and 64 points per side, with 21060, 6808 and 1728 interactions. A finer mesh shrinks rsr_s 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 α=1/(2rs)\alpha = 1/(2 r_s) (Lemma 1). It proves that the pruning of line L4 never drops a particle in range (Lemma 2), and that with θ=0\theta = 0 the walk adds the short-range force of every pair closer than rcutr_{\text{cut}} exactly once (Lemma 3). The omitted part beyond the cutoff is O(e−c2/4)O(e^{-c^2/4}) (Lemma 4). A node accepted at line L6 with θ<1/2\theta < 1/\sqrt2 has an error of O(θ2)O(\theta^2) relative to its force, because the dipole term vanishes about the center of mass (Lemma 5). With θ=0\theta = 0, 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 mi>0m_i > 0 are in the periodic unit square, the split scale is rs>0r_s > 0, and the cutoff is rcut=c rs≤12r_{\text{cut}} = c \, r_s \le \frac12. The exact force on particle ii is Fi=−∑j∑n∈Z2′mimjxi−xj+n∣xi−xj+n∣2F_i = -\sum_j \sum_{n \in \mathbb{Z}^2}' m_i m_j \frac{x_i - x_j + n}{|x_i - x_j + n|^2}, where the prime omits j=ij = i, n=0n = 0; it is the force of the potential mimjlog⁡rm_i m_j \log r over all images, defined as the limit of the Ewald sums. For a displacement z≠0z \ne 0 write K(z)=z∣z∣2e−∣z∣2/(4rs2)K(z) = \frac{z}{|z|^2} e^{-|z|^2 / (4 r_s^2)}, so the short-range force of jj on ii is −mimjK(z)-m_i m_j K(z).

Lemma 1 (the split). Let α=1/(2rs)\alpha = 1 / (2 r_s). Then e−k2/(4α2)=e−k2rs2e^{-k^2 / (4\alpha^2)} = e^{-k^2 r_s^2}, and Fi=Fishort+FilongF_i = F_i^{\text{short}} + F_i^{\text{long}}, where Fishort=−∑j∑n′mimjK(xi−xj+n)F_i^{\text{short}} = -\sum_j \sum_n' m_i m_j K(x_i - x_j + n) and FilongF_i^{\text{long}} is the force of the potential with the Fourier coefficients 2πk2e−k2rs2S(k)\frac{2\pi}{k^2} e^{-k^2 r_s^2} S(k), k∈2πZ2∖{0}k \in 2\pi\mathbb{Z}^2 \setminus \{0\}, S(k)=∑jmje−ik⋅xjS(k) = \sum_j m_j e^{-i k \cdot x_j}.

Proof. This is Lemma 1 of the P3M proof with α2=1/(4rs2)\alpha^2 = 1 / (4 r_s^2) and the sign of gravity: 1r=e−α2r2r+1−e−α2r2r\frac1r = \frac{e^{-\alpha^2 r^2}}{r} + \frac{1 - e^{-\alpha^2 r^2}}{r}, the second term is the field of a Gaussian cloud of density α2πe−α2∣x∣2\frac{\alpha^2}{\pi} e^{-\alpha^2 |x|^2}, and the Fourier transform of that cloud is e−k2/(4α2)e^{-k^2 / (4\alpha^2)}. □\square

Line L1 approximates FilongF_i^{\text{long}} on the mesh. Lines L2 to L6 approximate FishortF_i^{\text{short}}.

Lemma 2 (pruning is safe). Let a node be the square BB of side s≤1s \le 1 and center cBc_B, and let b=(bx,by)b = (b_x, b_y) with bx=max⁡(0,∣w(xi,x−cB,x)∣−s/2)b_x = \max(0, |w(x_{i,x} - c_{B,x})| - s/2), where w(t)=t−round(t)w(t) = t - \mathrm{round}(t), and the same for yy. For every point p∈Bp \in B, the minimum image distance from xix_i to pp is at least ∣b∣|b|.

Proof. The periodic distance ∣w(t)∣|w(t)| on the circle of length 1 satisfies the triangle inequality, so ∣w(xi,x−px)∣≥∣w(xi,x−cB,x)∣−∣w(cB,x−px)∣≥∣w(xi,x−cB,x)∣−s/2|w(x_{i,x} - p_x)| \ge |w(x_{i,x} - c_{B,x})| - |w(c_{B,x} - p_x)| \ge |w(x_{i,x} - c_{B,x})| - s/2, and it is also ≥0\ge 0. So each component of the minimum image displacement is at least the corresponding component of bb in absolute value. □\square

Lemma 3 (the exact walk). If θ=0\theta = 0, lines L3 to L6 add −mimjK(z)-m_i m_j K(z) for every ordered pair i≠ji \ne j whose minimum image displacement zz has ∣z∣<rcut|z| < r_{\text{cut}}, exactly once, and add nothing else.

Proof. The tree build puts each index into exactly one child, so the leaves partition the particles. With θ=0\theta = 0 the test s2<θ2d2s^2 < \theta^2 d^2 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 rcutr_{\text{cut}} of xix_i. Line L5 keeps exactly the particles j≠ij \ne i with ∣z∣<rcut|z| < r_{\text{cut}}. Since rcut≤12r_{\text{cut}} \le \frac12, an image at distance below rcutr_{\text{cut}} is the minimum image, and it is unique, so no image is counted twice. □\square

Lemma 4 (the cutoff). The images omitted by Lemma 3 change FishortF_i^{\text{short}} by at most mi∑jmj e−c2/4rcut γm_i \sum_j m_j \, \frac{e^{-c^2/4}}{r_{\text{cut}}} \, \gamma, where γ\gamma bounds the sum of the Gaussian tails over the lattice and tends to 1 as cc grows.

Proof. Each omitted image is at distance r≥rcutr \ge r_{\text{cut}}, and ∣K∣=e−r2/(4rs2)/r|K| = e^{-r^2 / (4 r_s^2)} / r is decreasing, with the value e−c2/4/rcute^{-c^2/4} / r_{\text{cut}} at rcutr_{\text{cut}}. The farther images of a pair are at distances rcut+tr_{\text{cut}} + t with tt growing like the lattice, so their sum is a convergent Gaussian series dominated by its first term. □\square

Lemma 5 (one accepted node). Let a node hold the masses mjm_j at yjy_j in a square of side ss, with total mass MM and center of mass ycy_c, and let d=∣xi−yc∣>0d = |x_i - y_c| > 0 in the frame where all yjy_j and ycy_c are taken in one image. If s<θds < \theta d with θ<1/2\theta < 1/\sqrt2, then

∣∑jmjK(xi−yj)−MK(xi−yc)∣≤C M θ2(1−2 θ)3 d,\Big| \sum_j m_j K(x_i - y_j) - M K(x_i - y_c) \Big| \le \frac{C \, M \, \theta^2}{(1 - \sqrt2\,\theta)^3 \, d},

where CC is an absolute constant. Relative to the size M/dM / d of the node's Newtonian force, the error is O(θ2)O(\theta^2).

Proof. Write z=rswz = r_s w. Then K(z)=rs−1w∣w∣2e−∣w∣2/4K(z) = r_s^{-1} \frac{w}{|w|^2} e^{-|w|^2/4}, and each second derivative of KK in zz is rs−3r_s^{-3} times a sum of terms ∣w∣−3P(∣w∣)e−∣w∣2/4|w|^{-3} P(|w|) e^{-|w|^2/4} with polynomials PP. Since uke−u2/4u^k e^{-u^2/4} is bounded on u≥0u \ge 0 for each kk, ∥D2K(z)∥≤C/∣z∣3\|D^2 K(z)\| \le C / |z|^3. Expand K(xi−yj)K(x_i - y_j) about ycy_c with the Taylor formula with remainder. The constant terms give MK(xi−yc)M K(x_i - y_c); the linear terms give DK⋅∑jmj(yc−yj)=0DK \cdot \sum_j m_j (y_c - y_j) = 0, by the definition of the center of mass. Both yjy_j and ycy_c lie in the square, so ∣yj−yc∣≤2s|y_j - y_c| \le \sqrt2 s, and every point of the segment between them is at distance at least d−2s>(1−2θ)dd - \sqrt2 s > (1 - \sqrt2\theta) d from xix_i. The remainder is then at most 12∑jmjC(2s)2((1−2θ)d)3=CMs2((1−2θ)d)3\frac12 \sum_j m_j \frac{C (\sqrt2 s)^2}{((1 - \sqrt2\theta) d)^3} = \frac{C M s^2}{((1 - \sqrt2\theta) d)^3}, and s<θds < \theta d gives the bound. □\square

Theorem. With exact arithmetic, the TreePM force on particle ii is Fi+Eimesh+Eicut+EitreeF_i + E_i^{\text{mesh}} + E_i^{\text{cut}} + E_i^{\text{tree}}, where EimeshE_i^{\text{mesh}} is the error of line L1 against FilongF_i^{\text{long}}, ∣Eicut∣|E_i^{\text{cut}}| is bounded by Lemma 4, and EitreeE_i^{\text{tree}} is the sum, over the nodes accepted at line L6, of the errors of Lemma 5. If θ=0\theta = 0, then Eitree=0E_i^{\text{tree}} = 0.

Proof. By Lemma 1, Fi=Fishort+FilongF_i = F_i^{\text{short}} + F_i^{\text{long}}. 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 FishortF_i^{\text{short}}. □\square

Momentum. If θ=0\theta = 0, the short-range part obeys Newton's third law pair by pair, because K(−z)=−K(z)K(-z) = -K(z) 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 θ>0\theta > 0, the force of node AA on particle ii and the force of the node that contains ii on the particles of AA are not the same approximation, and the total force is not zero in general.

What is not proved here. We do not bound EimeshE_i^{\text{mesh}}. The mesh solver deconvolves the TSC assignment and interpolation by U^2\hat U^2, which is not the optimal influence function, and its error depends on how fast e−k2rs2e^{-k^2 r_s^2} decays before the Nyquist wave number π/h\pi / h, where it is e−π2rs2/h2e^{-\pi^2 r_s^2 / h^2}, 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 xix_i 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 Θ(N)\Theta(N) for the assignment and the interpolation and Θ(M2log⁡M)\Theta(M^2 \log M) for the FFTs.
  • Tree build. Line L2 costs Θ(N⋅D)\Theta(N \cdot D) for a tree of depth DD. The depth is about log⁡4N\log_4 N 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 rcutr_{\text{cut}}, and inside that region about 1/θ21/\theta^2 nodes per level. For a fixed θ>0\theta > 0 and a fixed number of mesh cells in rcutr_{\text{cut}}, this is O(log⁡N)O(\log N) nodes per particle, so the time is O(Nlog⁡N+M2log⁡M)O(N \log N + M^2 \log M) even with clusters. With θ=0\theta = 0, a cluster of KK particles within rcutr_{\text{cut}} costs Θ(K2)\Theta(K^2), 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 Θ(N2)\Theta(N^2).
  • Space. Θ(N+M2)\Theta(N + M^2).

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 rs/hr_s / h, cc and θ\theta.
  • Insensitive to clustering. The short-range work grows like log⁡N\log N per particle in a cluster, not like the number of neighbours.
  • No Newton's third law for θ>0\theta > 0. 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 rs=1.25r_s = 1.25 cells, the total force is 0.09 times the root mean square force for θ=0.5\theta = 0.5, and 6×10−156 \times 10^{-15} times it for θ=0\theta = 0.
  • 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 NN, direct summation with Ewald sums is simpler.

Pitfalls

  • Cutoff past half the box. The short-range part uses only the minimum image, so c rsc \, r_s must stay below 12\frac12, or the nearest images beyond the cutoff are missed; the code raises an error.
  • Split scale too small. If rsr_s is below about one mesh cell, the long-range kernel is not smooth on the mesh, and aliasing dominates the error whatever θ\theta is.
  • Split scale too large. A large rsr_s puts many particles in range and makes the tree do most of the work.
  • Opening angle too large. In the example, θ=1\theta = 1 gives errors near 2×10−22 \times 10^{-2} for every rsr_s. Choose θ\theta 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.

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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of correctness
  • 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