Astronomy and Space Exploration ES

Higher Education / Numerical methods in astrophysics

Large-scale N-body and the Barnes–Hut tree

Why direct summation costs O(N²) and how the octree with opening criterion θ reduces it to O(N log N); Plummer gravitational softening and its error; the virial theorem as a diagnostic of a simulation.

⏱ 180 min algorithmic complexityhierarchical treesmultipole expansionvirial theoremerror statistics revision

By the end you will be able to:
  • Quantify the cost of direct force summation and prove that the number of interactions per body in a Barnes–Hut tree is O(log N) for a bounded distribution.
  • Build an octree, define the opening criterion s/d less than θ and bound the error of the monopole approximation.
  • Derive the force and potential of Plummer softening and quantify the bias (3/2)(ε/r)² it introduces.
  • Prove the virial theorem for a self-gravitating system and use it as a diagnostic of equilibrium and of the quality of the softening.
  • Measure on a Plummer sphere the error and cost of Barnes–Hut as a function of N and of θ.

1. Motivation: from three bodies to a billion

Illustration: Motivation: from three bodies to a billion

In the previous lesson we integrated three bodies. A globular cluster has N∼105N \sim 10^{5}–10610^{6} stars; a modern cosmological simulation, N≳1010N \gtrsim 10^{10} particles. The acceleration of each body,

ai=∑j≠iG mj rj−ri∥rj−ri∥3,\mathbf a_i = \sum_{j\ne i} G\,m_j\,\frac{\mathbf r_j - \mathbf r_i}{\lVert\mathbf r_j - \mathbf r_i\rVert^3},

requires N−1N - 1 terms, so each force evaluation costs N(N−1)/2N(N-1)/2 pairs: O(N2)O(N^2). With N=106N = 10^6 that is 5×10115\times10^{11} interactions per step; at 10910^{9} interactions per second, eight minutes per step, and a simulation needs 10410^{4}–10610^{6} steps. Barnes and Hut (1986) showed that by grouping distant bodies into “pseudo-particles” the cost drops to O(Nlog⁡N)O(N\log N) with a controllable error: it is the algorithm that, with refinements (high-order multipoles, fast multipole methods, meshes), lies behind almost all numerical galactic and cosmological dynamics.

In this lesson (and in src/lib/math/barneshut.ts) we use dimensionless units with G=1G = 1. For the Plummer model we also adopt Hénon units: total mass M=1M = 1, total energy E=−14E = -\tfrac14, so that the scale radius is a=3π/16≈0.589a = 3\pi/16 \approx 0.589.

2. The Barnes–Hut idea: monopole approximation

Illustration: The Barnes–Hut idea: monopole approximation

2.1 Potential of a distant group

Let a group of bodies with masses mjm_j at positions rj\mathbf r_j, with total mass M=∑mjM = \sum m_j and center of mass R=∑mjrj/M\mathbf R = \sum m_j\mathbf r_j/M, be contained in a cell of side ss. Its potential at a point r\mathbf r at distance d=∥r−R∥d = \lVert\mathbf r - \mathbf R\rVert from the center of mass, with xj=rj−R\mathbf x_j = \mathbf r_j - \mathbf R and d=r−R\mathbf d = \mathbf r - \mathbf R, is

Φ(r)=−G∑jmj∥d−xj∥=−Gd∑jmj∑ℓ=0∞(xjd)ℓPℓ(cos⁡γj),\Phi(\mathbf r) = -G\sum_j\frac{m_j}{\lVert\mathbf d - \mathbf x_j\rVert} = -\frac{G}{d}\sum_j m_j\sum_{\ell=0}^{\infty}\left(\frac{x_j}{d}\right)^{\ell} P_\ell(\cos\gamma_j),

where PℓP_\ell are the Legendre polynomials and γj\gamma_j the angle between xj\mathbf x_j and d\mathbf d (expansion valid for xj<dx_j \lt d). The first three terms are:

  • ℓ=0\ell = 0 (monopole): −GM/d-GM/d.
  • ℓ=1\ell = 1 (dipole): −Gd2∑jmj xj⋅d^=0-\dfrac{G}{d^2}\sum_j m_j\,\mathbf x_j\cdot\hat{\mathbf d} = 0, identically zero because ∑jmjxj=0\sum_j m_j\mathbf x_j = 0 by definition of the center of mass.
  • ℓ=2\ell = 2 (quadrupole): −Gd3∑jmj xj2 12(3cos⁡2γj−1)-\dfrac{G}{d^3}\sum_j m_j\,x_j^2\,\tfrac12(3\cos^2\gamma_j - 1), of size ≲GMs2/d3\lesssim G M s^2/d^3.

Therefore, when the group is replaced by a single mass MM at R\mathbf R (monopole approximation), the relative error of the potential is O ⁣((s/d)2)O\!\left((s/d)^2\right) and that of the force, by differentiation, is also O ⁣((s/d)2)O\!\left((s/d)^2\right). Choosing the center of mass as the center of the expansion is what kills the dipole and makes a parameter as simple as s/ds/d control the error quadratically.

2.2 The octree

The system is enclosed in a cube that is recursively subdivided into 8 octants until each cell contains at most one body. Each internal cell stores its total mass and its center of mass (accumulated during insertion). Construction costs O(Nlog⁡N)O(N\log N) on average and the tree is rebuilt at each step (Barnes & Hut did it that way; it is cheaper than maintaining it).

2.3 Opening criterion

To compute the force on body ii the tree is traversed from the root. At each cell of side ss whose center of mass is at distance dd from the body:

  • if s/d<θs/d \lt \theta (the cell looks “small”), its monopole is used and we do not descend;
  • otherwise, the cell is opened and its children are visited;
  • a leaf with a single body is treated exactly.

θ\theta is the opening parameter. With θ=0\theta = 0 no cell is accepted and the algorithm degenerates into direct summation (our test checks it to 10−910^{-9}). Usual values: θ≈0.5\theta \approx 0.5–0.80.8. The original Barnes–Hut criterion uses the side ss and the distance to the center of mass; Salmon and Warren (1994) showed that it can fail for cells whose center of mass is close to the edge, and proposed adding to dd the offset of the center of mass from the geometric center; our implementation uses the original criterion.

2.4 Cost O(Nlog⁡N)O(N\log N)

Proposition. For a given body and a system of NN bodies distributed with bounded density, the number of cells accepted with the criterion s/d<θs/d \lt \theta is O(θ−3log⁡N)O(\theta^{-3}\log N).

Proof (sketch). The cells at level kk have side sk=s0/2ks_k = s_0/2^k. A cell at that level is accepted if it is at distance d>sk/θd \gt s_k/\theta and its parent was opened, that is, d<2sk/θd \lt 2 s_k/\theta. The accepted cells of level kk therefore live in a spherical shell of radii sk/θs_k/\theta and 2sk/θ2 s_k/\theta, of volume 4π3(8−1)(sk/θ)3\tfrac{4\pi}{3}(8 - 1)(s_k/\theta)^3, which contains at most ≈29 θ−3\approx 29\,\theta^{-3} cells of volume sk3s_k^3. Since there are ≈log⁡2N1/3⋅\approx\log_2 N^{1/3}\cdot const non-empty levels (the depth of the tree is O(log⁡N)O(\log N) for bounded density), the total is O(θ−3log⁡N)O(\theta^{-3}\log N). Summing over the NN bodies: O(Nθ−3log⁡N)O(N\theta^{-3}\log N). ■\blacksquare

The θ−3\theta^{-3} dependence is harsh: going from θ=1\theta = 1 to θ=0.5\theta = 0.5 multiplies the cost by 8. In our table (§5) the measured ratio between θ=1\theta = 1 and θ=0.5\theta = 0.5 is 530/179≈3530/179 \approx 3, less than 8 because at N=2000N = 2000 many interactions are with individual leaves, not with cells.

3. Gravitational softening

Illustration: Gravitational softening

3.1 Why it is needed

With finite NN, two bodies can come arbitrarily close and the force ∝1/r2\propto 1/r^2 diverges: the time step would have to become tiny and, worse, a “collision” between two simulation particles represents nothing physical when each particle stands for 10410^{4} stars or a chunk of dark matter. The potential of each particle is replaced by that of a Plummer sphere of radius ε\varepsilon:

Φε(r)=−Gmr2+ε2,aε=−∇Φε=−Gm r(r2+ε2)3/2.\Phi_\varepsilon(r) = -\frac{G m}{\sqrt{r^2 + \varepsilon^2}},\qquad \mathbf a_\varepsilon = -\nabla\Phi_\varepsilon = -\frac{G m\,\mathbf r}{(r^2 + \varepsilon^2)^{3/2}} .

It is exactly the potential generated by the Plummer (1911) density, ρ(r)=3m4πε3(1+r2/ε2)−5/2\rho(r) = \dfrac{3m}{4\pi\varepsilon^3}\left(1 + r^2/\varepsilon^2\right)^{-5/2} (exercise 3). The force is finite everywhere: its maximum, ∣a∣max⁡=2Gm33 ε2\lvert a\rvert_{\max} = \dfrac{2Gm}{3\sqrt3\,\varepsilon^2}, occurs at r=ε/2r = \varepsilon/\sqrt2 (exercise 4). This same ε\varepsilon is the eps parameter of accelerations in integrators.ts and of the whole barneshut.ts module.

3.2 Bias and noise

The price is a bias: for r≫εr \gg \varepsilon,

∣aε∣∣a∣=(1+ε2r2)−3/2=1−32ε2r2+O ⁣(ε4r4),\frac{\lvert\mathbf a_\varepsilon\rvert}{\lvert\mathbf a\rvert} = \left(1 + \frac{\varepsilon^2}{r^2}\right)^{-3/2} = 1 - \frac32\frac{\varepsilon^2}{r^2} + O\!\left(\frac{\varepsilon^4}{r^4}\right),

the force is underestimated by 1.5 (ε/r)21.5\,(\varepsilon/r)^2 (1.51.5% at r=10εr = 10\varepsilon, 1515% at r=3εr = 3\varepsilon: sesgoPlummer). Dehnen (2001) analyzes the trade-off: a large ε\varepsilon reduces the noise of the force (the fluctuations due to the finite number of neighbors, which scale as N−1/2N^{-1/2} for the short-range forces) but increases the bias; there is an optimal ε\varepsilon that decreases with NN approximately as N−0.2N^{-0.2}–N−0.3N^{-0.3} for the Plummer profile, and compact-support kernels (splines) are preferable to the Plummer one because their bias vanishes exactly for r>2εr \gt 2\varepsilon. A practical rule: ε\varepsilon of the order of the mean separation between neighbors in the densest region; in our Plummer sphere with N=1000N = 1000 that mean distance to the nearest neighbor is 0.220.22 (Hénon units).

4. The virial theorem

Illustration: The virial theorem

4.1 Statement and proof

Let I=∑imi∥ri∥2I = \sum_i m_i\lVert\mathbf r_i\rVert^2 be the scalar moment of inertia. Differentiating twice,

12I¨=∑imi∥vi∥2+∑iri⋅Fi=2K+V,\frac12\ddot I = \sum_i m_i\lVert\mathbf v_i\rVert^2 + \sum_i \mathbf r_i\cdot\mathbf F_i = 2K + \mathcal V,

where KK is the kinetic energy and V=∑iri⋅Fi\mathcal V = \sum_i\mathbf r_i\cdot\mathbf F_i is the virial of Clausius. For pairwise forces Fij=−Fji\mathbf F_{ij} = -\mathbf F_{ji} directed along rij=ri−rj\mathbf r_{ij} = \mathbf r_i - \mathbf r_j, grouping pairs,

V=∑i<j(ri−rj)⋅Fij.\mathcal V = \sum_{i<j}\left(\mathbf r_i - \mathbf r_j\right)\cdot\mathbf F_{ij}.

If Fij\mathbf F_{ij} derives from a homogeneous potential of degree −1-1 (Φ=−Gmimj/rij\Phi = -G m_i m_j/r_{ij}), rij⋅Fij=−r ∂rΦ=Φ\mathbf r_{ij}\cdot\mathbf F_{ij} = -r\,\partial_r\Phi = \Phi, and V=W\mathcal V = W, the total potential energy. Averaging over time for a bounded system (⟨I¨⟩=0\langle\ddot I\rangle = 0):

2⟨K⟩+⟨W⟩=0,E=⟨K⟩+⟨W⟩=−⟨K⟩=12⟨W⟩.2\langle K\rangle + \langle W\rangle = 0,\qquad E = \langle K\rangle + \langle W\rangle = -\langle K\rangle = \tfrac12\langle W\rangle.

■\blacksquare (Binney & Tremaine §4.8.)

4.2 The virial with softening

With Plummer the force is not homogeneous of degree −2-2, and the virial of the force differs from the softened potential energy:

Vε=−∑i<jGmimj rij2(rij2+ε2)3/2,Wε=−∑i<jGmimjrij2+ε2,Vε=Wε+∑i<jGmimj ε2(rij2+ε2)3/2.\mathcal V_\varepsilon = -\sum_{i<j}\frac{G m_i m_j\, r_{ij}^2}{(r_{ij}^2 + \varepsilon^2)^{3/2}},\qquad W_\varepsilon = -\sum_{i<j}\frac{G m_i m_j}{\sqrt{r_{ij}^2 + \varepsilon^2}},\qquad \mathcal V_\varepsilon = W_\varepsilon + \sum_{i<j}\frac{G m_i m_j\,\varepsilon^2}{(r_{ij}^2+\varepsilon^2)^{3/2}} .

So the correct relation in equilibrium is 2K+Vε=02K + \mathcal V_\varepsilon = 0, not 2K+Wε=02K + W_\varepsilon = 0; the difference is positive and of order (ε/r)2∣W∣(\varepsilon/r)^2\lvert W\rvert. virial() returns the three quantities. In our Plummer sphere (N=1000N = 1000): with ε=0\varepsilon = 0, K=0.262K = 0.262, W=−0.521W = -0.521, 2K/∣W∣=1.0062K/\lvert W\rvert = 1.006 (the 0.6% deviation from 1 is sampling noise; the theoretical values are K=14K = \tfrac14, W=−12W = -\tfrac12). With ε=0.1\varepsilon = 0.1, Wε=−0.506W_\varepsilon = -0.506 and Vε=−0.484\mathcal V_\varepsilon = -0.484: the naive condition 2K/∣Wε∣2K/\lvert W_\varepsilon\rvert gives 1.0351.035 and the correct one 2K/∣Vε∣2K/\lvert\mathcal V_\varepsilon\rvert gives 1.081.08: the system, generated in Newtonian equilibrium, is 8% “too hot” for the softened gravity and will expand slightly when integrated. With ε=0.3\varepsilon = 0.3 (≈a/2\approx a/2) the discrepancy rises to 40%: such a softening no longer simulates the same system.

4.3 Use as a diagnostic

In a simulation one monitors Q=2K/∣V∣Q = 2K/\lvert\mathcal V\rvert (in addition to EE, P\mathbf P and L\mathbf L):

  • QQ oscillates around 1 with period ∼\sim dynamical time: system in equilibrium.
  • Sustained Q>1Q \gt 1: hot system, it expands; Q<1Q \lt 1: it collapses. A system in cold collapse (Q≈0Q \approx 0) “violently relaxes” toward Q≈1Q \approx 1 in a few dynamical times (Lynden-Bell 1967).
  • Secular drift of QQ with constant EE: two-body relaxation (evaporation, core collapse), a physical effect in clusters but spurious in simulations of collisionless systems, where it signals ε\varepsilon too small or NN too small.

5. Numerical results

Illustration: Numerical results

All from barneshut.ts on Plummer spheres generated with modeloPlummer (seed 7), ε=0.01\varepsilon = 0.01; the relative error of each body is ∥aBH−adirect∥/∥adirect∥\lVert\mathbf a_{\text{BH}} - \mathbf a_{\text{direct}}\rVert/\lVert\mathbf a_{\text{direct}}\rVert.

5.1 Cost and error as a function of NN (θ=0.5\theta = 0.5)

NNInteractions per body (BH)Direct (N−1N-1)SavingMedian errorMaximum error
2501442491.74.6×10−34.6\times10^{-3}2.7×10−22.7\times10^{-2}
5002314992.23.7×10−33.7\times10^{-3}3.0×10−23.0\times10^{-2}
10003589992.83.0×10−33.0\times10^{-3}2.2×10−22.2\times10^{-2}
200053019993.82.6×10−32.6\times10^{-3}6.0×10−26.0\times10^{-2}
400073839995.42.3×10−32.3\times10^{-3}0.150.15
800095879998.41.9×10−31.9\times10^{-3}0.160.16

When NN is multiplied by 32 (250 → 8000) the interactions per body are multiplied by 6.7, whereas direct summation is multiplied by 32. The growth is faster than pure log⁡N\log N (which would give ×1.6\times 1.6) because at these NN the Plummer profile, highly concentrated, makes a large fraction of the interactions be with leaves; the asymptotic O(log⁡N)O(\log N) regime is only reached at much larger NN, when the depth of the tree dominates over the interactions with leaves. The maximum error grows with NN: there is always some body for which a cell lies right at the limit of the criterion; this is the case that motivated the Salmon and Warren correction.

5.2 Error as a function of θ\theta (N=2000N = 2000)

θ\thetaInteractions per bodyMedian errorMaximum error
0.213262.3×10−42.3\times10^{-4}1.7×10−31.7\times10^{-3}
0.39696.8×10−46.8\times10^{-4}6.9×10−36.9\times10^{-3}
0.55302.6×10−32.6\times10^{-3}6.0×10−26.0\times10^{-2}
0.73196.7×10−36.7\times10^{-3}0.140.14
1.01791.8×10−21.8\times10^{-2}0.410.41
1.5936.0×10−26.0\times10^{-2}1.51.5

The median error scales approximately as θ2.5\theta^{2.5} between 0.20.2 and 11 (the monopole prediction is θ2\theta^{2} per cell, but the number of accepted cells also grows with θ\theta and the errors add with random signs). With θ=1.5\theta = 1.5 there are bodies whose force is completely wrong (error 150%): the criterion has accepted cells that contain the body’s own nearest neighbor.

5.3 What precision is needed

A relative force error of 10−310^{-3} per particle and per step, with random signs, accumulates after nn steps as n⋅10−3\sqrt n\cdot 10^{-3}: in 10410^{4} steps, 10%. But the discretization noise (using NN particles to represent a continuum) already produces force errors of order N−1/2N^{-1/2} (Dehnen 2001): for N=106N = 10^{6}, 10−310^{-3}. It makes no sense to compute the force much better than that intrinsic noise: hence θ≈0.5\theta \approx 0.5–0.70.7 is the standard.

three equal masses, T ≈ 6.3259 · t = 0.00

What to observe. The simulator uses direct summation (three bodies do not justify a tree). With the “Pythagorean” scenario, turn on softening with ε=0.1\varepsilon = 0.1 and compare the evolution with that of ε=0\varepsilon = 0: the close encounters that eject mass 3 are damped and the final state changes. It is the most direct demonstration that ε\varepsilon is a physical parameter of the model, not a numerical detail.

Problems

1. (Quadrupole). Show that for a group of masses with center of mass at the origin the quadrupole term of the potential at d\mathbf d is −G2d3∑jmj(3(xj⋅d^)2−xj2)-\dfrac{G}{2d^3}\sum_j m_j\left(3(\mathbf x_j\cdot\hat{\mathbf d})^2 - x_j^2\right), and that for a cubic cell of side ss centered on the center of mass it is bounded in absolute value by 34 GMs2/d3\tfrac34\,G M s^2/d^3. Conclude that the relative error of the monopole potential is ≤34(s/d)2\le \tfrac34(s/d)^2 and, with θ=0.5\theta = 0.5, below 19% in the worst case.

Show solution

From P2(cos⁡γ)=12(3cos⁡2γ−1)P_2(\cos\gamma) = \tfrac12(3\cos^2\gamma - 1) and xjcos⁡γj=xj⋅d^x_j\cos\gamma_j = \mathbf x_j\cdot\hat{\mathbf d} the expression follows. Inside a cube of side ss centered on the center of mass, xj≤32sx_j \le \tfrac{\sqrt3}{2}s, hence ∣3(xj⋅d^)2−xj2∣≤2xj2≤32s2\lvert 3(\mathbf x_j\cdot\hat{\mathbf d})^2 - x_j^2\rvert \le 2 x_j^2 \le \tfrac32 s^2 and the term is bounded by 34GMs2/d3\tfrac{3}{4}G M s^2/d^3. Relative to the monopole GM/dGM/d: 34(s/d)2<34θ2\tfrac34(s/d)^2 \lt \tfrac34\theta^2. With θ=0.5\theta = 0.5: 1919% as a worst-case bound on the potential; the typical error is much smaller (the table gives a median of 0.30.3%) because the masses are rarely all at the corners and the errors from different cells partially cancel. The force (derivative) has a bound of the same order with a different constant.

2. (Zero dipole). Show that if the expansion is made around a point C\mathbf C other than the center of mass (for example, the geometric center of the cell), a dipole term of relative error O(s/d)O(s/d) appears, and compute how much worse it is with θ=0.5\theta = 0.5.

Show solution

With xj′=rj−C\mathbf x_j' = \mathbf r_j - \mathbf C, ∑jmjxj′=M(R−C)≠0\sum_j m_j\mathbf x_j' = M(\mathbf R - \mathbf C) \ne 0, and the ℓ=1\ell = 1 term is −GMd2(R−C)⋅d^-\dfrac{G M}{d^2}(\mathbf R - \mathbf C)\cdot\hat{\mathbf d}, of relative size ∥R−C∥/d≤32s/d\lVert\mathbf R - \mathbf C\rVert/d \le \tfrac{\sqrt3}{2}s/d. Compared with the quadrupole ∼(s/d)2\sim(s/d)^2, with s/d=0.5s/d = 0.5 the dipole is ≈0.43\approx 0.43 versus 0.190.19: more than twice, and it decays only linearly with distance. This is why the center of mass (and not the geometric center) is the center of the expansion. It is an application of the general principle: the dipole can always be made to vanish by choosing the origin; not so the quadrupole.

3. (Plummer density). Show, with Poisson’s equation ∇2Φ=4πGρ\nabla^2\Phi = 4\pi G\rho, that the potential Φε=−Gm/r2+ε2\Phi_\varepsilon = -Gm/\sqrt{r^2+\varepsilon^2} corresponds to ρ(r)=3m4πε3(1+r2/ε2)−5/2\rho(r) = \dfrac{3m}{4\pi\varepsilon^3}\left(1 + r^2/\varepsilon^2\right)^{-5/2}, and check that ∫ρ dV=m\int\rho\,dV = m.

Show solution

In spherical symmetry ∇2Φ=r−2 ∂r(r2∂rΦ)\nabla^2\Phi = r^{-2}\,\partial_r(r^2\partial_r\Phi). With u=r2+ε2u = r^2 + \varepsilon^2: ∂rΦ=Gm r u−3/2\partial_r\Phi = G m\,r\,u^{-3/2}, r2∂rΦ=Gm r3u−3/2r^2\partial_r\Phi = G m\,r^3 u^{-3/2}, and ∂r(r3u−3/2)=3r2u−3/2−3r4u−5/2=3r2u−5/2(u−r2)=3r2ε2u−5/2\partial_r(r^3 u^{-3/2}) = 3r^2u^{-3/2} - 3r^4u^{-5/2} = 3r^2u^{-5/2}(u - r^2) = 3r^2\varepsilon^2u^{-5/2}. Hence ∇2Φ=3Gmε2(r2+ε2)−5/2\nabla^2\Phi = 3Gm\varepsilon^2(r^2+\varepsilon^2)^{-5/2} and ρ=3mε24π(r2+ε2)−5/2\rho = \dfrac{3m\varepsilon^2}{4\pi}(r^2+\varepsilon^2)^{-5/2}, which is the required expression. Mass: ∫0∞4πr2ρ dr=3mε2∫0∞r2(r2+ε2)−5/2dr=3m∫0∞t2(1+t2)−5/2dt=3m⋅13=m\int_0^\infty 4\pi r^2\rho\,dr = 3m\varepsilon^2\int_0^\infty r^2(r^2+\varepsilon^2)^{-5/2}dr = 3m\int_0^\infty t^2(1+t^2)^{-5/2}dt = 3m\cdot\tfrac13 = m (the integral equals 13\tfrac13: substitute t=tan⁡ϕt = \tan\phi). ■\blacksquare 50% of the mass lies inside r=1.305 εr = 1.305\,\varepsilon (equation r3/(r2+ε2)3/2=12r^3/(r^2+\varepsilon^2)^{3/2} = \tfrac12). In Hénon units, with a=3π/16a = 3\pi/16, one obtains W=−3π32GM2a=−12W = -\tfrac{3\pi}{32}\dfrac{GM^2}{a} = -\tfrac12 and, by the virial theorem, K=14K = \tfrac14, E=−14E = -\tfrac14: the values the test uses.

4. (Maximum force). Show that ∣aε∣=Gm r(r2+ε2)−3/2\lvert\mathbf a_\varepsilon\rvert = Gm\,r(r^2+\varepsilon^2)^{-3/2} is maximal at r=ε/2r = \varepsilon/\sqrt2 with value 2Gm33 ε2\dfrac{2Gm}{3\sqrt3\,\varepsilon^2}, and deduce a lower bound on the time step of a stable leapfrog, h≲ε3/2/Gmh \lesssim \varepsilon^{3/2}/\sqrt{Gm}.

Show solution

ddr[r(r2+ε2)−3/2]=(r2+ε2)−5/2(r2+ε2−3r2)=0⇒r2=ε2/2\dfrac{d}{dr}\left[r(r^2+\varepsilon^2)^{-3/2}\right] = (r^2+\varepsilon^2)^{-5/2}\left(r^2 + \varepsilon^2 - 3r^2\right) = 0 \Rightarrow r^2 = \varepsilon^2/2. Substituting: amax⁡=Gm ε/2(3ε2/2)3/2=Gmε2⋅1/2(3/2)3/2=2Gm33 ε2a_{\max} = Gm\,\dfrac{\varepsilon/\sqrt2}{(3\varepsilon^2/2)^{3/2}} = \dfrac{Gm}{\varepsilon^2}\cdot\dfrac{1/\sqrt2}{(3/2)^{3/2}} = \dfrac{2Gm}{3\sqrt3\,\varepsilon^2}. The maximum local “frequency” of an encounter is ω2∼amax⁡/r∼Gm/ε3\omega^2 \sim a_{\max}/r \sim Gm/\varepsilon^3, and the stability of the leapfrog for an oscillator requires hω<2h\omega \lt 2 (previous lesson, exercise 4): h≲2ε3/(Gm)h \lesssim 2\sqrt{\varepsilon^3/(Gm)}. This is the true practical reason for softening: it bounds the time step from below. With ε=0.01\varepsilon = 0.01 and m=10−3m = 10^{-3} (our sphere with N=1000N = 1000), h≲0.06h \lesssim 0.06.

5. (Virial with softening). Prove the identity Vε=Wε+∑i<jGmimjε2(rij2+ε2)−3/2\mathcal V_\varepsilon = W_\varepsilon + \sum_{i<j}G m_i m_j\varepsilon^2(r_{ij}^2+\varepsilon^2)^{-3/2} and conclude that ∣Vε∣<∣Wε∣\lvert\mathcal V_\varepsilon\rvert \lt \lvert W_\varepsilon\rvert: a system in Newtonian equilibrium always looks “hot” to the softened gravity.

Show solution

For a pair, rij⋅Fij=−Gmimj rij2/(rij2+ε2)3/2\mathbf r_{ij}\cdot\mathbf F_{ij} = -G m_i m_j\,r_{ij}^2/(r_{ij}^2+\varepsilon^2)^{3/2}. Writing r2=(r2+ε2)−ε2r^2 = (r^2+\varepsilon^2) - \varepsilon^2: −Gmimjr2+ε2+Gmimjε2(r2+ε2)3/2-\dfrac{G m_i m_j}{\sqrt{r^2+\varepsilon^2}} + \dfrac{G m_i m_j\varepsilon^2}{(r^2+\varepsilon^2)^{3/2}}. Summing over pairs gives the identity; the second term is positive, hence Vε>Wε\mathcal V_\varepsilon \gt W_\varepsilon and, both being negative, ∣Vε∣<∣Wε∣<∣W0∣\lvert\mathcal V_\varepsilon\rvert \lt \lvert W_\varepsilon\rvert \lt \lvert W_0\rvert. A system with 2K=∣W0∣2K = \lvert W_0\rvert has 2K/∣Vε∣>12K/\lvert\mathcal V_\varepsilon\rvert \gt 1. In our model: 1.081.08 with ε=0.1\varepsilon = 0.1, in agreement with the table. To correct it, the velocities are generated with the softened potential or KK is rescaled by ∣Vε∣/∣W0∣\lvert\mathcal V_\varepsilon\rvert/\lvert W_0\rvert.

6. (Computational: tree in 2D). Implement a quadtree for NN bodies in the plane, with criterion s/d<θs/d \lt \theta, and measure (a) the number of interactions per body for N=102,103,104N = 10^2, 10^3, 10^4 with θ=0.5\theta = 0.5; (b) the median error against direct summation for θ∈{0.3,0.5,0.7,1}\theta \in \{0.3, 0.5, 0.7, 1\}. Compare with the tables of §5.

Show solution

Minimal structure in Python (recursive; for N=104N = 10^4 it takes seconds):

import numpy as np
class Celda:
    def __init__(self, cx, cy, s):
        self.cx, self.cy, self.s = cx, cy, s
        self.m = 0.0; self.X = 0.0; self.Y = 0.0   # accumulated mass and center of mass
        self.cuerpo = None; self.hijos = None
    def insertar(self, i, x, y, m):
        if self.m == 0 and self.hijos is None:          # empty leaf
            self.cuerpo, self.m, self.X, self.Y = i, m, x, y; return
        if self.hijos is None:                          # occupied leaf: subdivide
            self.hijos = [None]*4; j = self.cuerpo; self.cuerpo = None
            mj, xj, yj = self.m, self.X, self.Y; self.m = 0
            self._bajar(j, xj, yj, mj)
        self._bajar(i, x, y, m)
        self.X = (self.X*self.m + x*m)/(self.m+m); self.Y = (self.Y*self.m + y*m)/(self.m+m); self.m += m
    def _bajar(self, i, x, y, m):
        k = (x >= self.cx) + 2*(y >= self.cy); q = self.s/4
        if self.hijos[k] is None:
            self.hijos[k] = Celda(self.cx + (q if k & 1 else -q), self.cy + (q if k & 2 else -q), self.s/2)
        self.hijos[k].insertar(i, x, y, m)
def fuerza(c, i, x, y, theta, eps, cont):
    if c.m == 0 or c.cuerpo == i: return np.zeros(2)
    dx, dy = c.X - x, c.Y - y; d = np.hypot(dx, dy)
    if c.hijos is None or c.s < theta*d:
        cont[0] += 1; return c.m*np.array([dx, dy])/(d*d + eps*eps)**1.5
    return sum(fuerza(h, i, x, y, theta, eps, cont) for h in c.hijos if h is not None)

The root is built with the square that contains all the bodies and fuerza is called for each one. Expected results: the number of interactions per body grows slowly (in 2D the factor is θ−2\theta^{-2} instead of θ−3\theta^{-3}), and the median errors with θ=0.5\theta = 0.5 are of order 10−310^{-3}, as in 3D. The error must vanish with θ=0\theta = 0: it is the first test to pass.

7. (Computational: violent relaxation). Generate a Plummer sphere with N=1000N = 1000 and halve all the velocities (Q=0.25Q = 0.25). Integrate with leapfrog (h=0.01h = 0.01, ε=0.05\varepsilon = 0.05, θ=0.5\theta = 0.5) up to t=20t = 20 and plot Q(t)=2K/∣Vε∣Q(t) = 2K/\lvert\mathcal V_\varepsilon\rvert, E(t)E(t) and the half-mass radius. In how many dynamical times is Q≈1Q \approx 1 reached?

Show solution

With modeloPlummer, leapfrogBarnesHut and virial from barneshut.ts (or the Python version of problem 6). The dynamical time of the sphere is tdyn=a3/(GM)≈0.45t_{\text{dyn}} = \sqrt{a^3/(GM)} \approx 0.45 in Hénon units. The system collapses: QQ rises above 1 (rebound) and is damped toward 1 in about 55–10 tdyn10\,t_{\text{dyn}}, that is, t≈2t \approx 2–55: Lynden-Bell’s violent relaxation. The half-mass radius drops to ≈0.6\approx 0.6 of the initial one and the system ends up more concentrated and with an extended envelope; EE must be conserved at the 1% level (the error comes from θ\theta and from the step); if not, reduce hh or θ\theta. A small fraction of particles may escape (Ei>0E_i \gt 0).

✦ Self-assessment

  1. 1. Why does the dipole term disappear in the Barnes–Hut approximation?
  2. 2. With the criterion s/d less than θ, reducing θ from 1 to 0.5 in 3D multiplies the number of accepted cells by approximately…
  3. 3. Plummer softening with parameter ε…
  4. 4. For a self-gravitating system in equilibrium without softening, the virial theorem states that…
  5. 5. A sphere generated in Newtonian equilibrium and integrated with softening ε has 2K/|𝒱ε|…
  6. 6. In a collisionless simulation, a slow drift of 2K/|𝒱| with well-conserved energy indicates…
Answer all the questions to check.

Further reading

  • Barnes & Hut (1986), Nature 324, 446: the original four-page paper, readable in full.
  • Aarseth (2003), Gravitational N-Body Simulations, ch. 6: tree codes in the context of direct methods; ch. 1 for the setup.
  • Dehnen (2001), MNRAS 324, 273, and Dehnen & Read (2011), EPJ Plus 126, 55: the modern review of softening, trees, fast multipoles and individual time steps.
  • Binney & Tremaine (2008), Galactic Dynamics, §2.9 (numerical solution of Poisson’s equation: trees, meshes) and §4.8 (Jeans equations and virial); §2.2.2 for the Plummer sphere.
  • Aarseth, Hénon & Wielen (1974), A&A 37, 183: the sampling algorithm for the Plummer model that modeloPlummer uses.
  • Salmon, J. K. & Warren, M. S. (1994). Skeletons from the treecode closet. J. Comput. Phys. 111, 136–155: the failures of the original criterion and the criteria with a guaranteed error bound.
🍎 Teacher guide
Time
2 classes of 90 min plus a 2-hour programming workshop
Learning outcome
By the end, the student justifies the O(N²) cost of direct summation and the O(N log N) of the tree, derives the error of the monopole approximation, explains the role of softening and uses the virial theorem as a diagnostic of a simulation.
Evidence of learning
Submission of problem 6 (2D tree with θ = 0 verification and cost and error tables) and of problem 7 (plots of Q(t), E(t) and half-mass radius with interpretation).

Materials

  • Python 3 with NumPy and Matplotlib
  • Reference code: src/lib/math/barneshut.ts and its test
  • The Barnes & Hut (1986) paper, for prior reading
  • The portal's N-body simulator (Pythagorean scenario with and without softening)

Suggested sequence

Class 1 (90 min). Opening (15 min): how much a step of direct summation costs for N=106N = 10^{6} and why “a bigger computer” is not enough. Development (60 min): multipole expansion and vanishing of the dipole (§2.1), construction of the tree on the board with 8–10 points in 2D, opening criterion, proposition on the O(Nlog⁡N)O(N\log N) cost. Closing (15 min): problem 2 in pairs.

Class 2 (90 min). Opening (10 min): demonstration of the simulator with and without softening. Development (55 min): Plummer potential and Poisson’s equation (problem 3), force bias, virial theorem with and without softening (§4), reading of the tables of §5. Closing (25 min): problems 4 and 5; mini-quiz.

Workshop (2 h). Full problem 6 (2D tree) with the θ=0\theta = 0 verification as first milestone, and problem 7 with the diagnostic plots. Students who finish can add the quadrupole term and measure how much the error drops at equal θ\theta.

Common mistakes

  • Thinking that ε is a “numerical trick” with no consequences. Show the change of final state of the Pythagorean problem and the virial ratio 1.08 with ε = 0.1: ε defines the system being simulated.
  • Making the multipole expansion around the geometric center of the cell. Ask for problem 2 before programming.
  • Believing that a force error of 0.3% is “too much” or “too little” without comparing it with the discretization noise N^(−1/2). Discuss §5.3.
  • Diagnosing equilibrium with 2K/|W| instead of 2K/|𝒱ε| when there is softening. It is problem 5.
  • Confusing violent relaxation (collisionless, fast) with two-body relaxation (collisional, slow). Ask for the time scales of each.
Key terms in this lesson (9)

Glossary terms that appear in the text. Each one links to its full entry.

  • N-body problem Simulating many bodies that all attract one another: a star cluster, a galaxy, the universe. Since each body feels all the others, the computation grows very quickly with N; the Barnes–Hut trick groups the distant ones together.
  • Virial theorem A rule that relates the energy of motion of a group of stars to the energy of their gravity. It makes it possible to "weigh" a cluster of galaxies by measuring only the speed of its members.
  • Logarithm The question "to what power must 10 be raised to get this number?". log(1000) = 3. It turns multiplications into additions and compresses huge numbers: that is why stellar magnitudes use logarithms.
  • Lagrange point Five special places near two bodies (such as the Sun and Earth) where a spacecraft can stay "still" with respect to them. The James Webb telescope is at one of them, L2, 1.5 million km away.
  • Leapfrog A simulation method that alternates a "kick" (changing the velocity) and a "drift" (moving the position), like a frog jumping. It is simple, time-reversible and conserves energy very well.
  • Gravity The force with which a planet pulls everything toward its center. On Earth it makes things fall 9.8 m/s faster every second; on Mars, with less mass and a smaller size, it is only 38 % of Earth's.
  • Two-body problem Working out how two bodies move when they attract only each other, like the Sun and a planet. It has an exact solution: Kepler's ellipses. With three bodies there is no longer a closed formula.
  • Dark matter An invisible kind of matter that neither emits nor reflects light, but whose gravity can be felt: it makes galaxies spin faster than expected. There is about five times more dark matter than normal matter, and we still do not know what it is.
  • Derivative How fast something changes at an instant: the derivative of position is velocity, and the derivative of velocity is acceleration. It is the slope of the graph at each point.

See the whole glossary →

References

  • Barnes, J. & Hut, P. (1986). A hierarchical O(N log N) force-calculation algorithm. Nature 324, 446–449. doi:10.1038/324446a0
  • Aarseth, S. J. (2003). Gravitational N-Body Simulations: Tools and Algorithms. Cambridge University Press. Ch. 1 (the N-body problem) and ch. 6 (tree codes).
  • Dehnen, W. (2001). Towards optimal softening in three-dimensional N-body codes — I. Minimizing the force error. MNRAS 324, 273–291. doi:10.1046/j.1365-8711.2001.04237.x
  • Dehnen, W. & Read, J. I. (2011). N-body simulations of gravitational dynamics. European Physical Journal Plus 126, 55. arXiv:1105.1082
  • Binney, J. & Tremaine, S. (2008). Galactic Dynamics, 2nd ed. Princeton University Press. §2.9 (numerical solution of Poisson's equation) and §4.8 (virial theorem).
  • Aarseth, S. J., Hénon, M. & Wielen, R. (1974). A comparison of numerical methods for the study of star cluster dynamics. Astronomy & Astrophysics 37, 183–187.
  • Plummer, H. C. (1911). On the problem of distribution in globular star clusters. MNRAS 71, 460–470.
  • Hairer, E., Lubich, C. & Wanner, G. (2006). Geometric Numerical Integration, 2nd ed. Springer. Ch. I.2 (leapfrog) and IX (backward error analysis).

Simulators for this lesson: N bodies: integrators and chaos