"""Verification of every identity and number quoted in the N-body note (n-body-problem.qmd).

Part A is symbolic (sympy); Part B checks the numbers quoted in the text and the tasks;
Part C integrates the N-body equations and checks the ten integrals numerically.
Run:  python3 codes/n-body-verify.py        (a few seconds)
"""
import numpy as np
import sympy as sp
from scipy.integrate import solve_ivp

ok = lambda label, cond: print(f"  [{'ok' if cond else 'FAIL'}] {label}")
close = lambda x, y, tol: abs(x - y) <= tol

# ======================================================================================= A. symbolic
print("A. symbolic")
Xi = sp.Matrix(sp.symbols("x1 x2 x3", real=True))
Xj = sp.Matrix(sp.symbols("y1 y2 y3", real=True))
G, mi, mj = sp.symbols("G m_i m_j", positive=True)
rij = Xj - Xi
r = sp.sqrt(rij.dot(rij))

grad_r = sp.Matrix([sp.diff(r, x) for x in Xi])
ok("grad_i r_ij = -rhat_ij", sp.simplify(grad_r + rij/r) == sp.zeros(3, 1))
grad_inv = sp.Matrix([sp.diff(1/r, x) for x in Xi])
ok("grad_i (1/r_ij) = r_ij / r_ij^3", sp.simplify(grad_inv - rij/r**3) == sp.zeros(3, 1))
Phi = -G*mi*mj/r
F = -sp.Matrix([sp.diff(Phi, x) for x in Xi])
ok("F_ij = -grad_i Phi_ij = G m_i m_j r_ij / r^3", sp.simplify(F - G*mi*mj*rij/r**3) == sp.zeros(3, 1))
Fji = -sp.Matrix([sp.diff(Phi, x) for x in Xj])
ok("F_ji = -F_ij (third law from the potential)", sp.simplify(F + Fji) == sp.zeros(3, 1))
torque = Xi.cross(F) + Xj.cross(Fji)
ok("pair torque R_i x F_ij + R_j x F_ji = 0", sp.simplify(torque) == sp.zeros(3, 1))

# curl of a point-mass field
x, y, z, M = sp.symbols("x y z M", real=True)
rr = sp.sqrt(x**2 + y**2 + z**2)
g = -G*M*sp.Matrix([x, y, z])/rr**3
curl = sp.Matrix([sp.diff(g[2], y) - sp.diff(g[1], z),
                  sp.diff(g[0], z) - sp.diff(g[2], x),
                  sp.diff(g[1], x) - sp.diff(g[0], y)])
ok("curl g = 0 for a point mass", sp.simplify(curl) == sp.zeros(3, 1))
ok("d g_y/dx = 3 G M x y / r^5", sp.simplify(sp.diff(g[1], x) - 3*G*M*x*y/rr**5) == 0)
ok("d g_x/dy = 3 G M x y / r^5", sp.simplify(sp.diff(g[0], y) - 3*G*M*x*y/rr**5) == 0)
gr = sp.Function("g")
cen = gr(rr)*sp.Matrix([x, y, z])/rr
curl_c = sp.Matrix([sp.diff(cen[2], y) - sp.diff(cen[1], z),
                    sp.diff(cen[0], z) - sp.diff(cen[2], x),
                    sp.diff(cen[1], x) - sp.diff(cen[0], y)])
ok("curl of any central field g(r) rhat = 0", sp.simplify(curl_c) == sp.zeros(3, 1))

# V = (1/2) sum_i Phi_i and grad_i V = grad_i Phi_i, for N = 3
P = [sp.Matrix(sp.symbols(f"p{k}_1:4", real=True)) for k in range(3)]
m = sp.symbols("m0:3", positive=True)
d = lambda a, b: sp.sqrt((P[a] - P[b]).dot(P[a] - P[b]))
V = -G*(m[0]*m[1]/d(0, 1) + m[0]*m[2]/d(0, 2) + m[1]*m[2]/d(1, 2))
Phi_i = [-G*sum(m[i]*m[j]/d(i, j) for j in range(3) if j != i) for i in range(3)]
ok("V (pairs) = (1/2) sum_i Phi_i  (N = 3)", sp.simplify(V - sum(Phi_i)/2) == 0)
ok("grad_i V = grad_i Phi_i  (N = 3, i = 0)",
   sp.simplify(sp.Matrix([sp.diff(V - Phi_i[0], c) for c in P[0]])) == sp.zeros(3, 1))

# ======================================================================================= B. numbers
print("B. numbers in the text")
Gn = 6.674e-11
AU = 1.495978707e11
Rsun, Rearth, Rmoon_orbit = 6.957e8, 6.378137e6, 3.844e8
r_iss = Rearth + 420e3
ok(f"R_sun/AU = {Rsun/AU:.4f}  (~0.005)", close(Rsun/AU, 0.0047, 1e-4))
ok(f"R_earth/AU = {Rearth/AU:.2e}  (~4e-5)", close(Rearth/AU, 4.26e-5, 1e-6))
ok(f"R_earth/r_moon = {Rearth/Rmoon_orbit:.4f}  (~0.017)", close(Rearth/Rmoon_orbit, 0.0166, 1e-4))
ok(f"R_earth/r_ISS = {Rearth/r_iss:.3f}  (~0.94)", close(Rearth/r_iss, 0.938, 1e-3))
ok(f"Earth from the ISS: disc {2*np.degrees(np.arcsin(Rearth/r_iss)):.0f} deg across (140)",
   close(2*np.degrees(np.arcsin(Rearth/r_iss)), 140, 0.5))
ok(f"  fraction of the whole sky {(1-np.cos(np.arcsin(Rearth/r_iss)))/2:.2f} (about a third)",
   close((1-np.cos(np.arcsin(Rearth/r_iss)))/2, 0.33, 0.01))

# Kepler III with planetary data (a in AU, T in years)
kep = {"Mercury": (0.387, 0.241), "Venus": (0.723, 0.615), "Earth": (1.000, 1.000),
       "Mars": (1.524, 1.881), "Jupiter": (5.203, 11.86), "Saturn": (9.537, 29.46)}
ratios = {k: T**2/a**3 for k, (a, T) in kep.items()}
print("     T^2/a^3:", {k: round(v, 3) for k, v in ratios.items()})
ok("T^2/a^3 within 1% of 1 for all six planets", all(abs(v - 1) < 0.01 for v in ratios.values()))

# Io and Callisto about Jupiter, in the same units: T^2/a^3 ~ M_sun/M_Jupiter
for nm, a_km, T_d in (("Io", 421700, 1.769138), ("Callisto", 1882700, 16.689)):
    q = (T_d/365.25)**2/(a_km*1e3/AU)**3
    ok(f"{nm}: T^2/a^3 = {q:.0f} yr^2/AU^3 (~1047 = M_sun/M_J)", close(q, 1047, 2))

# tilt of the invariable plane from the eight planets (the model of fig-invariable-plane.py)
Hv = np.zeros(3)
for nm, a, inc, raan, ecc, mrel in [("Me", 0.387, 7.00, 48.33, 0.2056, 0.0553), ("V", 0.723, 3.39, 76.68, 0.0068, 0.815),
                                    ("E", 1.0, 0.0, 0.0, 0.0167, 1.0), ("Ma", 1.524, 1.85, 49.56, 0.0934, 0.107),
                                    ("J", 5.203, 1.30, 100.46, 0.0489, 317.8), ("S", 9.537, 2.49, 113.72, 0.0565, 95.2),
                                    ("U", 19.191, 0.77, 74.23, 0.0457, 14.5), ("N", 30.069, 1.77, 131.72, 0.0113, 17.1)]:
    i_, O_ = np.radians(inc), np.radians(raan)
    Hv += mrel*np.sqrt(a*(1 - ecc**2))*np.array([np.sin(O_)*np.sin(i_), -np.cos(O_)*np.sin(i_), np.cos(i_)])
tilt = np.degrees(np.arccos(Hv[2]/np.linalg.norm(Hv)))
ok(f"invariable plane from the eight planets: {tilt:.2f} deg to the ecliptic (1.58)", close(tilt, 1.58, 0.01))

# Sun vs Earth pull on the Moon
GMsun, GMearth = 1.32712440018e20, 3.986004418e14
a_sun_moon = GMsun/AU**2
a_earth_moon = GMearth/Rmoon_orbit**2
print(f"     Sun on Moon {a_sun_moon:.3e}, Earth on Moon {a_earth_moon:.3e}, ratio {a_sun_moon/a_earth_moon:.2f}")
ok("Sun's pull on the Moon ~ 2.2 x Earth's", close(a_sun_moon/a_earth_moon, 2.2, 0.03))
ok(f"Sun's acceleration at 1 AU = {a_sun_moon*1e3:.2f} mm/s^2 (5.93)", close(a_sun_moon*1e3, 5.93, 0.01))
ok(f"Earth's acceleration at the Moon = {a_earth_moon*1e3:.2f} mm/s^2 (2.70)", close(a_earth_moon*1e3, 2.70, 0.01))

# tidal (differential) Sun on Earth-Moon pair ~ 2 GM r / R^3
tidal = 2*GMsun*Rmoon_orbit/AU**3
print(f"     tidal Sun at Moon distance {tidal:.2e} m/s^2 = {tidal/a_earth_moon:.4f} of Earth's pull")
ok("Sun's differential pull ~ 0.011 of Earth's pull on the Moon", close(tidal/a_earth_moon, 0.011, 0.001))

# Sun-Jupiter barycentre
mJ_ratio = 1/1047.35
aJ = 7.785e11
dJ = aJ*mJ_ratio/(1 + mJ_ratio)
print(f"     Sun-Jupiter barycentre {dJ/1e3:.0f} km from the Sun's centre = {dJ/Rsun:.3f} R_sun")
ok("barycentre ~ 1.07 R_sun", close(dJ/Rsun, 1.07, 0.01))
# all four giants aligned at aphelion: mass ratio (to the Sun) and aphelion distance [m]
giants = [(1/1047.35, 7.785e11*1.0489), (1/3497.9, 1.4335e12*1.0565), (1/22902.9, 2.8725e12*1.0457), (1/19412.2, 4.4951e12*1.0113)]
dmax = sum(q*a for q, a in giants)
print(f"     four giants aligned at aphelion: Sun {dmax/Rsun:.2f} R_sun from the barycentre")
ok("upper bound with all four giants ~ 2.2 R_sun", close(dmax/Rsun, 2.2, 0.1))

# ODE count
ok("Sun + 8 planets: 6N = 54 first-order ODEs", 6*9 == 54)

# angular momentum shares: m * sqrt(a(1-e^2)) in Earth units
pl = [("Mercury", 0.387, 0.0553, 0.2056), ("Venus", 0.723, 0.815, 0.0068), ("Earth", 1.0, 1.0, 0.0167),
      ("Mars", 1.524, 0.107, 0.0934), ("Jupiter", 5.203, 317.8, 0.0489), ("Saturn", 9.537, 95.2, 0.0565),
      ("Uranus", 19.19, 14.5, 0.0457), ("Neptune", 30.07, 17.1, 0.0113)]
Hs = {n: mm*np.sqrt(a*(1 - e**2)) for n, a, mm, e in pl}
tot = sum(Hs.values())
print("     orbital h shares (%):", {k: round(100*v/tot, 1) for k, v in Hs.items()})
ok(f"Jupiter carries {100*Hs['Jupiter']/tot:.0f}% of planetary orbital angular momentum (~61%)",
   close(100*Hs["Jupiter"]/tot, 61, 1))
ok(f"Jupiter + Saturn carry {100*(Hs['Jupiter']+Hs['Saturn'])/tot:.0f}% (~86%)",
   close(100*(Hs["Jupiter"] + Hs["Saturn"])/tot, 86, 1))
ok(f"Jupiter/Earth h ratio = {Hs['Jupiter']/Hs['Earth']:.0f} (~725)", close(Hs["Jupiter"]/Hs["Earth"], 725, 3))

# Jupiter's direct pull on Earth vs the Sun's, at closest approach (4.2 AU)
ratio_J = (1/1047.35)/(5.203 - 1.0)**2
print(f"     Jupiter/Sun pull on Earth at opposition {ratio_J:.2e}")
ok("Jupiter's pull on the Earth ~ 5.4e-5 of the Sun's", close(ratio_J, 5.4e-5, 0.1e-5))

# Sun mass fraction
masses_kg = {"Sun": 1.989e30, "Jupiter": 1.898e27, "Saturn": 5.683e26, "Neptune": 1.024e26,
             "Uranus": 8.681e25, "Earth": 5.972e24, "Venus": 4.867e24, "Mars": 6.417e23, "Mercury": 3.301e23}
frac = masses_kg["Sun"]/sum(masses_kg.values())
ok(f"Sun holds {100*frac:.2f}% of the Sun+planets mass (99.86)", close(100*frac, 99.866, 0.01))

# galactic acceleration of the solar system: v^2/R with v ~ 230 km/s, R ~ 8.2 kpc
kpc = 3.0857e19
ag = (230e3)**2/(8.2*kpc)
ok(f"galactic acceleration ~ {ag:.1e} m/s^2 (~2e-10)", 1.5e-10 < ag < 2.5e-10)

# work vs fuel: tangential impulse energy change
v, dv = sp.symbols("v dv", positive=True)
ok("tangential impulse: d(eps) = v dv + dv^2/2", sp.expand((v + dv)**2/2 - v**2/2 - (v*dv + dv**2/2)) == 0)

# ======================================================================================= C. integrals
print("C. the ten integrals, numerically (random 4-body system, G = 1)")
rng = np.random.default_rng(3)
N = 4
ms = rng.uniform(0.5, 2.0, N)
R0 = rng.normal(0, 1.0, (N, 3))
V0 = rng.normal(0, 0.4, (N, 3))


def rhs(t, y):
    Rr = y[:3*N].reshape(N, 3)
    acc = np.zeros_like(Rr)
    for i in range(N):
        for j in range(N):
            if i != j:
                dvec = Rr[j] - Rr[i]
                acc[i] += ms[j]*dvec/np.linalg.norm(dvec)**3
    return np.concatenate([y[3*N:], acc.ravel()])


def integrals(y):
    Rr, Vv = y[:3*N].reshape(N, 3), y[3*N:].reshape(N, 3)
    P_ = (ms[:, None]*Vv).sum(0)
    H_ = (ms[:, None]*np.cross(Rr, Vv)).sum(0)
    T_ = 0.5*(ms*(Vv**2).sum(1)).sum()
    V_ = -sum(ms[i]*ms[j]/np.linalg.norm(Rr[i] - Rr[j]) for i in range(N) for j in range(i + 1, N))
    return P_, H_, T_ + V_, (ms[:, None]*Rr).sum(0)


y0 = np.concatenate([R0.ravel(), V0.ravel()])
sol = solve_ivp(rhs, [0, 5], y0, method="DOP853", rtol=1e-12, atol=1e-12, dense_output=True)
P0, H0, E0, S0 = integrals(y0)
P1, H1, E1, S1 = integrals(sol.y[:, -1])
ok(f"linear momentum conserved (|dP| = {np.linalg.norm(P1 - P0):.1e})", np.linalg.norm(P1 - P0) < 1e-9)
ok(f"angular momentum conserved (|dH| = {np.linalg.norm(H1 - H0):.1e})", np.linalg.norm(H1 - H0) < 1e-8)
ok(f"energy conserved (|dE| = {abs(E1 - E0):.1e})", abs(E1 - E0) < 1e-8)
ok("sum m_i R_i = P t + const", np.linalg.norm(S1 - (S0 + P0*sol.t[-1])) < 1e-8)

print("D. exercises")
GM_moon_orbit = 4*np.pi**2*(384400e3)**3/(27.32*86400)**2
ok(f"Ex 1: GM from the Moon's orbit = {GM_moon_orbit/1e9:.4g} km^3/s^2 (~1% above GM_earth: includes the Moon)",
   close(GM_moon_orbit/GMearth, 1.0097, 0.002))
ok(f"Ex 2: Earth-Moon barycentre {384400/82.3:.0f} km from the Earth's centre (< 6371, inside)", 384400/82.3 < 6371)
ok("Ex 5: Earth-Moon-spacecraft = 18 first-order ODEs", 6*3 == 18)
ok("20 yr / 5 Myr = 4e-6", close(20/5e6, 4e-6, 1e-9))
