"""Sensitivity of a three-body orbit to its initial conditions.

Two runs of the chaotic case of three-body-animation.py; the second has body 1 moved
by 1e-6 in x. Left: the paths of body 1 in both runs. Right: the distance between the
two copies of body 1 against time (log scale), with the energy error of run A for scale.
Run from sfm-slides:  python3 codes/fig-nbody-sensitivity.py  -> img/fig-nbody-sensitivity.png
Try another offset:   python3 codes/fig-nbody-sensitivity.py 1e-9   (prints only, figure untouched)
"""
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp

os.makedirs("img", exist_ok=True)

CREAM, INK = "#fcfbf7", "#2f2a24"
MAROON, BLUE, GREEN, AMBER = "#6b1f1f", "#2f5ea8", "#2d6a2d", "#b45309"
plt.rcParams.update({
    "figure.facecolor": CREAM, "savefig.facecolor": CREAM, "axes.facecolor": CREAM,
    "axes.edgecolor": INK, "axes.labelcolor": INK, "text.color": INK,
    "xtick.color": INK, "ytick.color": INK, "font.size": 12,
    "axes.grid": True, "grid.alpha": 0.25, "grid.color": INK,
})

m = np.ones(3)
pos = np.array([[-1.0, 0.2, 0.0], [1.1, -0.1, 0.0], [0.1, -1.3, 0.0]])
vel = np.array([[0.15, 0.45, 0.0], [-0.35, 0.10, 0.0], [0.20, -0.55, 0.0]])
pos -= pos.mean(0)
vel -= vel.mean(0)
T_END = 45.0
DELTA = float(sys.argv[1]) if len(sys.argv) > 1 else 1e-6


def rhs(t, y):
    R = y[:9].reshape(3, 3)
    a = np.zeros_like(R)
    for i in range(3):
        for j in range(3):
            if i != j:
                d = R[j] - R[i]
                a[i] += m[j]*d/np.linalg.norm(d)**3
    return np.concatenate([y[9:], a.ravel()])


def energy(y):
    R, V = y[:9].reshape(3, 3), y[9:].reshape(3, 3)
    T = 0.5*(m*(V**2).sum(1)).sum()
    U = -sum(m[i]*m[j]/np.linalg.norm(R[i] - R[j]) for i in range(3) for j in range(i + 1, 3))
    return T + U


t = np.linspace(0, T_END, 6000)
yA = np.concatenate([pos.ravel(), vel.ravel()])
yB = yA.copy()
yB[0] += DELTA
kw = dict(t_eval=t, method="DOP853", rtol=1e-12, atol=1e-13)
A = solve_ivp(rhs, [0, T_END], yA, **kw).y
B = solve_ivp(rhs, [0, T_END], yB, **kw).y
sep = np.linalg.norm(A[0:3] - B[0:3], axis=0)
E0 = energy(yA)
dE = np.array([abs(energy(A[:, k]) - E0) for k in range(len(t))])

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13.2, 5.4))
ax1.plot(A[0], A[1], color=BLUE, lw=1.6, label="run A")
ax1.plot(B[0], B[1], color=MAROON, lw=1.2, ls="--", label=r"run B (body 1 moved by $10^{-6}$)")
ax1.plot(A[0, 0], A[1, 0], "o", color=INK, ms=6)
ax1.text(A[0, 0] + 0.05, A[1, 0] + 0.08, "start", fontsize=11)
ax1.set_aspect("equal")
ax1.set_xlabel("$x$")
ax1.set_ylabel("$y$")
ax1.set_title("Path of body 1 in the two runs")
ax1.legend(loc="lower left", fontsize=10, framealpha=0.9)

ax2.semilogy(t, np.maximum(sep, 1e-16), color=MAROON, lw=2, label="distance between the two copies of body 1")
ax2.semilogy(t, np.maximum(dE, 1e-16), color=GREEN, lw=1.2, label="energy error of run A (integrator)")
ax2.axhline(DELTA, color=INK, lw=0.8, ls=":")
ax2.text(12, DELTA*0.15, "initial offset $10^{-6}$", fontsize=10)
ax2.set_xlabel("time $t$ (units with $G = m = 1$)")
ax2.set_ylabel("size")
ax2.set_ylim(1e-15, 100)
ax2.set_title("The offset grows; the integrator error does not")
ax2.legend(loc="lower right", fontsize=10, framealpha=0.9)

fig.tight_layout()
if len(sys.argv) == 1:
    fig.savefig("img/fig-nbody-sensitivity.png", dpi=160, bbox_inches="tight")

when = f"t = {t[np.argmax(sep > 0.1)]:.2f}" if (sep > 0.1).any() else "never (before t = 45)"
print(f"initial offset {DELTA:.0e}: exceeds 0.1 at {when}; separation at t = 45: {sep[-1]:.3g} "
      f"(growth factor {sep[-1]/DELTA:.1e}); max energy error {dE.max():.1e}")
for name, Y in (("A", A), ("B", B)):
    R = Y[:9, -1].reshape(3, 3)
    d = {f"{i+1}{j+1}": round(float(np.linalg.norm(R[i] - R[j])), 2) for i in range(3) for j in range(i + 1, 3)}
    print(f"run {name}: final mutual distances {d}")
