Astronomy and Space Exploration ES

Projects / Higher Education

Higher Education ⏱ 6 weeks · independent work of 5 to 6 h per week + 1 h of tutoring under review

Your Own N-Body Integrator

“Why does a second-order symplectic integrator conserve energy over millions of steps while a fourth-order one does not?”

Program RK4 and leapfrog from scratch for the gravitational N-body problem, validate them with the two-body problem, the figure-eight and Burrau's Pythagorean problem, and measure the energy drift, the order of convergence and the chaotic sensitivity.

Goal

Implement and verify RK4 and leapfrog (kick-drift-kick) integrators for N bodies, demonstrate empirically their orders of convergence and their behavior in energy and angular momentum, reproduce reference solutions and estimate a finite-time Lyapunov exponent.

Final product

Your own library (Python or TypeScript) with automated tests, a notebook or report with the convergence, energy-drift and angular-momentum graphs, the figure-eight and Burrau reproduced, and a critical analysis comparing with the portal's src/lib/math/nbody.ts.

Materials

  • Computer with Python (NumPy, Matplotlib) or Node/TypeScript with Vitest
  • The portal's reference code: src/lib/math/integrators.ts and src/lib/math/nbody.ts, with their tests
  • Initial conditions of the figure-eight (Chenciner & Montgomery 2000; Simó 2002) and of the Pythagorean problem (Szebehely & Peters 1967), reproduced in the lesson
  • Access to the portal's N bodies simulator for comparison

Math it uses

  • N-body Hamiltonian; first integrals: energy, linear and angular momentum
  • Runge–Kutta (RK4) and splitting (leapfrog / Störmer–Verlet) methods; local and global order
  • Symplectic integrators and the modified Hamiltonian (backward error analysis)
  • Finite-time Lyapunov exponent (Benettin's method); regularization of close encounters

On the portal

Lessons and articles: Simulators:

Project phases

Week 1 — The problem and the first integrals

  1. Write the Hamiltonian H=∑ipi22mi−∑i<jGmimj∣ri−rj∣H = \sum_i \dfrac{p_i^2}{2m_i} - \sum_{i<j}\dfrac{G m_i m_j}{|\mathbf r_i - \mathbf r_j|} and derive the equations of motion. Implement aceleraciones(masas, posiciones) in O(N2)O(N^2) and verify Newton’s third law: ∑imiai=0\sum_i m_i \mathbf a_i = 0 to machine precision.
  2. Implement energia, momentoLineal, momentoAngular and tests that they are zero or constant in simple configurations (two equal masses at rest; center of mass at the origin).
  3. Choose units: G=1G = 1 for the reference problems; for the Solar System, au, years and solar masses (G=4π2G = 4\pi^2).

Week 2 — RK4

  1. Implement a generic RK4 for y˙=f(t,y)\dot{\mathbf y} = \mathbf f(t, \mathbf y) with the state y=(r1,…,rN,v1,…,vN)\mathbf y = (\mathbf r_1,\dots,\mathbf r_N,\mathbf v_1,\dots,\mathbf v_N) (lesson 2).
  2. Convergence test with the circular two-body problem (μ=1\mu = 1, r=1r = 1, v=1v = 1, T=2πT = 2\pi): position error after one period for h=T/50,T/100,T/200,T/400h = T/50, T/100, T/200, T/400. The log–log slope must be ≈ 4.
  3. Energy drift: integrate 1 000 periods with h=T/100h = T/100 and plot ΔE/E0\Delta E/E_0 against tt: it grows secularly (linearly). Measure the slope.
  4. Optional: RK45 with adaptive step and tolerance; compare the number of evaluations of f\mathbf f for the same error.

Week 3 — Leapfrog (kick-drift-kick)

  1. Implement the KDK leapfrog: v1/2=v0+h2a0\mathbf v_{1/2} = \mathbf v_0 + \tfrac h2\mathbf a_0; r1=r0+hv1/2\mathbf r_1 = \mathbf r_0 + h\mathbf v_{1/2}; v1=v1/2+h2a1\mathbf v_1 = \mathbf v_{1/2} + \tfrac h2\mathbf a_1. Check that it is second order (slope ≈ 2) and time-reversible: integrating nn steps with hh and nn with −h-h returns the initial state to round-off precision.
  2. Energy drift over 1 000 periods: ΔE/E0\Delta E/E_0 oscillates with no secular drift. Explain the result with the modified Hamiltonian H~=H+h2H2+…\tilde H = H + h^2 H_2 + \dots (lesson 1).
  3. Angular momentum: show that the leapfrog conserves it exactly for central forces (to round-off) and check it; RK4 does not.
  4. Fourth-order Yoshida composition from three leapfrogs; verify order 4 and that it still has no energy drift.

Week 4 — Reference solutions

  1. Figure-eight: with Simó’s conditions, integrate one period T=6.3259T = 6.3259 with h=T/6000h = T/6000 and verify that the state returns to the initial one with error <10−4< 10^{-4} and that E≈−1.28714E \approx -1.28714, L=0\mathbf L = 0. Plot the trajectory and compare it with the simulator N bodies.
  2. Burrau’s Pythagorean problem: integrate up to t=70t = 70 with fixed-step leapfrog and with RK4; observe the spikes of ∣ΔE/E0∣|\Delta E/E_0| at the close encounters and the ejection of mass 3 around t≈59.4t \approx 59.4. Try h=10−3,10−4,10−5h = 10^{-3}, 10^{-4}, 10^{-5}: does the escape time change? Is that a failure of the integrator or a property of the system?
  3. Add a softening ϵ\epsilon (∣r∣2→∣r∣2+ϵ2|\mathbf r|^2 \to |\mathbf r|^2 + \epsilon^2) and discuss how much it alters the physics; alternatively, implement block variable time steps.

Week 5 — Chaos

  1. Implement Benettin’s method: integrate two trajectories separated by δ0=10−8\delta_0 = 10^{-8}, renormalize every τ\tau and accumulate ln⁡(δ/δ0)\ln(\delta/\delta_0). Estimate λ\lambda for Burrau on [0,20][0, 20] (the lesson reports λ≈1\lambda \approx 1 with h=10−4h = 10^{-4}) and for the circular two-body orbit (it should tend to 0 like ln⁡t/t\ln t / t).
  2. Plot ln⁡δ(t)\ln\delta(t) for the figure-eight with a perturbation of 10−610^{-6}: slow growth (Simó’s linear stability) versus the exponential growth of Burrau.
  3. Discuss why the finite-time exponent depends on hh, on δ0\delta_0 and on τ\tau, and how to report it honestly.

Week 6 — Report and comparison

  1. Report with: equations, description of the methods, convergence graphs (measured slopes), energy and angular-momentum drift, figure-eight and Burrau, Lyapunov, and a table of computational cost (force evaluations per unit of error).
  2. Compare your implementation with the portal’s src/lib/math/nbody.ts: run your tests against both and document the differences (if you find a bug in the portal, report it with a minimal case).
  3. A 10-minute presentation with a live demonstration: the panel chooses hh and the student shows the energy drift of each method.

Mathematics in the project

  • Hamilton’s equations: r˙i=∂H/∂pi\dot{\mathbf r}_i = \partial H/\partial\mathbf p_i, p˙i=−∂H/∂ri\dot{\mathbf p}_i = -\partial H/\partial\mathbf r_i.
  • Order of a method: global error ∼hp\sim h^p; it is measured by the slope of log⁡(error)\log(\text{error}) against log⁡h\log h.
  • Symplecticity: the leapfrog preserves the 2-form ∑dri∧dpi\sum d\mathbf r_i \wedge d\mathbf p_i; by backward error analysis it solves exactly a modified Hamiltonian H~\tilde H close to HH, which bounds ΔE\Delta E over times exponentially long in 1/h1/h.
  • Angular momentum in leapfrog: Ln+1−Ln=h2 rn+1×an+1+⋯=0\mathbf L_{n+1} - \mathbf L_n = \tfrac h2\,\mathbf r_{n+1}\times\mathbf a_{n+1} + \dots = 0 for central forces because r×a=0\mathbf r \times \mathbf a = 0.
  • Lyapunov: λ=lim⁡t→∞1tln⁡∣δ(t)∣∣δ0∣\lambda = \lim_{t\to\infty} \dfrac1t \ln\dfrac{|\delta(t)|}{|\delta_0|}; in practice, the average of Benettin renormalizations.

Assessment rubric

CriterionInsufficientSatisfactoryGoodOutstanding
Implementation and testsCode without tests or incorrectCorrect RK4 and leapfrog with conservation testsTests of order, reversibility and references (figure-eight, Burrau)Documented library, Yoshida or adaptive step, comparison with the portal
Numerical analysisNo order measurementConvergence slopes measuredExplanation of the drift with the modified HamiltonianDiscusses computational cost and the limits of regularization
ChaosDoes not estimate λ\lambdaBenettin implemented; λ\lambda for BurrauCompares with two bodies and the figure-eight; discusses the parameter dependenceAnalyzes Burrau’s escape time against hh and interprets it
Report and presentationIncompleteComplete with graphs and conclusionsQuality figures, reproducible, public codeLive demonstration and well-founded critique of the reference code

Variants and extensions

  • Barnes–Hut: octree for N∼104N \sim 10^4 and comparison of error against θ\theta (lesson 3).
  • Real Solar System: JPL Horizons initial conditions for the Sun + 8 planets; integrate 1 000 years with leapfrog and measure the drift of Mercury’s perihelion (non-relativistic) and the energy.
  • Resonances: Sun–Jupiter–asteroid system and the appearance of the Kirkwood gaps (resonances lesson).
  • KS regularization: for close encounters in Burrau.

Inclusion

  • A computational project, compatible with screen readers and keyboard input; the figures have textual descriptions and equivalent tables.
  • In pairs, one implements RK4 and the other leapfrog with the same interface, and then they swap to review.
  • The language is freely chosen; test skeletons are provided in Python and TypeScript.

Safety

  • A desk project, with no physical risks; eye breaks during long programming sessions.
  • As everywhere on the portal: never look at the Sun directly or with instruments without an ISO 12312-2 certified filter.

References and data sources

  • Hairer, E., Lubich, C. & Wanner, G. (2006). Geometric Numerical Integration, 2nd ed., Springer (chs. I, VI and IX: backward error analysis and energy conservation).
  • Chenciner, A. & Montgomery, R. (2000). A remarkable periodic solution of the three-body problem in the case of equal masses. Annals of Mathematics 152, 881–901. Simó's (2002) conditions, with G = m = 1: x₁ = −x₂ = (0.97000436, −0.24308753), x₃ = 0, v₃ = −2v₁ = −2v₂ = (−0.93240737, −0.86473146); period T ≈ 6.3259, E ≈ −1.28714, L = 0.
  • Szebehely, V. & Peters, C. F. (1967). Complete solution of a general problem of three bodies. AJ 72, 876. Pythagorean problem: masses 3, 4, 5 at rest at (1, 3), (−2, −1), (1, −1); E = −769/60; escape of mass 3 around t ≈ 59.4 (G = 1).
  • Benettin, G., Galgani, L., Giorgilli, A. & Strelcyn, J.-M. (1980). Lyapunov characteristic exponents for smooth dynamical systems. Meccanica 15, 9–20.
  • Aarseth, S. J. (2003). Gravitational N-Body Simulations, Cambridge University Press (softening, regularization and variable time step).