Algorithm Search⌘K

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
Properties
deterministicnot implicitone stepnot symmetricnot symplectic
Origin
Junichiro Makino, Sverre J. Aarseth, 1991

The fourth-order Hermite integrator advances the bodies of an N-body system with the acceleration a\mathbf{a} and its time derivative, the jerk j=a˙\mathbf{j} = \dot{\mathbf{a}}, both computed by direct summation. A step first predicts the positions and velocities by a Taylor series to the jerk, then computes a\mathbf{a} and j\mathbf{j} at the predicted state, fits a cubic in time through the two values of a\mathbf{a} and j\mathbf{j} (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 NN bodies, masses mim_i, positions xi\mathbf{x}_i and velocities vi\mathbf{v}_i, with G=1G = 1, a softening parameter ϵ≥0\epsilon \ge 0 and a time step hh. The output is an approximation of the state at time t+ht + h of the gravitational N-body problem. The jerk of body ii follows from the pair force by the chain rule: with rij=xj−xi\mathbf{r}_{ij} = \mathbf{x}_j - \mathbf{x}_i, vij=vj−vi\mathbf{v}_{ij} = \mathbf{v}_j - \mathbf{v}_i and r2=∣rij∣2+ϵ2r^2 = |\mathbf{r}_{ij}|^2 + \epsilon^2,

ai=G∑j≠imjrijr3,ji=G∑j≠imj(vijr3−3(rij⋅vij) rijr5).\mathbf{a}_i = G \sum_{j \ne i} m_j \frac{\mathbf{r}_{ij}}{r^3}, \qquad \mathbf{j}_i = G \sum_{j \ne i} m_j \left( \frac{\mathbf{v}_{ij}}{r^3} - \frac{3 (\mathbf{r}_{ij} \cdot \mathbf{v}_{ij})\, \mathbf{r}_{ij}}{r^5} \right).

The algorithm

  1. HERMITE-STEP(x, v, a, j, h) ▷ for each body i
  2. 1x_p ← x + v h + a h²/2 + j h³/6
  3. 2v_p ← v + a h + j h²/2
  4. 3(a_1, j_1) ← FORCE-AND-JERK(x_p, v_p)
  5. 4a⁽²⁾ ← (-6 (a - a_1) - h (4 j + 2 j_1)) / h²
  6. 5a⁽³⁾ ← (12 (a - a_1) + 6 h (j + j_1)) / h³
  7. 6x_1 ← x_p + a⁽²⁾ h⁴/24 + a⁽³⁾ h⁵/120
  8. 7v_1 ← v_p + a⁽²⁾ h³/6 + a⁽³⁾ h⁴/24
  9. 8return x_1, v_1, a_1, j_1
  10. FORCE-AND-JERK(x, v): for each pair i < j, add with opposite signs
  11. 9m r_ij / r³ to a
  12. 10m (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 Θ(N2)\Theta(N^2). Lines L4 and L5 compute the second and third derivatives of a\mathbf{a} at the start of the step from the cubic through a\mathbf{a}, j\mathbf{j}, a1\mathbf{a}_1 and j1\mathbf{j}_1, and lines L6 and L7 add the matching Taylor terms. In closed form, the corrector is

v1=v+h2(a+a1)+h212(j−j1),x1=x+vh+h220(7a+3a1)+h360(3j−2j1).\mathbf{v}_1 = \mathbf{v} + \frac{h}{2}(\mathbf{a} + \mathbf{a}_1) + \frac{h^2}{12}(\mathbf{j} - \mathbf{j}_1), \qquad \mathbf{x}_1 = \mathbf{x} + \mathbf{v} h + \frac{h^2}{20}(7\mathbf{a} + 3\mathbf{a}_1) + \frac{h^3}{60}(3\mathbf{j} - 2\mathbf{j}_1).

The values a(2)+ha(3)\mathbf{a}^{(2)} + h \mathbf{a}^{(3)} and a(3)\mathbf{a}^{(3)} at the end of the step feed the step criterion of Aarseth (2003, Section 2.3),

hnew=η ∣a∣∣a(2)∣+∣j∣2∣j∣∣a(3)∣+∣a(2)∣2,h_{\text{new}} = \sqrt{\eta \, \frac{|\mathbf{a}| |\mathbf{a}^{(2)}| + |\mathbf{j}|^2}{|\mathbf{j}| |\mathbf{a}^{(3)}| + |\mathbf{a}^{(2)}|^2}},

a rule of thumb with η\eta of about 0.010.01 to 0.020.02.

Example

Two bodies of mass 1/21/2 at (∓0.5,0,0)(\mp 0.5, 0, 0) with velocities (0,∓0.5,0)(0, \mp 0.5, 0) move on a circle of radius 0.50.5 with period 2π2\pi. Take one step of h=0.1h = 0.1 for body 2, which starts at (0.5,0)(0.5, 0) with v=(0,0.5)\mathbf{v} = (0, 0.5), a=(−0.5,0)\mathbf{a} = (-0.5, 0) and j=(0,−0.5)\mathbf{j} = (0, -0.5). The exact state at t=0.1t = 0.1 is 0.5(cos⁡0.1,sin⁡0.1)0.5(\cos 0.1, \sin 0.1) and 0.5(−sin⁡0.1,cos⁡0.1)0.5(-\sin 0.1, \cos 0.1).

quantity position velocity position error
predicted (L1, L2) (0.497500000, 0.049916667) (-0.050000000, 0.497500000) 2.1×10−62.1 \times 10^{-6}
corrected (L6, L7) (0.497502082, 0.049916708) (-0.049916771, 0.497502078) 3.9×10−103.9 \times 10^{-10}
exact (0.497502083, 0.049916708) (-0.049916708, 0.497502083)

The force at the predicted point is a1=(−0.497506,−0.049917)\mathbf{a}_1 = (-0.497506, -0.049917), close to the exact −0.5(cos⁡0.1,sin⁡0.1)-0.5(\cos 0.1, \sin 0.1). The corrector reduces the position error by a factor of more than 5000. Over one period of an orbit with eccentricity 0.50.5, the position error is 2.2×10−62.2 \times 10^{-6} with 400 steps and 1.3×10−71.3 \times 10^{-7} with 800 steps, a ratio of 16.8, close to the 24=162^4 = 16 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 p(t)\mathbf{p}(t) that matches a\mathbf{a} and j\mathbf{j} at t=0t = 0 and a1\mathbf{a}_1 and j1\mathbf{j}_1 at t=ht = h (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 124a(4)(ξ) t2(t−h)2\frac{1}{24} \mathbf{a}^{(4)}(\xi)\, t^2 (t - h)^2, whose integral over the step is O(h5)O(h^5). The predictor errors enter a1\mathbf{a}_1 at order h4h^4 and j1\mathbf{j}_1 at order h3h^3, and they are multiplied by hh and h2h^2 in the corrector. So the local error is O(h5)O(h^5), and the global error over a fixed time is O(h4)O(h^4) (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 a(t)\mathbf{a}(t) be the acceleration along the exact solution, and assume that it has four continuous derivatives on the step [0,h][0, h]. Write a0=a(0)\mathbf{a}_0 = \mathbf{a}(0), j0=a˙(0)\mathbf{j}_0 = \dot{\mathbf{a}}(0), and a1\mathbf{a}_1, j1\mathbf{j}_1 for the values that line L3 computes at the end of the step.

Lemma 1 (the jerk). For the pair term f=Gm r/s3/2\mathbf{f} = G m\, \mathbf{r} / s^{3/2} with r=xq−xp\mathbf{r} = \mathbf{x}_q - \mathbf{x}_p, u=vq−vp\mathbf{u} = \mathbf{v}_q - \mathbf{v}_p and s=∣r∣2+ϵ2s = |\mathbf{r}|^2 + \epsilon^2, the time derivative is f˙=Gm(u/s3/2−3(r⋅u) r/s5/2)\dot{\mathbf{f}} = G m \left( \mathbf{u} / s^{3/2} - 3 (\mathbf{r} \cdot \mathbf{u})\, \mathbf{r} / s^{5/2} \right), as in line L10.

Proof. r˙=u\dot{\mathbf{r}} = \mathbf{u} and s˙=2 r⋅u\dot{s} = 2\, \mathbf{r} \cdot \mathbf{u}, so ddts−3/2=−32s−5/2⋅2 r⋅u\frac{d}{dt} s^{-3/2} = -\frac{3}{2} s^{-5/2} \cdot 2\, \mathbf{r} \cdot \mathbf{u}. Apply the product rule. □\square

Lemma 2 (the fitted derivatives). There is exactly one cubic p(t)=a0+j0t+a(2)t2/2+a(3)t3/6\mathbf{p}(t) = \mathbf{a}_0 + \mathbf{j}_0 t + \mathbf{a}^{(2)} t^2 / 2 + \mathbf{a}^{(3)} t^3 / 6 with p(h)=a1\mathbf{p}(h) = \mathbf{a}_1 and p˙(h)=j1\dot{\mathbf{p}}(h) = \mathbf{j}_1, and its coefficients are those of lines L4 and L5:

a(2)=−6(a0−a1)−h(4j0+2j1)h2,a(3)=12(a0−a1)+6h(j0+j1)h3.\mathbf{a}^{(2)} = \frac{-6(\mathbf{a}_0 - \mathbf{a}_1) - h(4\mathbf{j}_0 + 2\mathbf{j}_1)}{h^2}, \qquad \mathbf{a}^{(3)} = \frac{12(\mathbf{a}_0 - \mathbf{a}_1) + 6h(\mathbf{j}_0 + \mathbf{j}_1)}{h^3}.

Proof. The two conditions are the linear system h22a(2)+h36a(3)=a1−a0−hj0\frac{h^2}{2} \mathbf{a}^{(2)} + \frac{h^3}{6} \mathbf{a}^{(3)} = \mathbf{a}_1 - \mathbf{a}_0 - h \mathbf{j}_0 and ha(2)+h22a(3)=j1−j0h \mathbf{a}^{(2)} + \frac{h^2}{2} \mathbf{a}^{(3)} = \mathbf{j}_1 - \mathbf{j}_0. Its determinant is h44−h46=h412≠0\frac{h^4}{4} - \frac{h^4}{6} = \frac{h^4}{12} \ne 0, so the solution is unique. Substituting the formulas: the second equation gives −6Δ−4hj0−2hj1+6Δ+3h(j0+j1)h=j1−j0\frac{-6\Delta - 4h\mathbf{j}_0 - 2h\mathbf{j}_1 + 6\Delta + 3h(\mathbf{j}_0 + \mathbf{j}_1)}{h} = \mathbf{j}_1 - \mathbf{j}_0, with Δ=a0−a1\Delta = \mathbf{a}_0 - \mathbf{a}_1; the first gives −3Δ−h(2j0+j1)+2Δ+h(j0+j1)=−Δ−hj0-3\Delta - h(2\mathbf{j}_0 + \mathbf{j}_1) + 2\Delta + h(\mathbf{j}_0 + \mathbf{j}_1) = -\Delta - h\mathbf{j}_0. Both hold. □\square

Lemma 3 (the corrector). Lines L1, L2, L6 and L7 give

v1=v0+∫0hp(t) dt=v0+h2(a0+a1)+h212(j0−j1),\mathbf{v}_1 = \mathbf{v}_0 + \int_0^h \mathbf{p}(t)\, dt = \mathbf{v}_0 + \frac{h}{2}(\mathbf{a}_0 + \mathbf{a}_1) + \frac{h^2}{12}(\mathbf{j}_0 - \mathbf{j}_1),
x1=x0+v0h+∫0h(h−t) p(t) dt=x0+v0h+h220(7a0+3a1)+h360(3j0−2j1).\mathbf{x}_1 = \mathbf{x}_0 + \mathbf{v}_0 h + \int_0^h (h - t)\, \mathbf{p}(t)\, dt = \mathbf{x}_0 + \mathbf{v}_0 h + \frac{h^2}{20}(7\mathbf{a}_0 + 3\mathbf{a}_1) + \frac{h^3}{60}(3\mathbf{j}_0 - 2\mathbf{j}_1).

Proof. Lines L2 and L7 add up to v0+a0h+j0h2/2+a(2)h3/6+a(3)h4/24\mathbf{v}_0 + \mathbf{a}_0 h + \mathbf{j}_0 h^2/2 + \mathbf{a}^{(2)} h^3/6 + \mathbf{a}^{(3)} h^4/24, which is the integral of the cubic term by term. Lines L1 and L6 add up to x0+v0h\mathbf{x}_0 + \mathbf{v}_0 h plus the terms hn+2/(n+2)!h^{n+2}/(n+2)! times the coefficients of p\mathbf{p}, which is the double integral. Substituting Lemma 2 and collecting the terms in a0\mathbf{a}_0, a1\mathbf{a}_1, j0\mathbf{j}_0 and j1\mathbf{j}_1 gives the closed forms. For example, the coefficient of h2h^2 in x1\mathbf{x}_1 is 12a0−14Δ+110Δ=720a0+320a1\frac{1}{2}\mathbf{a}_0 - \frac{1}{4}\Delta + \frac{1}{10}\Delta = \frac{7}{20}\mathbf{a}_0 + \frac{3}{20}\mathbf{a}_1. □\square

Theorem (local and global order). Assume that the force is smooth with bounded derivatives near the solution. Then one step has local errors O(h5)O(h^5) in velocity and position, and over a fixed time TT with T/hT/h steps the error is O(h4)O(h^4).

Proof. First assume exact end values a1=a(h)\mathbf{a}_1 = \mathbf{a}(h) and j1=a˙(h)\mathbf{j}_1 = \dot{\mathbf{a}}(h). Then p\mathbf{p} is the cubic Hermite interpolant of a\mathbf{a} at 00 and hh, with the error a(t)−p(t)=a(4)(ξt)24t2(t−h)2\mathbf{a}(t) - \mathbf{p}(t) = \frac{\mathbf{a}^{(4)}(\xi_t)}{24} t^2 (t - h)^2 in each coordinate. Since ∫0ht2(t−h)2 dt=h5/30\int_0^h t^2 (t-h)^2\, dt = h^5 / 30, Lemma 3 gives a velocity error of at most h5720max⁡∣a(4)∣\frac{h^5}{720} \max |\mathbf{a}^{(4)}| and a position error of O(h6)O(h^6), because the exact solution satisfies the same integral identities with a\mathbf{a} in place of p\mathbf{p}.

The predictor of lines L1 and L2 is the Taylor polynomial to the jerk, so xp−x(h)=O(h4)\mathbf{x}_p - \mathbf{x}(h) = O(h^4) and vp−v(h)=O(h3)\mathbf{v}_p - \mathbf{v}(h) = O(h^3). The acceleration depends on positions only, so a1−a(h)=O(h4)\mathbf{a}_1 - \mathbf{a}(h) = O(h^4); the jerk depends on positions and velocities, so j1−a˙(h)=O(h3)\mathbf{j}_1 - \dot{\mathbf{a}}(h) = O(h^3). In the closed forms of Lemma 3, a1\mathbf{a}_1 enters with the factor hh and j1\mathbf{j}_1 with the factor h2h^2, so these errors add O(h5)O(h^5) to v1\mathbf{v}_1 and O(h5)O(h^5) or less to x1\mathbf{x}_1. So the local error is O(h5)O(h^5).

The step map is Lipschitz in (x,v)(\mathbf{x}, \mathbf{v}) with constant 1+O(h)1 + O(h), 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 O(h5)O(h^5) into a global error O(h4)O(h^4) over a fixed time. □\square

Remarks. The momentum is conserved up to rounding, because each pair adds opposite terms to a\mathbf{a} and j\mathbf{j} (lines L9 and L10), so the update of the total momentum ∑mv\sum m \mathbf{v} 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 N(N−1)/2N(N-1)/2 pairs of about twice the cost of a pair of the force alone. So a step costs Θ(N2)\Theta(N^2), and the extra space is Θ(N)\Theta(N) for the predicted state and the new a\mathbf{a} and j\mathbf{j}. With block time steps, a step of the bodies of one block of nn bodies costs Θ(nN)\Theta(n N), plus Θ(N)\Theta(N) 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 0.50.5 with 400 steps per orbit, the relative energy error ∣E(t)−E(0)∣/∣E(0)∣|E(t) - E(0)| / |E(0)| is 1.5×10−71.5 \times 10^{-7} after one orbit and 1.5×10−61.5 \times 10^{-6} after ten (measurement). The total momentum is conserved up to rounding.
  • Gives the step criterion for free. The fitted a(2)\mathbf{a}^{(2)} and a(3)\mathbf{a}^{(3)} 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 a1\mathbf{a}_1 and j1\mathbf{j}_1 at the predicted state by O(h4)O(h^4). The scheme keeps a1\mathbf{a}_1 and j1\mathbf{j}_1 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 vj−vi\mathbf{v}_j - \mathbf{v}_i when the relative position is xj−xi\mathbf{x}_j - \mathbf{x}_i. 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 a\mathbf{a} and j\mathbf{j} 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 ϵ=0\epsilon = 0. 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.

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

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

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