Algorithmadvanced
Fourth-order Hermite integrator
Also called Hermite predictor-corrector scheme.
Predicts positions from the force and its time derivative, then corrects with a Hermite interpolant; the standard integrator of direct N-body codes.
- Time
- Θ(N^2) step
- Space
- Θ(N) extra
- Where
- N = the number of bodies
- Model
- Real RAM
- Properties
- deterministicnot implicitone stepnot symmetricnot symplectic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Junichiro Makino, Sverre J. Aarseth, 1991
The fourth-order Hermite integrator advances the bodies of an N-body system with the acceleration and its time derivative, the jerk , both computed by direct summation. A step first predicts the positions and velocities by a Taylor series to the jerk, then computes and at the predicted state, fits a cubic in time through the two values of and (Hermite interpolation), and corrects the step with the integral of that cubic. It needs one force evaluation per step, like leapfrog, but it is fourth order, and it gives the higher derivatives that a step criterion needs. With individual block time steps it is the standard integrator of direct codes for star clusters, such as the NBODY codes and GRAPE and GPU codes. It is not symplectic, so its energy error drifts slowly.
In plain words
To move a body forward in time, you can use how fast it moves and how its speed changes. This method also uses how the pull on it changes from moment to moment. With these, it makes a first guess of where each body will be after a short time.
Then it works out the pulls again at the guessed places, and how fast they change there. Now it knows the pull and its rate of change at the start and at the end of the step. It draws the smoothest curve that fits all four of these, and uses that curve to correct the guess. One new set of pulls per step is enough, and halving the step makes the error about sixteen times smaller.
The problem
The input is the state of bodies, masses , positions and velocities , with , a softening parameter and a time step . The output is an approximation of the state at time of the gravitational N-body problem. The jerk of body follows from the pair force by the chain rule: with , and ,
The algorithm
HERMITE-STEP(x, v, a, j, h) ▷ for each body i- 1
x_p ← x + v h + a h²/2 + j h³/6 - 2
v_p ← v + a h + j h²/2 - 3
(a_1, j_1) ← FORCE-AND-JERK(x_p, v_p) - 4
a⁽²⁾ ← (-6 (a - a_1) - h (4 j + 2 j_1)) / h² - 5
a⁽³⁾ ← (12 (a - a_1) + 6 h (j + j_1)) / h³ - 6
x_1 ← x_p + a⁽²⁾ h⁴/24 + a⁽³⁾ h⁵/120 - 7
v_1 ← v_p + a⁽²⁾ h³/6 + a⁽³⁾ h⁴/24 - 8
return x_1, v_1, a_1, j_1 FORCE-AND-JERK(x, v): for each pair i < j, add with opposite signs- 9
m r_ij / r³ to a - 10
m (v_ij / r³ - 3 (r_ij · v_ij) r_ij / r⁵) to j
Lines L1 and L2 are the predictor. Line L3 is the only force evaluation, of cost . Lines L4 and L5 compute the second and third derivatives of at the start of the step from the cubic through , , and , and lines L6 and L7 add the matching Taylor terms. In closed form, the corrector is
The values and at the end of the step feed the step criterion of Aarseth (2003, Section 2.3),
a rule of thumb with of about to .
Example
Two bodies of mass at with velocities move on a circle of radius with period . Take one step of for body 2, which starts at with , and . The exact state at is and .
| quantity | position | velocity | position error |
|---|---|---|---|
| predicted (L1, L2) | (0.497500000, 0.049916667) | (-0.050000000, 0.497500000) | |
| corrected (L6, L7) | (0.497502082, 0.049916708) | (-0.049916771, 0.497502078) | |
| exact | (0.497502083, 0.049916708) | (-0.049916708, 0.497502083) |
The force at the predicted point is , close to the exact . The corrector reduces the position error by a factor of more than 5000. Over one period of an orbit with eccentricity , the position error is with 400 steps and with 800 steps, a ratio of 16.8, close to the of a fourth-order method (measurement with this implementation).
Correctness
The jerk formula is the time derivative of the pair force (Lemma 1 of the proof file). Lines L4 and L5 give the unique cubic that matches and at and and at (Lemma 2), and lines L6 and L7 integrate it once and twice (Lemma 3). The cubic Hermite interpolant of a smooth function has the error , whose integral over the step is . The predictor errors enter at order and at order , and they are multiplied by and in the corrector. So the local error is , and the global error over a fixed time is (theorem, for a smooth force).
Proof: The Hermite corrector integrates the cubic Hermite interpolant of the acceleration, and the scheme is fourth orderfull
We write one body and suppress its index; the statements hold for each body and each coordinate. Let be the acceleration along the exact solution, and assume that it has four continuous derivatives on the step . Write , , and , for the values that line L3 computes at the end of the step.
Lemma 1 (the jerk). For the pair term with , and , the time derivative is , as in line L10.
Proof. and , so . Apply the product rule.
Lemma 2 (the fitted derivatives). There is exactly one cubic with and , and its coefficients are those of lines L4 and L5:
Proof. The two conditions are the linear system and . Its determinant is , so the solution is unique. Substituting the formulas: the second equation gives , with ; the first gives . Both hold.
Lemma 3 (the corrector). Lines L1, L2, L6 and L7 give
Proof. Lines L2 and L7 add up to , which is the integral of the cubic term by term. Lines L1 and L6 add up to plus the terms times the coefficients of , which is the double integral. Substituting Lemma 2 and collecting the terms in , , and gives the closed forms. For example, the coefficient of in is .
Theorem (local and global order). Assume that the force is smooth with bounded derivatives near the solution. Then one step has local errors in velocity and position, and over a fixed time with steps the error is .
Proof. First assume exact end values and . Then is the cubic Hermite interpolant of at and , with the error in each coordinate. Since , Lemma 3 gives a velocity error of at most and a position error of , because the exact solution satisfies the same integral identities with in place of .
The predictor of lines L1 and L2 is the Taylor polynomial to the jerk, so and . The acceleration depends on positions only, so ; the jerk depends on positions and velocities, so . In the closed forms of Lemma 3, enters with the factor and with the factor , so these errors add to and or less to . So the local error is .
The step map is Lipschitz in with constant , since it is built from the force and its derivative. The standard argument for one-step methods (see global error) then turns a local error into a global error over a fixed time.
Remarks. The momentum is conserved up to rounding, because each pair adds opposite terms to and (lines L9 and L10), so the update of the total momentum by Lemma 3 is zero. The energy is not conserved exactly: the scheme is not symplectic, and for a fixed step its energy error grows linearly in time.
Complexity
In the real RAM model, one step evaluates the force and the jerk once, with pairs of about twice the cost of a pair of the force alone. So a step costs , and the extra space is for the predicted state and the new and . With block time steps, a step of the bodies of one block of bodies costs , plus for predicting all bodies.
Properties
- Fourth order, one force evaluation per step. The classical Runge-Kutta method of order 4 needs four.
- Self-starting. Only the state and the force at one time are needed, unlike multistep schemes. This is what makes individual time steps simple.
- Not symplectic and not time-symmetric. For a fixed step the energy error drifts; for the orbit of eccentricity with 400 steps per orbit, the relative energy error is after one orbit and after ten (measurement). The total momentum is conserved up to rounding.
- Gives the step criterion for free. The fitted and are the inputs of the Aarseth criterion.
Variants and improvements
- Iterated corrector. Repeat lines L3 to L7 with the corrected state. With two or more iterations the scheme approaches the implicit time-symmetric Hermite scheme, whose energy error does not drift for periodic orbits (Makino, Hut, Kaplan and Saygin 2006).
- Individual and block time steps. Each body has its own step, a power of 2 fraction of a base step; at each time only the bodies of one block are corrected, and all others are only predicted (block time steps).
- Ahmad-Cohen neighbor scheme. Split the force into the part of near neighbors, corrected with a small step, and the part of distant bodies, with a larger step (Makino and Aarseth 1992).
- Higher orders. Sixth- and eighth-order Hermite schemes also use the snap and the crackle of each pair.
- Regularized pairs. Close binaries are taken out and integrated with Kustaanheimo-Stiefel regularization, and the Hermite scheme moves their center of mass.
When to use it
Use the Hermite scheme for collisional systems integrated with direct summation: star clusters, galactic nuclei and systems with up to about a million bodies on GPUs, where accuracy per force evaluation matters and steps differ widely between bodies. For collisionless systems with softening and a shared step, use leapfrog, which is symplectic and cheaper. For planetary systems with one dominant mass, use the Wisdom-Holman map.
Pitfalls
- Recomputing the force after the corrector. The force and the jerk at the corrected state differ from and at the predicted state by . The scheme keeps and for the next step; a second evaluation doubles the cost and is the iterated variant, not the basic scheme.
- Jerk with the wrong sign. The relative velocity must be when the relative position is . Test the jerk against a finite difference of the acceleration.
- A step that grows too fast. A step chosen only from the criterion can double many times in one step at the start; limit the growth, or start with a criterion that uses and only.
- Expecting bounded energy errors. The scheme is not symplectic. For long integrations at a fixed step, the drift grows linearly; use the time-symmetric variant or a symplectic method if that matters.
- Close encounters. The step goes to zero as two bodies approach with . Regularize the pair.
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/hermite-n-body-integrator/. The authors are listed in prov/M1QQTQ.jsonl.
"""Fourth-order Hermite predictor-corrector integrator for the N-body problem.
The force and its time derivative (the jerk) are computed by direct
summation. A step predicts positions and velocities with a Taylor series in
the acceleration and the jerk, evaluates the force and the jerk at the
predicted state, fits the second and third derivatives of the acceleration
from the two values of the acceleration and of the jerk (Hermite
interpolation), and corrects. Plummer softening eps; G = 1 unless given.
"""
import math
from typing import Sequence
Vec = Sequence[float]
State = list[list[float]]
def acc_jerk(m: Sequence[float], x: Sequence[Vec], v: Sequence[Vec], eps: float = 0.0,
G: float = 1.0) -> tuple[State, State]:
"""Accelerations and jerks of all bodies, by summation over pairs."""
n, dim = len(m), len(x[0])
a = [[0.0] * dim for _ in range(n)]
j = [[0.0] * dim for _ in range(n)]
e2 = eps * eps
for p in range(n - 1):
for q in range(p + 1, n):
dx = [x[q][k] - x[p][k] for k in range(dim)]
dv = [v[q][k] - v[p][k] for k in range(dim)]
r2 = sum(c * c for c in dx) + e2
rinv3 = G / (r2 * math.sqrt(r2))
rv = 3.0 * sum(dx[k] * dv[k] for k in range(dim)) / r2
for k in range(dim):
fa = rinv3 * dx[k] # @line L9
fj = rinv3 * (dv[k] - rv * dx[k]) # @line L10
a[p][k] += m[q] * fa
a[q][k] -= m[p] * fa
j[p][k] += m[q] * fj
j[q][k] -= m[p] * fj
return a, j
def hermite_step(m: Sequence[float], x: State, v: State, a: State, j: State, h: float,
eps: float = 0.0, G: float = 1.0):
"""One step of size h. Returns x1, v1, a1, j1 and the second and third
derivatives of the acceleration at the end of the step (for the step criterion)."""
n, dim = len(m), len(x[0])
h2, h3 = h * h, h * h * h
xp = [[x[i][k] + v[i][k] * h + a[i][k] * h2 / 2 + j[i][k] * h3 / 6 for k in range(dim)] for i in range(n)] # @line L1
vp = [[v[i][k] + a[i][k] * h + j[i][k] * h2 / 2 for k in range(dim)] for i in range(n)] # @line L2
a1, j1 = acc_jerk(m, xp, vp, eps, G) # @line L3
x1, v1, s1, c1 = [], [], [], []
for i in range(n):
xi, vi, si, ci = [], [], [], []
for k in range(dim):
da = a[i][k] - a1[i][k]
snap = (-6.0 * da - h * (4.0 * j[i][k] + 2.0 * j1[i][k])) / h2 # @line L4
crackle = (12.0 * da + 6.0 * h * (j[i][k] + j1[i][k])) / h3 # @line L5
xi.append(xp[i][k] + snap * h2 * h2 / 24 + crackle * h2 * h3 / 120) # @line L6
vi.append(vp[i][k] + snap * h3 / 6 + crackle * h2 * h2 / 24) # @line L7
si.append(snap + crackle * h)
ci.append(crackle)
x1.append(xi)
v1.append(vi)
s1.append(si)
c1.append(ci)
return x1, v1, a1, j1, s1, c1 # @line L8
def integrate(m: Sequence[float], x: Sequence[Vec], v: Sequence[Vec], h: float, steps: int,
eps: float = 0.0, G: float = 1.0) -> tuple[State, State]:
"""Shared constant step h for all bodies."""
x = [list(p) for p in x]
v = [list(q) for q in v]
a, j = acc_jerk(m, x, v, eps, G)
for _ in range(steps):
x, v, a, j, _, _ = hermite_step(m, x, v, a, j, h, eps, G)
return x, v
def aarseth_step(a: Vec, j: Vec, snap: Vec, crackle: Vec, eta: float = 0.02) -> float:
"""Aarseth's step criterion sqrt(eta (|a||a2| + |j|^2) / (|j||a3| + |a2|^2))."""
na, nj, ns, nc = (math.hypot(*u) for u in (a, j, snap, crackle))
return math.sqrt(eta * (na * ns + nj * nj) / (nj * nc + ns * ns))
def energy(m: Sequence[float], x: Sequence[Vec], v: Sequence[Vec], eps: float = 0.0, G: float = 1.0) -> float:
n = len(m)
k = 0.5 * sum(m[i] * sum(c * c for c in v[i]) for i in range(n))
u = -sum(G * m[i] * m[q] / math.sqrt(sum((x[i][d] - x[q][d]) ** 2 for d in range(len(x[i]))) + eps * eps)
for i in range(n) for q in range(i + 1, n))
return k + u
test_hermite_n_body_integrator.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hermite-n-body-integrator/. The authors are listed in prov/M1QQTQ.jsonl.
import math
import random
import pytest
from hermite_n_body_integrator import aarseth_step, acc_jerk, energy, hermite_step, integrate
def kepler_pair(e):
"""Two bodies of mass 1/2 at apocenter of an orbit with semi-major axis 1 and eccentricity e.
G M = 1, so the period is 2 pi."""
r = 1.0 + e
vrel = math.sqrt((1.0 - e) / (1.0 + e))
m = [0.5, 0.5]
x = [(-r / 2, 0.0, 0.0), (r / 2, 0.0, 0.0)]
v = [(0.0, -vrel / 2, 0.0), (0.0, vrel / 2, 0.0)]
return m, x, v
def period_error(e, steps):
m, x, v = kepler_pair(e)
x1, _ = integrate(m, x, v, 2 * math.pi / steps, steps)
return math.dist(x1[1], x[1])
def test_jerk_is_time_derivative_of_acceleration():
rng = random.Random(2)
m = [rng.uniform(0.5, 1.5) for _ in range(8)]
x = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(8)]
v = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(8)]
_, jerk = acc_jerk(m, x, v, eps=0.05)
dt = 1e-5
ap, _ = acc_jerk(m, [[x[i][k] + v[i][k] * dt for k in range(3)] for i in range(8)], v, eps=0.05)
am, _ = acc_jerk(m, [[x[i][k] - v[i][k] * dt for k in range(3)] for i in range(8)], v, eps=0.05)
for i in range(8):
for k in range(3):
assert (ap[i][k] - am[i][k]) / (2 * dt) == pytest.approx(jerk[i][k], rel=1e-6, abs=1e-7)
def test_fourth_order_on_eccentric_kepler_orbit():
e1 = period_error(0.5, 400)
e2 = period_error(0.5, 800)
assert e1 < 1e-4
assert 12 < e1 / e2 < 20 # 2^4 = 16 for a fourth-order method
def test_period_and_energy_on_circular_orbit():
m, x, v = kepler_pair(0.0)
x1, v1 = integrate(m, x, v, 2 * math.pi / 200, 200)
assert math.dist(x1[1], x[1]) < 1e-6
e0 = energy(m, x, v)
assert e0 == pytest.approx(-0.125, rel=1e-15)
assert abs(energy(m, x1, v1) - e0) / abs(e0) < 1e-8
def test_momentum_is_conserved():
rng = random.Random(5)
n = 6
m = [rng.uniform(0.5, 1.5) for _ in range(n)]
x = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(n)]
v = [[rng.uniform(-0.3, 0.3) for _ in range(3)] for _ in range(n)]
p0 = [sum(m[i] * v[i][k] for i in range(n)) for k in range(3)]
x1, v1 = integrate(m, x, v, 1e-3, 300, eps=0.05)
for k in range(3):
assert sum(m[i] * v1[i][k] for i in range(n)) == pytest.approx(p0[k], abs=1e-12)
def test_three_bodies_against_fine_reference():
rng = random.Random(9)
m = [1.0, 0.8, 0.6]
x = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(3)]
v = [[rng.uniform(-0.3, 0.3) for _ in range(3)] for _ in range(3)]
ref, _ = integrate(m, x, v, 1e-3 / 4, 4000, eps=0.1)
coarse, _ = integrate(m, x, v, 2e-3, 500, eps=0.1)
fine, _ = integrate(m, x, v, 1e-3, 1000, eps=0.1)
err_coarse = max(math.dist(p, q) for p, q in zip(coarse, ref))
err_fine = max(math.dist(p, q) for p, q in zip(fine, ref))
assert err_fine < 1e-6
assert err_coarse / err_fine > 12 # at least fourth order
def test_aarseth_step_on_circular_orbit():
# On a circular orbit with angular frequency 1, |j| = |a|, |a2| = |a| and |a3| = |a|,
# so the criterion gives sqrt(eta).
m, x, v = kepler_pair(0.0)
x = [list(p) for p in x]
v = [list(q) for q in v]
a, j = acc_jerk(m, x, v)
h = 2 * math.pi / 1000
_, _, a1, j1, snap, crackle = hermite_step(m, x, v, a, j, h)
assert aarseth_step(a1[0], j1[0], snap[0], crackle[0], eta=0.01) == pytest.approx(0.1, rel=1e-3)
History
Earlier direct codes of Aarseth used a fourth-order scheme that fitted a polynomial through the forces at four past times, with divided differences. Makino (1991) proposed computing the jerk directly by summation and fitting the cubic with the values at only two times, which gives a self-starting scheme with larger steps for the same accuracy, and a new step criterion. Makino and Aarseth (1992) combined it with individual steps and the Ahmad-Cohen neighbor scheme. The scheme became the standard of the NBODY codes and of the GRAPE special-purpose computers.
References
- Junichiro Makino, Optimal order and time-step criterion for Aarseth-type N-body integrators, Astrophysical Journal 369, 1991, 200-212, the Hermite scheme with the direct computation of the force derivative and the step criterion
- Junichiro Makino and Sverre J. Aarseth, On a Hermite integrator with Ahmad-Cohen scheme for gravitational many-body problems, Publications of the Astronomical Society of Japan 44(2), 1992, 141-151, the fourth-order Hermite scheme with individual and neighbor time steps
- Sverre J. Aarseth, Gravitational N-Body Simulations, Tools and Algorithms, Cambridge University Press, 2003, Section 2.3 (individual time steps and the step criterion), Section 2.5 (Hermite scheme), Appendix H (Hermite integration method)
- Junichiro Makino, Piet Hut, Murat Kaplan and Hasan Saygin, A time-symmetric block time-step algorithm for N-body simulations, New Astronomy 12(2), 2006, 124-133, the time-symmetric form of the Hermite scheme
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.
| 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 M1QQTQ Edit this page History Report an error Markdown