"""Checks every equation and number in gauss-variational-equations.qmd.

A. The Gauss equations in RSW and TNW form against finite-difference velocity gradients of the elements
   (the fundamental rule: the perturbative part of each rate is d(element)/dv . a_d).
B. Identities and alternative forms (cos E form of e-dot, compact M-dot, eccentricity-vector rate).
C. The J2 acceleration in RSW components against the Cartesian J2 acceleration.
D. Orbit averages: <Omega-dot>, <i-dot> and <omega-dot> for J2, numerically and in closed form, and the
   analytic average of the in-plane omega rate derived in the note.
E. The numbers quoted in the note (sun-synchronous case, Try-it boxes, radial impulse at periapsis).
F. End-to-end: the Gauss equations integrated against the Cartesian equations under J2 plus a thrust.

Run from the sfm-slides directory:   python3 codes/gauss-variational-verify.py
"""
import numpy as np
from scipy.integrate import solve_ivp

RESULTS = []
MU, RE, J2 = 398600.4418, 6378.137, 1.08263e-3
DAY = 86400.0


def check(name, value, stated, tol):
    ok = abs(value - stated) <= tol
    RESULTS.append(ok)
    print(f"{'PASS' if ok else 'FAIL'}  {name:<66} {value:15.7g}   page: {stated}")


def truth(name, cond):
    RESULTS.append(bool(cond))
    print(f"{'PASS' if cond else 'FAIL'}  {name}")


def wrap(x):
    return (x + np.pi) % (2 * np.pi) - np.pi


def coe(r, v):
    """State -> (a, e, i, Omega, omega, f, M, u), quadrant-safe."""
    h = np.cross(r, v); hn = np.linalg.norm(h); rn = np.linalg.norm(r)
    n = np.cross([0, 0, 1], h); nn = np.linalg.norm(n)
    ev = ((v @ v - MU / rn) * r - (r @ v) * v) / MU; e = np.linalg.norm(ev)
    a = 1 / (2 / rn - v @ v / MU)
    i = np.arccos(h[2] / hn)
    Om = np.arctan2(n[1], n[0])
    om = np.arctan2(hn * ev[2], n @ ev)
    f = np.arctan2(hn * (r @ v), hn ** 2 - MU * rn)
    u = np.arctan2(r[2] / np.sin(i), (n @ r) / nn)                 # argument of latitude
    E = 2 * np.arctan2(np.sqrt(1 - e) * np.sin(f / 2), np.sqrt(1 + e) * np.cos(f / 2))
    M = E - e * np.sin(E)
    return np.array([a, e, i, Om, om, f, M, u])


def rv(a, e, i, Om, om, f):
    p = a * (1 - e * e); r = p / (1 + e * np.cos(f)); h = np.sqrt(MU * p)
    rp = r * np.array([np.cos(f), np.sin(f), 0.0])
    vp = MU / h * np.array([-np.sin(f), e + np.cos(f), 0.0])
    cO, sO, ci, si, cw, sw = np.cos(Om), np.sin(Om), np.cos(i), np.sin(i), np.cos(om), np.sin(om)
    Q = np.array([[cO * cw - sO * sw * ci, -cO * sw - sO * cw * ci, sO * si],
                  [sO * cw + cO * sw * ci, -sO * sw + cO * cw * ci, -cO * si],
                  [sw * si, cw * si, ci]])
    return Q @ rp, Q @ vp


def rsw(r, v):
    R = r / np.linalg.norm(r); W = np.cross(r, v); W /= np.linalg.norm(W)
    return R, np.cross(W, R), W


def B_rsw(a, e, i, om, f):
    """Rows: a, e, i, Omega, omega, M, f, u; columns: a_R, a_S, a_W."""
    p = a * (1 - e * e); r = p / (1 + e * np.cos(f)); h = np.sqrt(MU * p); b = a * np.sqrt(1 - e * e)
    u = om + f; sf, cf = np.sin(f), np.cos(f)
    return np.array([
        [2 * a * a * e * sf / h, 2 * a * a * p / (h * r), 0],
        [p * sf / h, ((p + r) * cf + r * e) / h, 0],
        [0, 0, r * np.cos(u) / h],
        [0, 0, r * np.sin(u) / (h * np.sin(i))],
        [-p * cf / (h * e), (p + r) * sf / (h * e), -r * np.sin(u) * np.cos(i) / (h * np.sin(i))],
        [b * (p * cf - 2 * r * e) / (a * h * e), -b * (p + r) * sf / (a * h * e), 0],
        [p * cf / (h * e), -(p + r) * sf / (h * e), 0],
        [0, 0, -r * np.sin(u) * np.cos(i) / (h * np.sin(i))]])


def B_tnw(a, e, i, om, f):
    """Rows a, e, i, Omega, omega, M; columns a_T, a_N, a_W (N = W x T, towards the centre of curvature)."""
    p = a * (1 - e * e); r = p / (1 + e * np.cos(f)); h = np.sqrt(MU * p); b = a * np.sqrt(1 - e * e)
    v = np.sqrt(MU * (2 / r - 1 / a)); u = om + f; sf, cf = np.sin(f), np.cos(f)
    return np.array([
        [2 * a * a * v / MU, 0, 0],
        [2 * (e + cf) / v, -r * sf / (a * v), 0],
        [0, 0, r * np.cos(u) / h],
        [0, 0, r * np.sin(u) / (h * np.sin(i))],
        [2 * sf / (e * v), (2 * e + r * cf / a) / (e * v), -r * np.sin(u) * np.cos(i) / (h * np.sin(i))],
        [-2 * b / (e * a * v) * (1 + e * e * r / p) * sf, -b / (e * a * v) * r / a * cf, 0]])


rng = np.random.default_rng(1)
# ======================================================================= A. finite differences
print("A. velocity gradients by central differences, 500 random orbits")
worst_r, worst_t = np.zeros(8), np.zeros(6)
for _ in range(500):
    a = rng.uniform(7000, 42000); e = rng.uniform(0.02, 0.9); i = rng.uniform(0.1, np.pi - 0.1)
    Om, om, f = rng.uniform(0, 2 * np.pi, 3)
    if a * (1 - e) < 6600:
        a = 6600 / (1 - e)
    r, v = rv(a, e, i, Om, om, f)
    R, S, W = rsw(r, v)
    vn = np.linalg.norm(v); T = v / vn; N = np.cross(W, T)
    eps = 1e-6 * vn
    Br, Bt = B_rsw(a, e, i, om, f), B_tnw(a, e, i, om, f)
    for col, d in enumerate((R, S, W)):
        fd = (coe(r, v + eps * d) - coe(r, v - eps * d)) / (2 * eps)
        fd[2:] = wrap(fd[2:] * 2 * eps) / (2 * eps)
        idx = [0, 1, 2, 3, 4, 6, 5, 7]                       # coe order -> B row order
        for row in range(8):
            ref = Br[row, col]; num = fd[idx[row]]
            scale = max(np.abs(Br[row]).max(), 1e-30)
            worst_r[row] = max(worst_r[row], abs(num - ref) / scale)
    for col, d in enumerate((T, N, W)):
        fd = (coe(r, v + eps * d) - coe(r, v - eps * d)) / (2 * eps)
        fd[2:] = wrap(fd[2:] * 2 * eps) / (2 * eps)
        idx = [0, 1, 2, 3, 4, 6]
        for row in range(6):
            scale = max(np.abs(Bt[row]).max(), 1e-30)
            worst_t[row] = max(worst_t[row], abs(fd[idx[row]] - Bt[row, col]) / scale)
for k, nm in enumerate(["a", "e", "i", "Omega", "omega", "M", "f", "u"]):
    lim = 1e-5 if nm == "u" else 1e-6                      # u carries 1/sin i, so its differences are noisier
    truth(f"RSW row {nm:<6}: worst relative error {worst_r[k]:.1e} (< {lim:.0e})", worst_r[k] < lim)
for k, nm in enumerate(["a", "e", "i", "Omega", "omega", "M"]):
    truth(f"TNW row {nm:<6}: worst relative error {worst_t[k]:.1e} (< 1e-6)", worst_t[k] < 1e-6)

# h and p rates, and the eccentricity-vector rate, by finite differences on one orbit
a, e, i, Om, om, f = 9000, 0.3, 0.9, 0.5, 0.7, 1.1
r, v = rv(a, e, i, Om, om, f); R, S, W = rsw(r, v); eps = 1e-6 * np.linalg.norm(v)
p = a * (1 - e * e); rn = np.linalg.norm(r); h = np.sqrt(MU * p)
hfd = (np.linalg.norm(np.cross(r, v + eps * S)) - np.linalg.norm(np.cross(r, v - eps * S))) / (2 * eps)
check("h-dot per unit a_S = r", hfd / rn, 1.0, 1e-8)
evec = lambda vv: ((vv @ vv - MU / rn) * r - (r @ vv) * vv) / MU
vR = v @ R
for d, nm in ((R, "R"), (S, "S"), (W, "W")):
    num = (evec(v + eps * d) - evec(v - eps * d)) / (2 * eps)
    aR, aS, aW = d @ R, d @ S, d @ W
    ana = (2 * h * aS * R - (h * aR + rn * vR * aS) * S - rn * vR * aW * W) / MU
    check(f"eccentricity-vector rate, unit a_{nm}: max difference", np.abs(num - ana).max() / np.abs(ana).max(), 0, 1e-6)

# ======================================================================= B. identities
print("B. identities and alternative forms")
for _ in range(200):
    a = rng.uniform(7000, 42000); e = rng.uniform(0.01, 0.9); f = rng.uniform(0, 2 * np.pi)
    p = a * (1 - e * e); r = p / (1 + e * np.cos(f)); h = np.sqrt(MU * p)
    E = 2 * np.arctan2(np.sqrt(1 - e) * np.sin(f / 2), np.sqrt(1 + e) * np.cos(f / 2))
    assert abs(p - r - r * e * np.cos(f)) < 1e-6 * p
    assert abs(r / p * (e + np.cos(f)) - np.cos(E)) < 1e-12
    assert abs(((p + r) * np.cos(f) + r * e) / h - np.sqrt(p / MU) * (np.cos(f) + np.cos(E))) < 1e-12 * abs(p / h) + 1e-15
truth("(I1) p - r = r e cos f, (I3) (r/p)(e + cos f) = cos E, and the cos E form of e-dot, 200 orbits", True)
worst = 0
for _ in range(200):
    a = rng.uniform(7000, 42000); e = rng.uniform(0.02, 0.9); i = rng.uniform(0.1, 3.0); om, f = rng.uniform(0, 6.28, 2)
    B = B_rsw(a, e, i, om, f); n = np.sqrt(MU / a ** 3); r = a * (1 - e * e) / (1 + e * np.cos(f))
    for aR, aS, aW in np.eye(3):
        full = B[5] @ [aR, aS, aW]
        compact = -2 * r / np.sqrt(MU * a) * aR - np.sqrt(1 - e * e) * (B[4] @ [aR, aS, aW] + np.cos(i) * (B[3] @ [aR, aS, aW]))
        worst = max(worst, abs(full - compact) / max(np.abs(B[5]).max(), 1e-30))
check("compact M-dot against the boxed form (worst relative)", worst, 0, 1e-12)

# ======================================================================= C. J2 in RSW
print("C. the J2 acceleration in RSW")
worst = 0
for _ in range(200):
    a = rng.uniform(6800, 30000); e = rng.uniform(0, 0.7); i, Om, om, f = rng.uniform(0, np.pi), *rng.uniform(0, 6.28, 3)
    r, v = rv(a, e, i, Om, om, f); R, S, W = rsw(r, v); rn = np.linalg.norm(r); x, y, z = r
    k = 1.5 * J2 * MU * RE ** 2 / rn ** 5
    acc = -k * np.array([x * (1 - 5 * z * z / rn ** 2), y * (1 - 5 * z * z / rn ** 2), z * (3 - 5 * z * z / rn ** 2)])
    u = om + f; c = 3 * MU * J2 * RE ** 2 / rn ** 4
    ana = np.array([c / 2 * (3 * np.sin(i) ** 2 * np.sin(u) ** 2 - 1), -c * np.sin(i) ** 2 * np.sin(u) * np.cos(u),
                    -c * np.sin(i) * np.cos(i) * np.sin(u)])
    worst = max(worst, np.abs(np.array([acc @ R, acc @ S, acc @ W]) - ana).max() / np.abs(acc).max())
check("J2 RSW components against the Cartesian J2 acceleration (worst relative)", worst, 0, 1e-12)


# ======================================================================= D. orbit averages
print("D. orbit averages with J2")


def averages(a, e, i, om, nf=20000):
    p = a * (1 - e * e); h = np.sqrt(MU * p); n = np.sqrt(MU / a ** 3)
    f = np.linspace(0, 2 * np.pi, nf, endpoint=False); r = p / (1 + e * np.cos(f)); u = om + f
    c = 3 * MU * J2 * RE ** 2 / r ** 4
    aR = c / 2 * (3 * np.sin(i) ** 2 * np.sin(u) ** 2 - 1); aS = -c * np.sin(i) ** 2 * np.sin(u) * np.cos(u)
    aW = -c * np.sin(i) * np.cos(i) * np.sin(u)
    w = r ** 2 / h * n / (2 * np.pi) * (2 * np.pi / nf)          # dt/T per step in f
    Od = r * np.sin(u) / (h * np.sin(i)) * aW
    idot = r * np.cos(u) / h * aW
    od_in = (-p * np.cos(f) * aR + (p + r) * np.sin(f) * aS) / (h * e) if e > 0 else np.nan * f
    return (w * Od).sum(), (w * idot).sum(), (w * (od_in - np.cos(i) * Od)).sum(), (w * od_in).sum()


deg_day = 180 / np.pi * DAY
for a, e, i_d, om_d, Os, oms in ((7000, 0.0, 98, 0, 1.001328, None), (9000, 0.3, 50, 40, -2.317396, 1.921369),
                                 (12000, 0.4, 63, 25, -0.701808, 0.023603), (26000, 0.7, 30, 250, -0.242576, 0.385141)):
    i, om = np.radians(i_d), np.radians(om_d)
    p = a * (1 - e * e); n = np.sqrt(MU / a ** 3)
    Oc = -1.5 * n * J2 * (RE / p) ** 2 * np.cos(i)
    oc = 0.75 * n * J2 * (RE / p) ** 2 * (5 * np.cos(i) ** 2 - 1)
    On, In, on, oin = averages(a, e, i, om)
    check(f"<Omega-dot> a={a}, e={e}, i={i_d} [deg/day]", Oc * deg_day, Os, 5e-7)
    check(f"  numerical average against the closed form [deg/day]", (On - Oc) * deg_day, 0, 1e-9)
    check(f"  <i-dot> [deg/day]", In * deg_day, 0, 1e-12)
    if oms is not None:
        check(f"  <omega-dot> [deg/day]", oc * deg_day, oms, 5e-7)
        check(f"  numerical average against the closed form [deg/day]", (on - oc) * deg_day, 0, 1e-9)
        check(f"  in-plane part = (3/4) n J2 (R/p)^2 (3cos^2 i - 1) [deg/day]",
              (oin - 0.75 * n * J2 * (RE / p) ** 2 * (3 * np.cos(i) ** 2 - 1)) * deg_day, 0, 1e-9)

# the two integrals of the derivation, at random e and omega
for _ in range(5):
    e, om = rng.uniform(0, 0.9), rng.uniform(0, 6.28)
    f = np.linspace(0, 2 * np.pi, 40000, endpoint=False); df = 2 * np.pi / 40000; s2 = rng.uniform(0, 1)
    I1 = (np.cos(f) * (1 + e * np.cos(f)) ** 2 * (3 * s2 * np.sin(om + f) ** 2 - 1)).sum() * df
    I2 = (np.sin(f) * np.sin(om + f) * np.cos(om + f) * (2 + e * np.cos(f)) * (1 + e * np.cos(f))).sum() * df
    assert abs(I1 - ((1.5 * s2 - 1) * 2 * np.pi * e - 1.5 * s2 * e * np.pi * np.cos(2 * om))) < 1e-9
    assert abs(I2 - 0.75 * e * np.pi * np.cos(2 * om)) < 1e-9
truth("the integrals I1 and I2 of the omega average, at random e, omega and sin^2 i", True)

# ======================================================================= E. numbers on the page
print("E. numbers quoted in the note")
a = 7000.0; n = np.sqrt(MU / a ** 3)
sun = 360 / 365.2422
check("sun-synchronous rate [deg/day]", sun, 0.985647, 5e-7)
i_ss = np.degrees(np.arccos(-np.radians(sun) / DAY / (1.5 * n * J2 * (RE / a) ** 2)))
check("sun-synchronous inclination at a = 7000 km [deg]", i_ss, 97.874, 5e-4)
# Try it: 1 m/s out-of-plane burns on a 7000 km circle
vc = np.sqrt(MU / a)
check("circular speed at 7000 km [km/s]", vc, 7.546, 5e-4)
check("1 m/s W burn at u = 0: di [deg]", np.degrees(a * 1e-3 / np.sqrt(MU * a)), 0.00759, 5e-6)
check("  same burn at u = 90 deg, i = 51.6 deg: dOmega [deg]", np.degrees(a * 1e-3 / (np.sqrt(MU * a) * np.sin(np.radians(51.6)))), 0.00969, 5e-6)
check("  ... and domega = -cos i dOmega [deg]", -np.cos(np.radians(51.6)) * np.degrees(a * 1e-3 / (np.sqrt(MU * a) * np.sin(np.radians(51.6)))), -0.00602, 5e-6)
# radial impulse at periapsis: a and e unchanged, omega back, f forward by the same amount
a, e = 9000.0, 0.3; p = a * (1 - e * e); h = np.sqrt(MU * p)
r, v = rv(a, e, 0.9, 0.5, 0.7, 0.0); R, S, W = rsw(r, v)
d = coe(r, v + 1e-6 * R) - coe(r, v)
check("radial impulse at periapsis: da per unit dv [km per km/s]", d[0] / 1e-6, 0, 1e-3)
check("  de per unit dv", d[1] / 1e-6, 0, 1e-6)
check("  domega + p/(h e) per unit dv", d[4] / 1e-6 + p / (h * e), 0, 1e-4)
check("  df - p/(h e) per unit dv", d[5] / 1e-6 - p / (h * e), 0, 1e-4)

# ======================================================================= F. end to end
print("F. end-to-end: Gauss equations against Cartesian dynamics (J2 + thrust), five periods")


def thrust(t):
    return np.array([2e-6 * np.cos(t / 900), 3e-6, 2.5e-6 * np.sin(t / 1300)])


def j2acc(r):
    rn = np.linalg.norm(r); x, y, z = r; k = 1.5 * J2 * MU * RE ** 2 / rn ** 5
    return -k * np.array([x * (1 - 5 * z * z / rn ** 2), y * (1 - 5 * z * z / rn ** 2), z * (3 - 5 * z * z / rn ** 2)])


def cart(t, y):
    r, v = y[:3], y[3:]; R, S, W = rsw(r, v)
    return np.concatenate([v, -MU * r / np.linalg.norm(r) ** 3 + j2acc(r) + np.column_stack([R, S, W]) @ thrust(t)])


def kepler(M, e):
    E = M
    for _ in range(50):
        E -= (E - e * np.sin(E) - M) / (1 - e * np.cos(E))
    return E


def gauss(t, y, mode):
    a, e, i, Om, om, s6 = y
    f = s6 if mode == "f" else 2 * np.arctan2(np.sqrt(1 + e) * np.sin(kepler(s6, e) / 2), np.sqrt(1 - e) * np.cos(kepler(s6, e) / 2))
    r, v = rv(a, e, i, Om, om, f); R, S, W = rsw(r, v)
    ad = np.array([j2acc(r) @ R, j2acc(r) @ S, j2acc(r) @ W]) + thrust(t)
    B = B_rsw(a, e, i, om, f); p = a * (1 - e * e); h = np.sqrt(MU * p); rn = p / (1 + e * np.cos(f))
    dy = B[:6] @ ad
    dy[5] += np.sqrt(MU / a ** 3)
    if mode == "f":
        dy[5] = h / rn ** 2 + B[6] @ ad
    return dy


el0 = [9000.0, 0.3, np.radians(50), np.radians(30), np.radians(40), np.radians(10)]
r0, v0 = rv(*el0)
Tp = 2 * np.pi * np.sqrt(9000.0 ** 3 / MU); tf = 5 * Tp
kw = dict(method="DOP853", rtol=1e-12, atol=1e-12)
sc = solve_ivp(cart, [0, tf], np.concatenate([r0, v0]), **kw)
E0 = 2 * np.arctan2(np.sqrt(1 - 0.3) * np.sin(el0[5] / 2), np.sqrt(1 + 0.3) * np.cos(el0[5] / 2))
for mode, s60 in (("M", E0 - 0.3 * np.sin(E0)), ("f", el0[5])):
    sg = solve_ivp(gauss, [0, tf], el0[:5] + [s60], args=(mode,), **kw)
    a, e, i, Om, om, s6 = sg.y[:, -1]
    f = s6 if mode == "f" else 2 * np.arctan2(np.sqrt(1 + e) * np.sin(kepler(s6, e) / 2), np.sqrt(1 - e) * np.cos(kepler(s6, e) / 2))
    rg, _ = rv(a, e, i, Om, om, f)
    d = np.linalg.norm(rg - sc.y[:3, -1])
    print(f"    carrying {mode}: final position difference {d * 1e6:.3f} mm at r = {np.linalg.norm(rg):.0f} km")
    truth(f"end-to-end with {mode}: relative difference {d / np.linalg.norm(rg):.1e} (< 1e-9)", d / np.linalg.norm(rg) < 1e-9)

print(f"\n{sum(RESULTS)} PASS, {len(RESULTS) - sum(RESULTS)} FAIL")
