"""Newtonian gravity and the time integrators (Euler, RK2, RK4)."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable, Dict, List, Tuple
import numpy as np
from .config import System
State = Tuple[np.ndarray, np.ndarray] # (positions, velocities)
[docs]
@dataclass
class Trajectory:
"""Result of :func:`simulate`.
Attributes:
times: Times of the saved frames, shape ``(n_frames,)``.
positions: Shape ``(n_frames, n_bodies, dim)``.
velocities: Shape ``(n_frames, n_bodies, dim)``.
energy: Total energy at each saved frame. It should stay nearly constant;
a large drift means ``dt`` is too big.
names: Body labels.
masses: Body masses.
"""
times: np.ndarray
positions: np.ndarray
velocities: np.ndarray
energy: np.ndarray
names: List[str]
masses: np.ndarray
@property
def energy_drift(self) -> float:
"""Relative change of total energy between first and last frame."""
e0 = self.energy[0]
return float(abs((self.energy[-1] - e0) / e0)) if e0 != 0 else float(abs(self.energy[-1]))
[docs]
def accelerations(positions: np.ndarray, masses: np.ndarray, G: float = 1.0, softening: float = 0.0) -> np.ndarray:
r"""Gravitational acceleration of every body due to all the others.
.. math::
\mathbf{a}_i = -G \sum_{k \neq i} m_k
\frac{\mathbf{r}_i - \mathbf{r}_k}{\left(|\mathbf{r}_i - \mathbf{r}_k|^2 + \epsilon^2\right)^{3/2}}
Args:
positions: Shape ``(n, dim)``.
masses: Shape ``(n,)``.
G: Gravitational constant.
softening: Softening length :math:`\epsilon`.
Returns:
Accelerations, shape ``(n, dim)``.
"""
r_ik = positions[:, np.newaxis, :] - positions[np.newaxis, :, :] # r_i - r_k
dist2 = np.sum(r_ik**2, axis=-1) + softening**2
np.fill_diagonal(dist2, np.inf) # a body does not attract itself
inv_r3 = dist2**-1.5
return -G * np.einsum("ik,ikd,k->id", inv_r3, r_ik, masses)
[docs]
def total_energy(positions: np.ndarray, velocities: np.ndarray, masses: np.ndarray,
G: float = 1.0, softening: float = 0.0) -> float:
"""Kinetic plus gravitational potential energy."""
kinetic = 0.5 * np.sum(masses * np.sum(velocities**2, axis=-1))
i, k = np.triu_indices(len(masses), k=1)
dist = np.sqrt(np.sum((positions[i] - positions[k]) ** 2, axis=-1) + softening**2)
potential = -G * np.sum(masses[i] * masses[k] / dist)
return float(kinetic + potential)
# --------------------------------------------------------------------------- #
# Integrators: each takes the state and returns the state one step later.
# --------------------------------------------------------------------------- #
[docs]
def euler_step(x: np.ndarray, v: np.ndarray, dt: float, acc: Callable[[np.ndarray], np.ndarray]) -> State:
"""Forward Euler (1st order). Simple but drifts quickly; for teaching only."""
return x + dt * v, v + dt * acc(x)
[docs]
def rk2_step(x: np.ndarray, v: np.ndarray, dt: float, acc: Callable[[np.ndarray], np.ndarray]) -> State:
"""Midpoint Runge-Kutta (2nd order)."""
x_mid = x + 0.5 * dt * v
v_mid = v + 0.5 * dt * acc(x)
return x + dt * v_mid, v + dt * acc(x_mid)
[docs]
def rk4_step(x: np.ndarray, v: np.ndarray, dt: float, acc: Callable[[np.ndarray], np.ndarray]) -> State:
"""Classic Runge-Kutta (4th order). The default."""
k1x, k1v = v, acc(x)
k2x, k2v = v + 0.5 * dt * k1v, acc(x + 0.5 * dt * k1x)
k3x, k3v = v + 0.5 * dt * k2v, acc(x + 0.5 * dt * k2x)
k4x, k4v = v + dt * k3v, acc(x + dt * k3x)
x_new = x + dt / 6.0 * (k1x + 2 * k2x + 2 * k3x + k4x)
v_new = v + dt / 6.0 * (k1v + 2 * k2v + 2 * k3v + k4v)
return x_new, v_new
METHODS: Dict[str, Callable] = {"euler": euler_step, "rk2": rk2_step, "rk4": rk4_step}
[docs]
def simulate(system: System, method: str = "rk4", save_every: int = 1) -> Trajectory:
"""Integrate the system from ``t = 0`` to ``system.final_time``.
The last step is shortened if needed so the run ends exactly at ``final_time``.
Args:
system: Bodies and settings, usually from :func:`celestial_rhapsody.load_system`.
method: ``"rk4"`` (default), ``"rk2"`` or ``"euler"``.
save_every: Keep one frame every ``save_every`` steps. The final state is always kept.
Returns:
A :class:`Trajectory`.
"""
if method not in METHODS:
raise ValueError(f"Unknown method '{method}'. Choose from: {', '.join(METHODS)}")
if save_every < 1:
raise ValueError("save_every must be at least 1.")
step = METHODS[method]
m, G, eps = system.masses, system.G, system.softening
def acc(pos: np.ndarray) -> np.ndarray:
return accelerations(pos, m, G, eps)
x, v = system.positions.copy(), system.velocities.copy()
t, T, dt = 0.0, system.final_time, system.dt
times, xs, vs, es = [t], [x.copy()], [v.copy()], [total_energy(x, v, m, G, eps)]
n = 0
while t < T - 1e-12 * T:
h = min(dt, T - t) # do not overshoot final_time
x, v = step(x, v, h, acc)
t += h
n += 1
if n % save_every == 0 or t >= T - 1e-12 * T:
times.append(t)
xs.append(x.copy())
vs.append(v.copy())
es.append(total_energy(x, v, m, G, eps))
return Trajectory(
times=np.array(times),
positions=np.array(xs),
velocities=np.array(vs),
energy=np.array(es),
names=list(system.names),
masses=m.copy(),
)