"""Checks the numbers quoted in earth-gravity-perturbations.qmd.

A. Legendre polynomials and the coefficient estimates (spheroid, Clairaut, MacCullagh, the Kaula comparison).
B. The J2 secular rates: ISS, GPS, sun-synchronous orbits, Exercise 6, the first-order mean-motion change
   (against the Lagrange equation evaluated by finite differences on the averaged disturbing function).
C. The five-day numerical experiment of @sec-validation (fitted slopes of the osculating Omega and omega).
D. Geostationary drift from C22, S22: J22, the long axis, the equilibria, the peak acceleration, libration.
E. Exercise 4 (the J2 acceleration in Cartesian and spherical components).

Run from the sfm-slides directory:   python3 codes/earth-gravity-verify.py
"""
import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import brentq
from numpy.polynomial import legendre as L

RESULTS = []
MU, RE, J2 = 398600.4418, 6378.137, 1.08263e-3
C22, S22 = 1.5745e-6, -9.0387e-7
J3, J4 = -2.5327e-6, -1.6196e-6
DAY, D2R = 86400.0, np.pi / 180
WE = 7.2921151e-5


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


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


# ======================================================================= A
print("A. Legendre polynomials and coefficient estimates")
P = [np.array([1.0]), np.array([0.0, 1.0])]
for n in range(1, 6):                                       # Bonnet: (n+1)P_{n+1} = (2n+1) x P_n - n P_{n-1}
    P.append(((2 * n + 1) * np.convolve([0, 1], P[n]) - n * np.pad(P[n - 1], (0, 2))[:n + 2]) / (n + 1))
truth("Bonnet recurrence reproduces numpy's P_0..P_6", all(np.allclose(np.polynomial.polynomial.polyval(np.linspace(-1, 1, 9), P[k]),
                                                            L.legval(np.linspace(-1, 1, 9), [0] * k + [1])) for k in range(7)))
check("P_5(1)", np.polynomial.polynomial.polyval(1.0, P[5]), 1.0, 1e-12)
check("J2 from MacCullagh, 0.3307/305.4", 0.3307 / 305.4, 1.08e-3, 5e-6)
check("homogeneous spheroid 2f/5, f = 1/298.26", 2 / 5 / 298.26, 1.34e-3, 5e-6)
m = WE ** 2 * RE ** 3 / MU
check("Clairaut m = omega^2 R^3/mu", m, 3.461e-3, 5e-7)
check("Clairaut (2f - m)/3, f = 1/298.257", (2 / 298.257 - m) / 3, 1.081e-3, 5e-7)
check("Exercise 8: C/(M R^2) = 305.4 J2", 305.4 * J2, 0.3306, 5e-4)
Jb2 = J2 / np.sqrt(5)
check("normalised J2bar", Jb2, 4.84e-4, 5e-7)
check("Kaula's rule at n = 2", 1e-5 / 4, 2.5e-6, 1e-12)
check("J2bar / Kaula (about 200)", Jb2 / 2.5e-6, 200, 10)
truth("J3bar, J4bar, |C22bar,S22bar| all within a factor 3 of Kaula's rule",
      all(1 / 3 < v / (1e-5 / n ** 2) < 3 for v, n in ((abs(J3) / np.sqrt(7), 3), (abs(J4) / 3, 4),
                                                        (np.hypot(C22, S22) / np.sqrt(10 / 24), 2))))

# ======================================================================= B
print("B. J2 secular rates")


def rates(a, e, i):
    n = np.sqrt(MU / a ** 3); p = a * (1 - e * e); k = n * J2 * (RE / p) ** 2
    return -1.5 * k * np.cos(i), 0.75 * k * (5 * np.cos(i) ** 2 - 1), n * (1 + 0.75 * J2 * (RE / p) ** 2 * np.sqrt(1 - e * e) * (3 * np.cos(i) ** 2 - 1))


dd = DAY / D2R
Od, _, _ = rates(RE + 420, 0, 51.6 * D2R)
check("ISS Omega-dot [deg/day]", Od * dd, -4.95, 0.005)
check("ISS: days for one turn of the plane", 360 / abs(Od * dd), 73, 0.5)
check("GPS Omega-dot [deg/day]", rates(RE + 20200, 0, 55 * D2R)[0] * dd, -0.039, 0.0005)
sun = 360 / 365.2422
check("mean Sun [deg/day]", sun, 0.9856, 5e-5)
iss = lambda a: np.degrees(np.arccos(-(sun * D2R / DAY) / (1.5 * np.sqrt(MU / a ** 3) * J2 * (RE / a) ** 2)))
check("sun-synchronous inclination at 700 km [deg]", iss(RE + 700), 98.19, 0.005)
h6 = brentq(lambda h: iss(RE + h) - 98.6, 300, 1500)
check("Exercise 6: altitude for i = 98.6 deg [km]", h6, 800, 5)
check("critical inclination [deg]", np.degrees(np.arccos(1 / np.sqrt(5))), 63.435, 5e-4)
check("its supplement [deg]", 180 - np.degrees(np.arccos(1 / np.sqrt(5))), 116.565, 5e-4)
check("validation case Omega-dot (a=8000, e=0.1, i=50) [deg/day]", rates(8000, 0.1, 50 * D2R)[0] * dd, -2.957, 5e-4)
check("validation case omega-dot [deg/day]", rates(8000, 0.1, 50 * D2R)[1] * dd, 2.452, 5e-4)
check("M-dot faster than n below 54.7 deg (3cos^2 i = 1 at) [deg]", np.degrees(np.arccos(1 / np.sqrt(3))), 54.7, 0.05)


def Rbar(a, e, i):                                          # orbit-averaged J2 disturbing function
    return MU * J2 * RE ** 2 / (4 * a ** 3 * (1 - e * e) ** 1.5) * (3 * np.cos(i) ** 2 - 1)


worst = 0
for a, e, i in ((7000, 0.01, 0.3), (8000, 0.1, 50 * D2R), (12000, 0.4, 1.1), (26000, 0.7, 2.6)):
    n = np.sqrt(MU / a ** 3); ha, he = 1e-3, 1e-7
    dRa = (Rbar(a + ha, e, i) - Rbar(a - ha, e, i)) / (2 * ha)
    dRe = (Rbar(a, e + he, i) - Rbar(a, e - he, i)) / (2 * he)
    Mdot = n - 2 / (n * a) * dRa - (1 - e * e) / (n * a * a * e) * dRe
    worst = max(worst, abs(Mdot - rates(a, e, i)[2]) / abs(rates(a, e, i)[2] - n))
check("M-dot: Lagrange equation by finite differences vs the boxed formula (rel.)", worst, 0, 1e-5)

# ======================================================================= C
print("C. the five-day numerical experiment")


def acc(t, s):
    r, v = s[:3], s[3:]; rn = np.linalg.norm(r); x, y, z = r; k = -1.5 * J2 * MU * RE ** 2 / rn ** 5
    return np.concatenate([v, -MU * r / rn ** 3 + 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 coe2rv(a, e, i, Om, w, nu):
    p = a * (1 - e ** 2); rp = p / (1 + e * np.cos(nu)) * np.array([np.cos(nu), np.sin(nu), 0])
    vp = np.sqrt(MU / p) * np.array([-np.sin(nu), e + np.cos(nu), 0])
    R3 = lambda x: np.array([[np.cos(x), -np.sin(x), 0], [np.sin(x), np.cos(x), 0], [0, 0, 1]])
    R1 = lambda x: np.array([[1, 0, 0], [0, np.cos(x), -np.sin(x)], [0, np.sin(x), np.cos(x)]])
    Q = R3(Om) @ R1(i) @ R3(w)
    return Q @ rp, Q @ vp


r0, v0 = coe2rv(8000.0, 0.1, 50 * D2R, 40 * D2R, 30 * D2R, 0.0)
tt = np.linspace(0, 5 * DAY, 6000)
sol = solve_ivp(acc, (0, 5 * DAY), np.concatenate([r0, v0]), t_eval=tt, rtol=1e-12, atol=1e-9, method="DOP853")
Om, w = [], []
for k in range(len(tt)):
    r, v = sol.y[:3, k], sol.y[3:, k]; h = np.cross(r, v); ev = np.cross(v, h) / MU - r / np.linalg.norm(r)
    N = np.array([-h[1], h[0], 0]); Om.append(np.arctan2(h[0], -h[1]))
    w.append(np.arctan2(np.dot(np.cross(N, ev), h) / np.linalg.norm(h), np.dot(N, ev)))
slope = lambda y: np.polyfit(tt, np.unwrap(y), 1)[0] * dd
check("fitted Omega-dot over five days [deg/day]", slope(Om), -2.964, 5e-4)
check("fitted omega-dot over five days [deg/day]", slope(w), 2.459, 5e-4)

# ======================================================================= D
print("D. geostationary drift")
J22 = np.hypot(C22, S22); lam22 = 0.5 * np.degrees(np.arctan2(S22, C22))
check("J22", J22, 1.8155e-6, 5e-11)
check("lambda22 [deg]", lam22, -14.9, 0.05)
check("stable longitude east [deg]", lam22 + 90, 75.1, 0.05)
check("stable longitude west [deg]", -(lam22 - 90), 104.9, 0.05)
check("unstable longitude [deg E]", lam22 + 180, 165.1, 0.05)
aG = 42164.0
pk = 18 * MU * RE ** 2 * J22 / aG ** 5 * 1e3 * 1e-3           # rad/s^2 (km units cancel)
check("peak lambda-ddot [rad/s^2]", pk, 3.98e-15, 5e-18)
check("  in deg/day^2", np.degrees(pk) * DAY ** 2, 1.70e-3, 5e-6)
check("libration period [yr]", 2 * np.pi / np.sqrt(2 * pk) / (365.25 * DAY), 2.2, 0.05)

# ======================================================================= E
print("E. Exercise 4")
r = np.array([4500.0, 3000.0, 5000.0]); rn = np.linalg.norm(r); x, y, z = r
k = -1.5 * J2 * MU * RE ** 2 / rn ** 5
aC = k * np.array([x * (1 - 5 * z * z / rn ** 2), y * (1 - 5 * z * z / rn ** 2), z * (3 - 5 * z * z / rn ** 2)])
phi = np.arcsin(z / rn); c = 1.5 * J2 * MU * RE ** 2 / rn ** 4
ar = c * (3 * np.sin(phi) ** 2 - 1); aphi = -c * np.sin(2 * phi)         # radial and northward components
er = r / rn; en = np.array([-np.sin(phi) * x / np.hypot(x, y), -np.sin(phi) * y / np.hypot(x, y), np.cos(phi)])
check("Exercise 4: Cartesian and spherical forms agree (max diff, km/s^2)", np.abs(aC - (ar * er + aphi * en)).max(), 0, 1e-15)

# ======================================================================= F
print("F. added: the ISS worked example, the ring exercise, the torque remark")
aI = RE + 420; nI = np.sqrt(MU / aI ** 3); kI = nI * J2 * (RE / aI) ** 2
check("ISS n [rad/s]", nI, 1.12638e-3, 5e-9)
check("ISS (R/a)^2", (RE / aI) ** 2, 0.880254, 5e-7)
check("ISS n J2 (R/a)^2 [deg/day]", kI * dd, 5.3138, 5e-5)
check("ISS omega-dot [deg/day]", 0.75 * kI * (5 * np.cos(51.6 * D2R) ** 2 - 1) * dd, 3.70, 0.005)
check("ISS M-dot - n [deg/day]", 0.75 * kI * (3 * np.cos(51.6 * D2R) ** 2 - 1) * dd, 0.63, 0.005)
TI = 2 * np.pi / nI
OI = -1.5 * kI * np.cos(51.6 * D2R)
check("ISS node per orbit [deg]", abs(OI * TI) / D2R, 0.32, 0.005)
check("  at the equator [km]", abs(OI * TI) * RE, 36, 0.5)
ring_pts = np.linspace(0, 2 * np.pi, 100001)[:-1]
check("ring in its own plane: <P2(cos gamma)>", np.mean(1.5 * np.cos(ring_pts) ** 2 - 0.5), 0.25, 1e-9)
check("osculating a amplitude 1.5 J2 R^2/a at 400 km [km]", 1.5 * J2 * RE ** 2 / (RE + 400), 10, 0.5)

print("Worked solutions of the exercises")
import sympy as _sp
_x = _sp.symbols("x"); _P = [_sp.Integer(1), _x]
for _n in range(1, 5): _P.append(_sp.expand(((2*_n + 1)*_x*_P[_n] - _n*_P[_n - 1])/(_n + 1)))
truth("Ex 1: P3 = (5x^3-3x)/2", _sp.expand(_P[3] - (5*_x**3 - 3*_x)/2) == 0)
truth("Ex 1: P5 = (63x^5-70x^3+15x)/8", _sp.expand(_P[5] - (63*_x**5 - 70*_x**3 + 15*_x)/8) == 0)
truth("Ex 1: 9x P4 and 4 P3 pieces", _sp.expand(9*_x*_P[4] - (315*_x**5 - 270*_x**3 + 27*_x)/8) == 0 and _sp.expand(4*_P[3] - (80*_x**3 - 48*_x)/8) == 0)
check("Ex 1: P5(1)", float(_P[5].subs(_x, 1)), 1.0, 0)
truth("Ex 1: P3 solves Legendre n = 3", _sp.expand((1 - _x**2)*_sp.diff(_P[3], _x, 2) - 2*_x*_sp.diff(_P[3], _x) + 12*_P[3]) == 0)
_r, _a, _G, _m, _ph = _sp.symbols("r a G m phi", positive=True)
_phs = np.linspace(0, 2*np.pi, 20001)[:-1]; _rr, _aa = 1.0, 0.2
_Unum = np.mean(1/np.sqrt(_rr**2 + _aa**2 - 2*_aa*_rr*np.cos(_phs)))
check("Ex 2: in-plane mean 1/s vs 1/r (1 + a^2/(4r^2) + 9a^4/(64r^4))", _Unum, (1 + _aa**2/4 + 9*_aa**4/64)/_rr, 2e-5)
truth("Ex 2: in-plane pull Gm/r^2 (1 + 3a^2/(4r^2))", _sp.simplify(-_sp.diff(_G*_m/_r*(1 + _a**2/(4*_r**2)), _r) - _G*_m/_r**2*(1 + 3*_a**2/(4*_r**2))) == 0)
truth("Ex 2: on-axis pull Gm/z^2 (1 - 3a^2/(2z^2))", _sp.simplify(-_sp.diff(_G*_m/_r*(1 - _a**2/(2*_r**2)), _r) - _G*_m/_r**2*(1 - 3*_a**2/(2*_r**2))) == 0)
_A, _C = _sp.symbols("A C", positive=True)
truth("Ex 3: axis U2 = G(A-C)/r^3", _sp.simplify(_G/(2*_r**3)*(2*_A + _C - 3*_C) - _G*(_A - _C)/_r**3) == 0)
truth("Ex 3: equator U2 = G(C-A)/(2r^3)", _sp.simplify(_G/(2*_r**3)*(2*_A + _C - 3*_A) - _G*(_C - _A)/(2*_r**3)) == 0)
_mu4 = 398600.44; _rv = np.array([4500.0, 3000.0, 5000.0]); _rn = np.linalg.norm(_rv); _zz = (_rv[2]/_rn)**2
_k = -1.5*_mu4*J2*RE**2/_rn**5
check("Ex 4: r", _rn, 7365.46, 0.005); check("Ex 4: z^2/r^2", _zz, 0.46083, 5e-6); check("Ex 4: k", _k, -1.2148e-9, 5e-14)
check("Ex 4: 1-5z^2/r^2", 1 - 5*_zz, -1.3041, 5e-5); check("Ex 4: 3-5z^2/r^2", 3 - 5*_zz, 0.6959, 5e-5)
_ac = np.array([_k*_rv[0]*(1 - 5*_zz), _k*_rv[1]*(1 - 5*_zz), _k*_rv[2]*(3 - 5*_zz)])*1e3
for _c, _q in zip(_ac, (7.129e-3, 4.753e-3, -4.227e-3)): check("Ex 4: Cartesian component [m/s^2]", _c, _q, 5e-7)
check("Ex 4: |a|", np.linalg.norm(_ac), 9.554e-3, 5e-7); check("Ex 4: mu/r^2 [m/s^2]", _mu4/_rn**2*1e3, 7.347, 5e-4); check("Ex 4: ratio %", 100*np.linalg.norm(_ac)/(_mu4/_rn**2*1e3), 0.13, 0.005)
_phi = np.arcsin(_rv[2]/_rn); _lam = np.arctan2(_rv[1], _rv[0])
check("Ex 4: phi", np.degrees(_phi), 42.75, 0.005); check("Ex 4: lambda", np.degrees(_lam), 33.69, 0.005)
_ar = 1.5*_mu4*J2*RE**2/_rn**4*(3*np.sin(_phi)**2 - 1)*1e3; _ap = -1.5*_mu4*J2*RE**2/_rn**4*np.sin(2*_phi)*1e3
check("Ex 4: a_r", _ar, 3.422e-3, 5e-7); check("Ex 4: a_phi", _ap, -8.920e-3, 5e-7); check("Ex 4: sign-change latitude", np.degrees(np.arcsin(1/np.sqrt(3))), 35.26, 0.005)
_ph_hat = np.array([-np.sin(_phi)*np.cos(_lam), -np.sin(_phi)*np.sin(_lam), np.cos(_phi)])
check("Ex 4: spherical = Cartesian", np.linalg.norm(_ar*_rv/_rn + _ap*_ph_hat - _ac), 0, 1e-18)
_i5 = _sp.symbols("i")
truth("Ex 5: polar omega-dot bracket = -1, a quarter of the equatorial 4", (5*_sp.cos(_sp.pi/2)**2 - 1) == -1)
_adot = 2*np.pi/(365.2422*86400)
check("Ex 6: Omega-dot sun [rad/s]", _adot, 1.991e-7, 5e-11); check("Ex 6: cos 98.6", np.cos(np.radians(98.6)), -0.14954, 5e-6)
_a6 = (-3*J2*RE**2*np.sqrt(MU)*np.cos(np.radians(98.6))/(2*_adot))**(2/7)
check("Ex 6: a", _a6, 7177.4, 0.05); check("Ex 6: altitude", _a6 - RE, 799, 0.5)
_K6 = np.degrees(_adot)*86400/np.cos(np.radians(98.6))
_dO = abs(_K6*np.sin(np.radians(98.6))*np.radians(0.1))
check("Ex 6: dOmega-dot per 0.1 deg [deg/day]", _dO, 0.011, 5e-4); check("Ex 6: local-time drift [min/yr]", _dO*365.25*4, 17, 0.5)
_J22 = np.hypot(C22, S22); _l22 = 0.5*np.degrees(np.arctan2(S22, C22)); _amp = 18*MU*RE**2*_J22/42164.0**5
check("Ex 7: J22", _J22, 1.8155e-6, 5e-11); check("Ex 7: lambda22", _l22, -14.93, 0.005)
check("Ex 7: peak [rad/s^2]", _amp, 3.976e-15, 5e-19); check("Ex 7: peak [deg/day^2]", np.degrees(_amp)*86400**2, 1.70e-3, 5e-6)
_s7 = np.sin(2*np.radians(60 - _l22)); check("Ex 7: 2(lambda-lambda22) [deg]", 2*(60 - _l22), 149.86, 0.005); check("Ex 7: sin", _s7, 0.5021, 5e-5)
_ldd = np.degrees(_amp)*86400**2*_s7; check("Ex 7: lambda-ddot", _ldd, 8.54e-4, 5e-7)
check("Ex 7: drift 30 d", 0.5*_ldd*900, 0.38, 0.005); check("Ex 7: along arc [km]", 42164*np.radians(0.5*_ldd*900), 280, 5)
check("Ex 7: time to 0.1 deg [d]", np.sqrt(2*0.1/_ldd), 15, 0.5)
_f = 1/298.26
check("Ex 8: (2f-f^2)/5", (2*_f - _f**2)/5, 1.339e-3, 5e-7); check("Ex 8: 2f/5", 2*_f/5, 1.341e-3, 5e-7)
check("Ex 8: too large %", 100*((2*_f - _f**2)/5/1.083e-3 - 1), 24, 0.5); check("Ex 8: C/MR^2", J2*305.4, 0.3306, 5e-5)

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