Algorithm Search⌘K

Algorithmintro

Direct N-body summation

Also called particle-particle method, direct summation.

Computes the force on each of N particles by summing over all other particles, in O(N^2) time per step and with no approximation error.

Time
Θ(N^2) worst
Space
Θ(N) extra
Where
N = the number of particles
Properties
deterministic
Origin
Sebastian von Hoerner, Sverre J. Aarseth, 1960

Direct N-body summation computes the gravitational acceleration of each of NN bodies as the sum of the pull of every other body. It visits each of the N(N−1)/2N(N-1)/2 pairs once, and it uses Newton's third law to give the force on both bodies of the pair. The result is exact up to rounding, so it is the reference against which the approximate methods (Barnes-Hut, the fast multipole method, particle-mesh) are measured. Its cost grows as N2N^2, so it is used for star clusters and planetary systems with up to about a million bodies, and on special hardware or GPUs. It is the force part of a solution of the gravitational N-body problem; an integrator such as Hermite or leapfrog moves the bodies.

In plain words

Each body pulls on each other body. The pull is stronger for a heavier body and weaker for a body that is far away. To find the total pull on one body, add up the pulls of all the others, one at a time.

Do this for every body and you have the forces. The work is one small calculation for each pair of bodies. A pair pulls with equal strength in opposite directions, so one calculation gives the pull on both bodies of the pair. With a thousand bodies there are about half a million pairs, and doubling the number of bodies makes four times the work. Nothing is left out, so the answer is exact except for rounding.

The problem

The input is NN masses mi>0m_i > 0 and positions xi∈R3\mathbf{x}_i \in \mathbb{R}^3, the gravitational constant GG (G=1G = 1 in code units) and a softening parameter ϵ≥0\epsilon \ge 0. The output is the acceleration of each body and the potential energy,

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

With ϵ=0\epsilon = 0 this is Newtonian gravity, and two bodies must not be at the same point. With ϵ>0\epsilon > 0 it is Plummer gravitational softening. In both cases ai=−1mi∇xiU\mathbf{a}_i = -\frac{1}{m_i} \nabla_{\mathbf{x}_i} U.

The algorithm

  1. DIRECT-SUM(m, x, epsilon, G) ▷ N bodies
  2. 1for i ← 1 to N do a_i ← 0; U ← 0
  3. 2for i ← 1 to N - 1 do
  4. 3for j ← i + 1 to N do
  5. 4d ← x_j - x_i
  6. 5s ← |d|² + epsilon²
  7. 6w ← G / (s √s)
  8. 7a_i ← a_i + m_j w d
  9. 8a_j ← a_j - m_i w d ▷ Newton's third law
  10. 9U ← U - G m_i m_j / √s
  11. 10return a, U

Lines L2 and L3 visit each unordered pair {i,j}\{i, j\} once. Line L6 computes the common factor G/r3G / r^3 of the pair, with the softened distance r=sr = \sqrt{s}. Lines L7 and L8 add the pair to both bodies with opposite signs. One pair costs one square root, one division and about 20 other operations in 3D.

Example

Take three bodies in the plane z=0z = 0, with G=1G = 1 and ϵ=0\epsilon = 0: m1=1m_1 = 1 at (0,0)(0, 0), m2=2m_2 = 2 at (3,0)(3, 0) and m3=3m_3 = 3 at (0,4)(0, 4). The distances are 3, 4 and 5, so each factor w=1/r3w = 1 / r^3 is rational.

pair d=xj−xi\mathbf{d} = \mathbf{x}_j - \mathbf{x}_i ww added to ai\mathbf{a}_i added to aj\mathbf{a}_j added to UU
(1, 2) (3, 0) 1/27 (2/9, 0) (-1/9, 0) -2/3
(1, 3) (0, 4) 1/64 (0, 3/16) (0, -1/16) -3/4
(2, 3) (-3, 4) 1/125 (-9/125, 12/125) (6/125, -8/125) -6/5

The sums are a1=(2/9,3/16)≈(0.222222,0.1875)\mathbf{a}_1 = (2/9, 3/16) \approx (0.222222, 0.1875), a2=(−1/9−9/125,12/125)≈(−0.183111,0.096)\mathbf{a}_2 = (-1/9 - 9/125, 12/125) \approx (-0.183111, 0.096), a3=(6/125,−1/16−8/125)=(0.048,−0.1265)\mathbf{a}_3 = (6/125, -1/16 - 8/125) = (0.048, -0.1265) and U=−157/60≈−2.616667U = -157/60 \approx -2.616667. As a check, ∑imiai=(2/9−2/9−18/125+18/125,  3/16+24/125−3/16−24/125)=(0,0)\sum_i m_i \mathbf{a}_i = (2/9 - 2/9 - 18/125 + 18/125, \; 3/16 + 24/125 - 3/16 - 24/125) = (0, 0).

Correctness

Each unordered pair is visited exactly once by lines L2 and L3, and the pair adds the term of jj to ai\mathbf{a}_i and the term of ii to aj\mathbf{a}_j. So after line L10 each ai\mathbf{a}_i holds the sum over all j≠ij \ne i, and UU holds the sum over all pairs. The pair terms of lines L7 and L8 are mjwdm_j w \mathbf{d} and −miwd-m_i w \mathbf{d}, so in exact arithmetic ∑imiai=0\sum_i m_i \mathbf{a}_i = 0, and the total momentum is conserved by any integrator that uses these forces at one common time. The full proof, with the gradient identity, is in the proof file.

Proof: Direct summation gives the exact accelerations, the potential energy and zero total forcefull

We use exact real arithmetic, as in the real RAM model. Let N≥1N \ge 1, masses mi>0m_i > 0, positions xi\mathbf{x}_i, G>0G > 0 and ϵ≥0\epsilon \ge 0. If ϵ=0\epsilon = 0, we assume that no two positions are equal. For a pair i≠ji \ne j write dij=xj−xi\mathbf{d}_{ij} = \mathbf{x}_j - \mathbf{x}_i, sij=∣dij∣2+ϵ2>0s_{ij} = |\mathbf{d}_{ij}|^2 + \epsilon^2 > 0 and wij=Gsij−3/2w_{ij} = G s_{ij}^{-3/2}. Then dji=−dij\mathbf{d}_{ji} = -\mathbf{d}_{ij}, sji=sijs_{ji} = s_{ij} and wji=wijw_{ji} = w_{ij}.

Claim 1 (the loop computes the sums). After line L10, ai=∑j≠imjwijdij\mathbf{a}_i = \sum_{j \ne i} m_j w_{ij} \mathbf{d}_{ij} for each ii, and U=−G∑i<jmimjsij−1/2U = -G \sum_{i < j} m_i m_j s_{ij}^{-1/2}.

Proof. Lines L2 and L3 run over the pairs (i,j)(i, j) with i<ji < j, and each such pair occurs exactly once. Consider a fixed body kk. The pairs that change ak\mathbf{a}_k are the pairs (k,j)(k, j) with j>kj > k, at line L7, and the pairs (i,k)(i, k) with i<ki < k, at line L8. Line L7 for the pair (k,j)(k, j) adds mjwkjdkjm_j w_{kj} \mathbf{d}_{kj}. Line L8 for the pair (i,k)(i, k) adds −miwikdik=miwkidki-m_i w_{ik} \mathbf{d}_{ik} = m_i w_{ki} \mathbf{d}_{ki}. So each j≠kj \ne k adds its term exactly once, and ak\mathbf{a}_k starts at 00 by line L1. Line L9 adds the term of each pair i<ji < j to UU exactly once, and UU starts at 00. □\square

Claim 2 (force is minus the gradient). For each ii, miai=−∇xiUm_i \mathbf{a}_i = -\nabla_{\mathbf{x}_i} U.

Proof. Only the pairs that contain ii depend on xi\mathbf{x}_i. For the pair of ii and jj, the term of UU is −Gmimjsij−1/2-G m_i m_j s_{ij}^{-1/2}, and ∇xisij=−2dij\nabla_{\mathbf{x}_i} s_{ij} = -2 \mathbf{d}_{ij}. So

∇xi(−Gmimjsij−1/2)=−Gmimj(−12)sij−3/2(−2dij)=−mimjwijdij.\nabla_{\mathbf{x}_i}\left(-G m_i m_j s_{ij}^{-1/2}\right) = -G m_i m_j \left(-\tfrac{1}{2}\right) s_{ij}^{-3/2} \left(-2 \mathbf{d}_{ij}\right) = -m_i m_j w_{ij} \mathbf{d}_{ij}.

So minus the gradient of this term is mimjwijdijm_i m_j w_{ij} \mathbf{d}_{ij}. The sum over j≠ij \ne i is miaim_i \mathbf{a}_i by Claim 1. □\square

Claim 3 (zero total force). ∑imiai=0\sum_i m_i \mathbf{a}_i = 0.

Proof. By Claim 1, ∑imiai=∑i∑j≠imimjwijdij\sum_i m_i \mathbf{a}_i = \sum_i \sum_{j \ne i} m_i m_j w_{ij} \mathbf{d}_{ij}. Group the terms in pairs {i,j}\{i, j\}. The two terms of a pair are mimjwijdijm_i m_j w_{ij} \mathbf{d}_{ij} and mjmiwjidji=−mimjwijdijm_j m_i w_{ji} \mathbf{d}_{ji} = -m_i m_j w_{ij} \mathbf{d}_{ij}, so they cancel. □\square

Consequences. Claim 1 is the definition of the softened (or, for ϵ=0\epsilon = 0, the Newtonian) accelerations, so the algorithm has no truncation error. By Claim 3, an integrator that updates all velocities with forces computed at one common time changes the total momentum ∑imivi\sum_i m_i \mathbf{v}_i by h∑imiai=0h \sum_i m_i \mathbf{a}_i = 0 per kick. In floating-point arithmetic the two terms of a pair are computed from the same rounded wijw_{ij} and dij\mathbf{d}_{ij}, but the sums are rounded in different orders, so Claim 3 holds only up to rounding.

Cost. The inner body of lines L4 to L9 runs ∑i=1N−1(N−i)=N(N−1)/2\sum_{i=1}^{N-1} (N - i) = N(N-1)/2 times, and each run costs a constant number of operations for a fixed dimension. Line L1 costs Θ(N)\Theta(N). So the time is Θ(N2)\Theta(N^2) for all inputs, and the extra space is the NN accelerations. □\square

Complexity

In the real RAM model, the loop of lines L2 and L3 runs exactly N(N−1)/2N(N-1)/2 times, and each pass costs Θ(1)\Theta(1) operations in a fixed dimension. So one force evaluation costs Θ(N2)\Theta(N^2) in every case, with no dependence on the positions. The extra space is Θ(N)\Theta(N) for the accelerations; no pair list is stored.

For N=1000N = 1000 there are 499500 pairs. A run of TT steps with one force evaluation per step costs Θ(N2T)\Theta(N^2 T). A force evaluation that reads every mass and position needs Ω(N)\Omega(N) time, and no exact method below Θ(N2)\Theta(N^2) is known for this sum with arbitrary real positions in this model. The tree and multipole methods trade a controlled error for O(Nlog⁡N)O(N \log N) or O(N)O(N) time.

Properties

  • No truncation error. The only errors are rounding errors. The order of the additions changes the result in the last bits, and the total momentum ∑mivi\sum m_i \mathbf{v}_i is conserved only up to rounding (see the floating-point model).
  • Symmetric. Lines L7 and L8 give equal and opposite pair forces, so there is no spurious net force, unlike tree codes where the forces of ii on jj and of jj on ii come from different approximations.
  • Simple to vectorize and to parallelize. All pairs are independent except for the sums. Each processor can take a block of targets ii and loop over all sources jj; this costs N(N−1)N(N-1) pair evaluations, twice as many, but needs no write conflicts.

Variants and improvements

  • All targets, all sources. Loop over all j≠ij \ne i for each ii without the third law. This doubles the work, but each target is written by one thread only; it is the usual form on GPUs.
  • Ring scheme. On PP processors, each holds N/PN / P bodies, and the blocks of sources travel around a ring of processors, so that each block meets each other block once (Aarseth 2003, Section 3.7).
  • Jerk with the force. The Hermite integrator also needs the time derivative of each pair force; it is computed in the same loop with a few more operations per pair.
  • Neighbor schemes. The Ahmad-Cohen scheme computes the force of near neighbors often and the force of distant bodies less often (Aarseth 2003, Section 3.2). It is still direct summation, but with two time scales.
  • Softening. With ϵ>0\epsilon > 0 the same loop gives the Plummer softened force, used for collisionless systems.

When to use it

Use direct summation when every close encounter matters, as in star clusters, the cores of galaxies with black holes, and planetary systems. Use it as the reference to measure the error of a tree code or an FMM. Use it when NN is below a few thousand, because there the tree methods have more overhead than they save. For collisionless systems with millions of bodies, use Barnes-Hut, FMM, particle-mesh or TreePM instead.

Pitfalls

  • Self-interaction. The pair j=ij = i must be skipped. With ϵ>0\epsilon > 0 it gives no force but adds −Gmi2/ϵ-G m_i^2 / \epsilon to the energy.
  • Coincident bodies with ϵ=0\epsilon = 0. Two bodies at the same point give a division by zero. Real close encounters with ϵ=0\epsilon = 0 need regularization, not a tiny time step.
  • Counting pairs twice in the energy. If the loop runs over all ordered pairs, the potential energy must be halved.
  • The cost of the square root. The square root and the division dominate the cost of a pair. Compute 1/s1/\sqrt{s} once and form ww from it.
  • Rounding in large sums. For large NN, the sum of many small far terms with a few large near terms loses digits. Compensated or pairwise summation reduces this when it matters (Kahan summation, pairwise summation).

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.

direct_n_body_summation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direct-n-body-summation/. The authors are listed in prov/14GKBC.jsonl.
"""Direct N-body summation of gravitational accelerations and potential energy.

The bodies have masses m[i] and positions x[i] (tuples of any dimension,
usually 3). The softening parameter eps gives the Plummer pair potential
-G m_i m_j / sqrt(r^2 + eps^2); eps = 0 is Newtonian gravity. Units: G = 1
unless given.

Each of the N(N - 1) / 2 pairs is visited once, and Newton's third law gives
the force on both bodies of the pair.

Cost: N(N - 1) / 2 pair evaluations, Theta(N^2) time, Theta(N) extra space.
"""

import math
from typing import Sequence

Vec = tuple[float, ...]


def direct_sum(m: Sequence[float], x: Sequence[Vec], eps: float = 0.0, G: float = 1.0) -> tuple[list[list[float]], float]:
    """Return (accelerations, potential energy) by summation over all pairs."""
    n = len(m)
    dim = len(x[0]) if n else 0
    a = [[0.0] * dim for _ in range(n)]  # @line L1
    u = 0.0
    e2 = eps * eps
    for i in range(n - 1):  # @line L2
        xi, ai = x[i], a[i]
        for j in range(i + 1, n):  # @line L3
            xj, aj = x[j], a[j]
            d = [xj[k] - xi[k] for k in range(dim)]  # @line L4
            s = sum(c * c for c in d) + e2  # @line L5
            if s == 0.0:
                raise ValueError("two bodies at the same point with eps = 0")
            r = math.sqrt(s)
            w = G / (s * r)  # @line L6
            for k in range(dim):
                ai[k] += m[j] * w * d[k]  # @line L7
                aj[k] -= m[i] * w * d[k]  # @line L8
            u -= G * m[i] * m[j] / r  # @line L9
    return a, u  # @line L10


def accelerations(m: Sequence[float], x: Sequence[Vec], eps: float = 0.0, G: float = 1.0) -> list[list[float]]:
    return direct_sum(m, x, eps, G)[0]


def potential_energy(m: Sequence[float], x: Sequence[Vec], eps: float = 0.0, G: float = 1.0) -> float:
    return direct_sum(m, x, eps, G)[1]


def kinetic_energy(m: Sequence[float], v: Sequence[Vec]) -> float:
    return 0.5 * sum(mi * sum(c * c for c in vi) for mi, vi in zip(m, v))


def leapfrog(m: Sequence[float], x: Sequence[Vec], v: Sequence[Vec], h: float, steps: int, eps: float = 0.0, G: float = 1.0) -> tuple[list[list[float]], list[list[float]]]:
    """Kick-drift-kick leapfrog (velocity Verlet) driven by direct_sum. Used to test the forces in motion."""
    x = [list(p) for p in x]
    v = [list(q) for q in v]
    a = accelerations(m, x, eps, G)
    for _ in range(steps):
        for i in range(len(m)):
            for k in range(len(x[i])):
                v[i][k] += 0.5 * h * a[i][k]
                x[i][k] += h * v[i][k]
        a = accelerations(m, x, eps, G)
        for i in range(len(m)):
            for k in range(len(x[i])):
                v[i][k] += 0.5 * h * a[i][k]
    return x, v
test_direct_n_body_summation.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direct-n-body-summation/. The authors are listed in prov/14GKBC.jsonl.
import math
import random

import pytest

from direct_n_body_summation import accelerations, direct_sum, kinetic_energy, leapfrog, potential_energy


def brute(m, x, eps=0.0, G=1.0):
    """Independent reference: for each body, loop over every other body (no third law)."""
    n, dim = len(m), len(x[0])
    acc = []
    for i in range(n):
        ai = [0.0] * dim
        for j in range(n):
            if j != i:
                d = [x[j][k] - x[i][k] for k in range(dim)]
                r2 = sum(c * c for c in d) + eps * eps
                for k in range(dim):
                    ai[k] += G * m[j] * d[k] / r2 ** 1.5
        acc.append(ai)
    u = -0.5 * sum(G * m[i] * m[j] / math.sqrt(sum((x[i][k] - x[j][k]) ** 2 for k in range(dim)) + eps * eps)
                   for i in range(n) for j in range(n) if i != j)
    return acc, u


def random_bodies(n, seed):
    rng = random.Random(seed)
    m = [rng.uniform(0.5, 2.0) for _ in range(n)]
    x = [tuple(rng.uniform(-1.0, 1.0) for _ in range(3)) for _ in range(n)]
    return m, x


def test_hand_example_345():
    m = [1.0, 2.0, 3.0]
    x = [(0.0, 0.0, 0.0), (3.0, 0.0, 0.0), (0.0, 4.0, 0.0)]
    a, u = direct_sum(m, x)
    want = [(2 / 9, 3 / 16, 0.0), (-1 / 9 - 9 / 125, 12 / 125, 0.0), (6 / 125, -1 / 16 - 8 / 125, 0.0)]
    for ai, wi in zip(a, want):
        for c, w in zip(ai, wi):
            assert c == pytest.approx(w, abs=1e-15)
    assert u == pytest.approx(-157 / 60, rel=1e-15)


@pytest.mark.parametrize("eps", [0.0, 0.05])
def test_against_brute_force(eps):
    m, x = random_bodies(60, 7)
    a, u = direct_sum(m, x, eps)
    b, ub = brute(m, x, eps)
    scale = max(math.sqrt(sum(c * c for c in bi)) for bi in b)
    for ai, bi in zip(a, b):
        for c, w in zip(ai, bi):
            assert abs(c - w) <= 1e-12 * scale
    assert u == pytest.approx(ub, rel=1e-12)


def test_total_force_is_zero():
    m, x = random_bodies(80, 3)
    a = accelerations(m, x)
    big = max(mi * math.sqrt(sum(c * c for c in ai)) for mi, ai in zip(m, a))
    for k in range(3):
        assert abs(sum(mi * ai[k] for mi, ai in zip(m, a))) <= 1e-12 * big * len(m)


def test_force_is_minus_gradient_of_energy():
    m, x = random_bodies(12, 11)
    eps, hstep = 0.1, 1e-6
    a = accelerations(m, x, eps)
    for i in range(len(m)):
        for k in range(3):
            xp = [list(p) for p in x]
            xm = [list(p) for p in x]
            xp[i][k] += hstep
            xm[i][k] -= hstep
            grad = (potential_energy(m, xp, eps) - potential_energy(m, xm, eps)) / (2 * hstep)
            assert -grad / m[i] == pytest.approx(a[i][k], rel=1e-6, abs=1e-8)


def test_circular_orbit_period_two_pi():
    # Two bodies of mass 1/2 at distance 1: G M = 1, relative speed 1, period 2 pi.
    m = [0.5, 0.5]
    x = [(-0.5, 0.0, 0.0), (0.5, 0.0, 0.0)]
    v = [(0.0, -0.5, 0.0), (0.0, 0.5, 0.0)]
    steps = 2000
    h = 2 * math.pi / steps
    x1, v1 = leapfrog(m, x, v, h, steps)
    for p, q in zip(x1, x):
        assert math.dist(p, q) < 1e-4
    e0 = kinetic_energy(m, v) + potential_energy(m, x)
    e1 = kinetic_energy(m, v1) + potential_energy(m, x1)
    assert e0 == pytest.approx(-0.125, rel=1e-15)
    assert abs(e1 - e0) / abs(e0) < 1e-10


def test_coincident_bodies_need_softening():
    m = [1.0, 1.0]
    x = [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)]
    with pytest.raises(ValueError):
        direct_sum(m, x)
    a, u = direct_sum(m, x, eps=0.5)
    assert a == [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
    assert u == pytest.approx(-2.0)

History

Von Hoerner published direct integrations of small star clusters on a digital computer in 1960. Aarseth wrote the NBODY codes from the 1960s on, with individual time steps, neighbor schemes and regularization, all built around a direct force sum (Aarseth 2003, Section 1.2). Hockney and Eastwood call the method the particle-particle (PP) method and compare it with mesh methods.

References

  1. Sverre J. Aarseth, Gravitational N-Body Simulations, Tools and Algorithms, Cambridge University Press, 2003, Sections 1.2 and 1.3 (history and basic concepts), Section 3.7 (ring scheme)
  2. Roger W. Hockney and James W. Eastwood, Computer Simulation Using Particles, Adam Hilger, 1988, the particle-particle (PP) method
  3. Sebastian von Hoerner, Die numerische Integration des N-Korper-Problemes fur Sternhaufen. I, Zeitschrift fur Astrophysik 50, 1960, 184-214, the first direct integrations of star clusters

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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