"""Checks every number and identity in the answers and solutions of n-body-questions.qmd
(The N-body Problem: Questions).

Each function below checks one group of questions. The labels it prints use the problem and question
numbers of the page. Run from the sfm-slides directory, or from anywhere:

    python3 codes/n-body-questions-verify.py
"""
from _verify import check, truth, sym_zero, Objective, run


def objective():
    """The 50 objective questions: numbering, options and answer key, and every number in an answer, recomputed and found in the option the page marks as correct."""
    import numpy as np

    # data, as in the page's data box

    G, Ms, Me, Mm = 6.674e-11, 1.989e30, 5.972e24, 7.342e22
    mus, AU, MJr, Rsun = 1.327e11, 1.496e8, 1047.6, 6.96e5

    num = Objective("n-body-questions.qmd", 50).num

    num(9, 9 * 8 / 2, "36")
    num(12, Rsun / AU, "4.7\\times10^{-3}", 4.7e-3, 0.05e-3)
    num(14, 4 ** 1.5, "8")
    num(19, G * Ms * Me / (AU * 1e3) ** 2, "3.5\\times10^{22}", 3.5e22, 0.05e22)
    aJ = 5.203 * AU
    num(21, aJ / (1 + MJr) / Rsun, "1.07")
    num(22, 384400 / (1 + 81.3), "4670", tol=5)
    num(23, mus / MJr / aJ ** 2 * 1e3, "2\\times10^{-7}", 2e-7, 0.15e-7)
    num(25, np.hypot(1, 2), "2.24")
    num(26, 1000 * 999 / 2, "499\\,500")
    num(27, 3.33e5 * (384400 / AU) ** 2, "2.2")
    num(32, 1 / MJr / 4.203 ** 2, "5\\times10^{-5}", 5e-5, 0.5e-5)
    num(36, 1.898e27 / 5.683e26 * np.sqrt(5.203 / 9.537), "2.5")
    num(37, 18 - 10, "8")
    num(39, 4 + 2 / np.sqrt(2), "4+\\sqrt2", 4 + np.sqrt(2), 1e-12)
    vJ = np.sqrt(mus / aJ)
    truth("Q40  Jupiter's speed 13.06 km/s", abs(vJ - 13.06) < 0.005)
    num(40, vJ / MJr * 1e3, "12.5")
    num(45, (Mm / Ms) * (AU / 384400) ** 3, "2.2")
    d6 = np.radians(6)
    num(46, np.degrees(np.arctan2(0.5 * np.sin(d6), 1 + 0.5 * np.cos(d6))), "2.0")
    num(48, 2 ** 1.5, "2\\sqrt2", 2 * np.sqrt(2), 1e-12)


def note_exercises():
    """Problems 7, 1, 8, 9, 2, 10 and 11, the exercises that used to end the N-body note."""
    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
    GMearth = 3.986004418e14     # m^3/s^2, as in n-body-verify.py

    GM_moon_orbit = 4*np.pi**2*(384400e3)**3/(27.32*86400)**2
    ok(f"P7: 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"P1: Earth-Moon barycentre {384400/82.3:.0f} km from the Earth's centre (< 6371, inside)", 384400/82.3 < 6371)
    ok("P2: Earth-Moon-spacecraft = 18 first-order ODEs", 6*3 == 18)
    # P11: two bodies in circles, omega^2 = G(m1+m2)/L^3
    m1_, m2_, G_, L_, w_ = sp.symbols("m1 m2 G L omega", positive=True)
    R1_ = m2_*L_/(m1_ + m2_); R2_ = m1_*L_/(m1_ + m2_)
    w2_ = G_*(m1_ + m2_)/L_**3
    ok("P11: R1 + R2 = L and m1 R1 = m2 R2", sp.simplify(R1_ + R2_ - L_) == 0 and sp.simplify(m1_*R1_ - m2_*R2_) == 0)
    ok("P11: body 1 balance holds with omega^2 = G(m1+m2)/L^3", sp.simplify(G_*m1_*m2_/L_**2 - m1_*w2_*R1_) == 0)
    ok("P11: body 2 balance holds with the same omega", sp.simplify(G_*m1_*m2_/L_**2 - m2_*w2_*R2_) == 0)
    T_E = 2*np.pi*np.sqrt(384400.0**3/398600)/86400; T_EM = 2*np.pi*np.sqrt(384400.0**3/(398600 + 4903))/86400
    ok(f"P11: Earth-Moon period, Earth mass only = {T_E:.2f} d (27.45)", close(T_E, 27.45, 0.005))
    ok(f"P11: Earth-Moon period, total mass = {T_EM:.2f} d (27.28)", close(T_EM, 27.28, 0.005))
    ok("P11: GM_earth/GM_moon = 81.3", close(398600/4903, 81.3, 0.05))
    # P7: GM from the Moon's orbit, the Moon's mass and the Sun's mean outward push
    GM1 = 4*np.pi**2*384400.0**3/(27.32*86400)**2
    ok(f"P7: T = {27.32*86400:.4e} s (2.3604e6)", close(27.32*86400, 2.3604e6, 50))
    ok(f"P7: GM = {GM1:.5g} km^3/s^2 (4.0246e5)", close(GM1, 4.0246e5, 5))
    ok(f"P7: {100*(GM1/398600.4418 - 1):.2f}% above GM_earth (1.0)", close(100*(GM1/398600.4418 - 1), 1.0, 0.05))
    GMtot = 398600.4418*(1 + 1/81.3)
    ok(f"P7: G(M+m) = {GMtot:.5g} (4.0350e5), {100*(GMtot/398600.4418-1):.2f}% above GM (1.2)",
       close(GMtot, 4.0350e5, 5) and close(100*(GMtot/398600.4418 - 1), 1.2, 0.05))
    ok(f"P7: measured value {100*(1 - GM1/GMtot):.2f}% below G(M+m) (0.26)", close(100*(1 - GM1/GMtot), 0.26, 0.005))
    th = sp.symbols("theta")
    ok("P7: mean of 2cos^2 - sin^2 round the circle = 1/2",
       sp.simplify(sp.integrate(2*sp.cos(th)**2 - sp.sin(th)**2, (th, 0, 2*sp.pi))/(2*sp.pi) - sp.Rational(1, 2)) == 0)
    push = 0.5*(27.32/365.25)**2
    ok(f"P7: mean solar push = {100*push:.2f}% (0.28)", close(100*push, 0.28, 0.005))
    GMeff = GMtot*(1 - push)
    ok(f"P7: effective GM = {GMeff:.5g} (4.0237e5), {100*abs(GMeff/GM1 - 1):.3f}% from measured (0.02)",
       close(GMeff, 4.0237e5, 5) and close(100*abs(GMeff/GM1 - 1), 0.02, 0.005))
    # P1: barycentre
    dB = 384400/82.3
    ok(f"P1: d = {dB:.0f} km (4671), {dB/6371:.2f} R (0.73), {6371 - dB:.0f} km deep (1700)",
       close(dB, 4671, 0.5) and close(dB/6371, 0.73, 0.005) and close(6371 - dB, 1700, 1))
    # P8: couple k z x r12
    k_ = sp.symbols("k", real=True)
    x1, y1, x2, y2 = sp.symbols("x1 y1 x2 y2", real=True)
    R1v, R2v, zh = sp.Matrix([x1, y1, 0]), sp.Matrix([x2, y2, 0]), sp.Matrix([0, 0, 1])
    r12v = R2v - R1v
    F12 = k_*zh.cross(r12v); F21 = k_*zh.cross(-r12v)
    ok("P8: F21 = -F12", sp.simplify(F12 + F21) == sp.zeros(3, 1))
    ok("P8: F12 perpendicular to r12", sp.simplify(F12.dot(r12v)) == 0)
    dH = R1v.cross(F12) + R2v.cross(F21)
    ok("P8: dH/dt = -k r12^2 z", sp.simplify(dH - (-k_*r12v.dot(r12v))*zh) == sp.zeros(3, 1))
    # P9: pair sum = half the body sum, grad_1 U = grad_1 Phi_1 = -F_1
    G4 = sp.symbols("G", positive=True)
    ms4 = sp.symbols("m1:5", positive=True)
    Xs = [sp.Matrix(sp.symbols(f"x{i} y{i} z{i}", real=True)) for i in range(1, 5)]
    dist = lambda i, j: sp.sqrt((Xs[j] - Xs[i]).dot(Xs[j] - Xs[i]))
    U4 = -G4*sum(ms4[i]*ms4[j]/dist(i, j) for i in range(4) for j in range(i + 1, 4))
    Phi4 = [-G4*sum(ms4[i]*ms4[j]/dist(i, j) for j in range(4) if j != i) for i in range(4)]
    ok("P9: 6 pair terms, 12 body terms", sum(len(sp.Add.make_args(sp.expand(P))) for P in Phi4) == 12
       and len(sp.Add.make_args(sp.expand(U4))) == 6)
    ok("P9: U = (1/2) sum Phi_i", sp.expand(U4 - sum(Phi4)/2) == 0)
    grad = lambda f: sp.Matrix([sp.diff(f, c) for c in Xs[0]])
    F1 = sum((G4*ms4[0]*ms4[j]/dist(0, j)**3*(Xs[j] - Xs[0]) for j in range(1, 4)), sp.zeros(3, 1))
    ok("P9: grad_1 U = grad_1 Phi_1", sp.expand(grad(U4) - grad(Phi4[0])) == sp.zeros(3, 1))
    rng = np.random.default_rng(3)
    subs = {sym: val for X in Xs for sym, val in zip(X, rng.normal(size=3))}
    subs.update({m: val for m, val in zip(ms4, rng.uniform(1, 2, 4))}); subs[G4] = 1.3
    ok("P9: grad_1 U = -F_1 (numerically at a random configuration)",
       max(abs(float((grad(U4) + F1)[k].subs(subs))) for k in range(3)) < 1e-12)
    # P2: order
    ok("P2: 6n = 18 for n = 3, 19 with the mass equation", 6*3 == 18 and 6*3 + 1 == 19)
    # P10: the chaotic run of fig-nbody-sensitivity.py
    m6 = np.ones(3)
    p6 = np.array([[-1.0, 0.2, 0.0], [1.1, -0.1, 0.0], [0.1, -1.3, 0.0]]); v6 = np.array([[0.15, 0.45, 0.0], [-0.35, 0.10, 0.0], [0.20, -0.55, 0.0]])
    p6 -= p6.mean(0); v6 -= v6.mean(0)

    def rhs6(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] += m6[j]*d/np.linalg.norm(d)**3
        return np.concatenate([y[9:], a.ravel()])

    y6 = np.concatenate([p6.ravel(), v6.ravel()]); y6B = y6.copy(); y6B[0] += 1e-6
    sA = solve_ivp(rhs6, [0, 45], y6, method="DOP853", rtol=1e-12, atol=1e-13, dense_output=True)
    sL = solve_ivp(rhs6, [0, 45], y6, method="DOP853", rtol=1e-10, atol=1e-11, dense_output=True)
    sB = solve_ivp(rhs6, [0, 45], y6B, method="DOP853", rtol=1e-12, atol=1e-13, dense_output=True)
    hstep = np.diff(sA.t)
    ts6 = np.linspace(0, 45, 20001); Y6 = sA.sol(ts6)
    dmin6 = min(np.linalg.norm(Y6[3*i:3*i+3] - Y6[3*j:3*j+3], axis=0).min() for i in range(3) for j in range(i + 1, 3))
    ok(f"P10: closest approach {dmin6:.3f} (0.015)", close(dmin6, 0.015, 0.0005))
    ok(f"P10: step from {hstep.max():.2f} to {hstep.min():.1e} (0.16, 3e-6), ratio {hstep.max()/hstep.min():.0f} (~5e4)",
       close(hstep.max(), 0.16, 0.005) and close(hstep.min(), 3e-6, 0.5e-6) and 3e4 < hstep.max()/hstep.min() < 7e4)
    sep45 = np.linalg.norm(sA.sol(45)[:3] - sB.sol(45)[:3]); num45 = np.linalg.norm(sA.sol(45)[:3] - sL.sol(45)[:3])
    ok(f"P10: separation at t = 45 is {sep45:.2f} (3.3)", close(sep45, 3.3, 0.05))
    ok(f"P10: looser-tolerance run moves body 1 by {num45:.4f} at t = 45 (0.0016)", close(num45, 0.0016, 0.00005))


def three_bodies():
    """Problem 12, three bodies that keep their shape."""
    import sympy as sp
    from numpy import sqrt, pi

    # ---------------------------------------------------------------- data table of the paper

    muS = 1.327e11         # km^3/s^2
    AU = 1.496e8           # km

    print("\nQ1")
    G, m, L, w, lam = sp.symbols("G m L omega lambda", positive=True)
    R = L / sp.sqrt(3)
    F = 2 * G * m**2 / L**2 * sp.cos(sp.pi / 6)          # net pull towards the centroid
    w2 = sp.solve(sp.Eq(m * w**2 * R, F), w)[0]**2
    sym_zero("omega^2 = 3 G m / L^3", w2 - 3 * G * m / L**3)
    T = 3 * m * sp.Rational(1, 2) * w2 * R**2
    U = -3 * G * m**2 / L
    sym_zero("T = 3 G m^2 / (2 L)", T - 3 * G * m**2 / (2 * L))
    sym_zero("E = -3 G m^2 / (2 L) = -T", (T + U) + T)
    H = 3 * m * R**2 * sp.sqrt(w2)
    sym_zero("H = m sqrt(3 G m L)", H - m * sp.sqrt(3 * G * m * L))
    lam2 = sp.solve(sp.Eq(lam**2 * T + U, 0), lam)[0]
    sym_zero("lambda = sqrt 2", lam2 - sp.sqrt(2))
    Tq = 2 * pi * sqrt(AU**3 / (3 * muS))
    check("P12 period of three solar masses at 1 AU [d]", Tq / 86400, 210.9)
    check("P12 one year / sqrt 3 [d]", 365.25 / sqrt(3), 210.9)


def who_pulls():
    """Problems 3, 4 and 5, who pulls harder, and a coincidence."""
    import numpy as np

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

    muS, muE, muM = 1.3271e20, 3.9860e14, 4.9028e12          # m^3/s^2
    aSE, aEM = 1.496e11, 3.844e8                              # m

    print("Problem 3")
    aEM_ = muE/aEM**2
    aSM = muS/aSE**2
    ok(f"a_E->M = {aEM_:.3e}, a_S->M = {aSM:.3e}, ratio {aSM/aEM_:.2f}", close(aEM_, 2.70e-3, 0.005e-3) and close(aSM, 5.93e-3, 0.005e-3) and close(aSM/aEM_, 2.20, 0.005))
    ok(f"(3.844e8)^2 = {aEM**2:.3e}, (1.496e11)^2 = {aSE**2:.3e}", close(aEM**2, 1.478e17, 0.001e17) and close(aSE**2, 2.238e22, 0.001e22))
    tid = 2*muS*aEM/aSE**3
    ok(f"tidal 2 mu_S r_EM / r_SE^3 = {tid:.2e} = {100*tid/aEM_:.1f}% of Earth's pull", close(tid, 3.0e-5, 0.05e-5) and close(100*tid/aEM_, 1.1, 0.05))
    # exact difference of the Sun's pulls on Moon (at new moon, Moon closer to Sun) and Earth
    exact = muS/(aSE - aEM)**2 - muS/aSE**2
    ok(f"exact difference at new moon {exact:.3e} (first-order {tid:.3e})", close(exact/tid, 1, 0.01))

    print("Problem 4")
    aME = muM/aEM**2
    ok(f"a_M->E = {aME:.3e}, a_S->E/a_M->E = {aSM/aME:.0f}", close(aME, 3.32e-5, 0.005e-5) and close(aSM/aME, 179, 0.5))
    ok(f"ratio of ratios = {(aSM/aME)/(aSM/aEM_):.1f} = mu_E/mu_M = {muE/muM:.1f}", close(muE/muM, 81.3, 0.05))

    print("Problem 5")
    ok(f"a_SE/a_EM = {aSE/aEM:.0f}", close(aSE/aEM, 389, 0.5))
    ok(f"D_S/D_M = {1.392e6/3475:.0f}", close(1.392e6/3475, 400, 1))
    ok(f"angular sizes: Sun {np.degrees(1.392e6/1.496e8):.3f} deg, Moon {np.degrees(3475/384400):.3f} deg", close(np.degrees(1.392e6/1.496e8), 0.533, 0.001) and close(np.degrees(3475/384400), 0.518, 0.001))


def which_mu():
    """Problem 6, which mu, and the third-body pulls at GEO."""
    import numpy as np

    # ---------------------------------------------------------------- constants (the handout's table)
    from orbit.constants import MU_EARTH as MU, R_EARTH as RE, MU_MOON as MU_M, D_MOON as D, MU_SUN as MU_S, AU
    G = 6.6743e-20            # km^3/(kg s^2)
    M_E, M_M = 5.9722e24, 7.342e22   # kg


    R_GEO = 42164.0
    DAY = 86400.0

    # ================================================================ Problem 1: which mu?
    print("\n--- Problem 6")
    xb = D*M_M/(M_E + M_M)
    check("P6 barycentre from Earth's centre, km", xb, "4668")
    check("P6 depth below surface, km", RE - xb, "1710")
    mu_em = G*(M_E + M_M)
    check("P6 mu = G(M+m)", mu_em, "403 503")
    check("P6 G M_E", G*M_E, "398 603")
    T_em, T_e = 2*np.pi*np.sqrt(D**3/mu_em)/DAY, 2*np.pi*np.sqrt(D**3/MU)/DAY
    check("P6 T with G(M+m), days", T_em, "27.28")
    check("P6 T with mu_E, days", T_e, "27.45")
    check("P6 period difference, hours", (T_e - T_em)*24, "4.0", tol=0.05)
    check("P6 mu ratio %", 100*(mu_em/MU - 1), "1.23")
    check("P6 observed sidereal month longer by %", 100*(27.321661/T_em - 1), "0.14", tol=0.005)
    aE = MU/R_GEO**2
    aM = MU_M/(D - R_GEO)**2
    aS = MU_S/AU**2
    check("P6 Earth's pull at GEO, m/s^2", aE*1e3, "0.2242")
    check("P6 distance GEO to Moon, km", D - R_GEO, "342 236")
    check("P6 Moon's pull at GEO, m/s^2 (x1e-5)", aM*1e3*1e5, "4.19")
    check("P6 Sun's pull at GEO, m/s^2 (x1e-3)", aS*1e3*1e3, "5.93")
    check("P6 Sun/Earth %", 100*aS/aE, "2.6", tol=0.05)
    check("P6 Sun/Moon", aS/aM, "142", tol=0.5)
    tM = MU_M*(1/(D - R_GEO)**2 - 1/D**2)
    tS = 2*MU_S*R_GEO/AU**3
    check("P6 Moon's tidal, m/s^2 (x1e-6)", tM*1e3*1e6, "8.68")
    check("P6 Sun's tidal, m/s^2 (x1e-6)", tS*1e3*1e6, "3.34")
    check("P6 tidal Moon/Sun", tM/tS, "2.6", tol=0.05)
    check("P6 Moon tidal / Earth (x1e-5)", tM/aE*1e5, "3.9", tol=0.05)
    check("P6 Sun tidal / Earth (x1e-5)", tS/aE*1e5, "1.5", tol=0.05)
    # The derivation of the Sun's term in (d).
    check("P6 r/d for the Sun (x1e-4)", R_GEO/AU*1e4, "2.82")
    check("P6 first dropped term ratio 3r/(2d) (x1e-4)", 1.5*R_GEO/AU*1e4, "4.2", tol=0.05)
    tS_exact = MU_S*(1/(AU - R_GEO)**2 - 1/AU**2)
    check("P6 Sun's tidal exact (x1e-6)", tS_exact*1e3*1e6, "3.344")
    check("P6 Sun's tidal approx (x1e-6)", tS*1e3*1e6, "3.343")
    check("P6 approx error %", 100*(tS_exact - tS)/tS_exact, "0.04", tol=0.005)
    check("P6 mu_Moon/D^3 over mu_Sun/AU^3", (MU_M/D**3)/(MU_S/AU**3), "2.2", tol=0.05)
    check("P6 mu_Sun/mu_Moon (x1e7)", MU_S/MU_M/1e7, "2.7", tol=0.05)
    check("P6 r/D for the Moon", R_GEO/D, "0.110")
    tM_approx = 2*MU_M*R_GEO/D**3
    check("P6 Moon's tidal approx (x1e-6)", tM_approx*1e3*1e6, "7.28")
    check("P6 Moon approx below exact %", 100*(1 - tM_approx/tM), "16", tol=0.5)

    check("P13 total Earth+Moon mass e24", (M_E + M_M)/1e24, "6.0456")


def three_equal_masses():
    """Problem 13, three equal masses on a rotating triangle."""
    import sympy as sp

    ok = lambda label, cond: print(f"  [{'ok' if cond else 'FAIL'}] {label}")
    G, m, d0, w0 = sp.symbols("G m d_0 omega_0", positive=True)
    R = d0 / sp.sqrt(3)
    ok("centroid distance d0/sqrt3 from the corner (equilateral triangle)",
       sp.simplify((d0 / 2) / sp.cos(sp.pi / 6) - R) == 0)
    F = 2 * G * m**2 / d0**2 * sp.cos(sp.pi / 6)
    ok("net pull sqrt3 G m^2/d0^2", sp.simplify(F - sp.sqrt(3) * G * m**2 / d0**2) == 0)
    w2 = sp.solve(sp.Eq(m * w0**2 * R, F), w0)[0]**2
    ok("omega0^2 = 3 G m / d0^3", sp.simplify(w2 - 3 * G * m / d0**3) == 0)
    ok("Kepler III with total mass 3m and separation d0", sp.simplify(w2 - G * (3 * m) / d0**3) == 0)


BLOCKS = [objective, note_exercises, three_bodies, who_pulls, which_mu, three_equal_masses]


if __name__ == "__main__":
    run(BLOCKS)
