"""Verification of every identity and number quoted in the chase note (chase-lambert.qmd).

Part A is symbolic (sympy); Part B reproduces the numbers, section by section.  The porkchop
statements are checked by minimising over the time of flight at a fixed departure phase (or
epoch), not by reading the plotting grid.
Run:  python3 codes/chase-lambert-verify.py        (two to three minutes)
"""
import warnings
import numpy as np
import sympy as sp
from scipy.optimize import brentq, minimize, minimize_scalar
from _lambertp import mu, RE, cw_stm, lambert_vec, state_planar
from _chase_grids import solve

warnings.simplefilter("ignore")
ok = lambda label, cond: print(f"  [{'ok' if cond else 'FAIL'}] {label}")
near = lambda x, y, tol: abs(x - y) <= tol
D = np.degrees

# =================================================================================== A. symbolic
print("A. symbolic")
tau, nn = sp.symbols("tau n", positive=True)
s_, c_ = sp.sin(tau), sp.cos(tau)
Prv = sp.Matrix([[s_/nn, 2*(1 - c_)/nn], [-2*(1 - c_)/nn, (4*s_ - 3*tau)/nn]])
ok("det Phi_rv = [8(1 - cos tau) - 3 tau sin tau] / n^2",
   sp.simplify(Prv.det() - (8*(1 - c_) - 3*tau*s_)/nn**2) == 0)
th, k, T = sp.symbols("theta k T", positive=True)
Tph = T*(1 - th/(2*sp.pi*k))
ok("k T_ph = k T - (theta/2pi) T", sp.simplify(k*Tph - (k*T - th/(2*sp.pi)*T)) == 0)
g = lambda t: 8*(1 - np.cos(t)) - 3*t*np.sin(t)
grid_t = np.linspace(0.01, 8*np.pi, 400001); gv = g(grid_t)
roots = [brentq(g, grid_t[i], grid_t[i + 1]) for i in range(len(grid_t) - 1) if gv[i]*gv[i + 1] < 0]
print("    roots of det Phi_rv for tau < 8 pi:", np.round(roots, 4).tolist())
odd = [r for r in roots if abs(r/(2*np.pi) - round(r/(2*np.pi))) > 1e-6]
ok("non-trivial roots: one in each (2 pi k, (2k+1) pi); first 8.8387 = 1.4067 T",
   near(odd[0], 8.8387, 1e-4) and near(odd[0]/(2*np.pi), 1.4067, 1e-4) and
   all(2*np.pi*(j + 1) < r < (2*j + 3)*np.pi for j, r in enumerate(odd)))

# ================================================================== B1. same orbit: phasing
print("B1. phasing at 420 km, 20 deg")
a = RE + 420.0; n = np.sqrt(mu/a**3); Tc = 2*np.pi/n; vc = np.sqrt(mu/a)
print(f"    a = {a:.3f} km, T = {Tc:.2f} s, v_c = {vc:.6f} km/s")
ok("T = 5578.22 s", near(Tc, 5578.22, 0.005))
rows = {(-1, 1): (6543.96, -88.3, 300.36, 1.463), (-1, 2): (6671.66, 167.0, 145.86, 3.013),
        (-1, 3): (6713.95, 251.6, 96.32, 4.562), (-1, 6): (6756.11, 335.9, 47.71, 9.211),
        (+1, 1): (7047.64, 919.0, 268.73, 1.636), (+1, 3): (6881.81, 587.3, 92.82, 4.735)}
good = True
for (sgn, kk), (aq, hq, dvq, tq) in rows.items():
    Tp = Tc*(1 + sgn*np.radians(20)/(2*np.pi*kk)); ap = (mu*(Tp/(2*np.pi))**2)**(1/3)
    dv = abs(np.sqrt(mu*(2/a - 1/ap)) - vc)*1e3; far = 2*ap - a - RE
    print(f"    {'behind' if sgn > 0 else 'ahead '} k={kk}: a_ph={ap:.2f}  far apsis {far:7.1f} km  2dv={2*dv:.2f} m/s  time {kk*Tp/3600:.3f} h")
    good &= near(ap, aq, 0.006) and near(far, hq, 0.06) and near(2*dv, dvq, 0.006) and near(kk*Tp/3600, tq, 0.0006)
ok("Example 1 table", good)
Tp3 = Tc*(1 - np.radians(20)/(6*np.pi)); ap3 = (mu*(Tp3/(2*np.pi))**2)**(1/3); vph3 = np.sqrt(mu*(2/a - 1/ap3))
print(f"    k=3 ahead: T_ph = {Tp3:.2f} s, perigee radius {2*ap3 - a:.2f} km, v_ph = {vph3:.6f} km/s, dv_ph = {1e3*(vc - vph3):.2f} m/s")
ok("k=3 working: T_ph = 5474.92 s, r_p = 6629.76 km, v = 7.609109, dv_ph = 48.16",
   near(Tp3, 5474.92, 0.005) and near(2*ap3 - a, 6629.76, 0.005) and near(vph3, 7.609109, 5e-7) and near(1e3*(vc - vph3), 48.16, 0.005))
print(f"    linear estimate v_c dT/(3T) at k=3: {1e3*vc*(20/1080)/3:.2f} m/s")
Tp12 = Tc*(1 - np.radians(20)/(24*np.pi)); ap12 = (mu*(Tp12/(2*np.pi))**2)**(1/3)
dv12 = 2e3*(vc - np.sqrt(mu*(2/a - 1/ap12)))
print(f"    k=12 ahead: rendezvous {dv12:.2f} m/s, {12*Tp12/3600:.2f} h, perigee altitude {2*ap12 - a - RE:.1f} km")
ok("k=12: 23.74 m/s, 18.51 h, perigee above 370 km", near(dv12, 23.74, 0.005) and near(12*Tp12/3600, 18.51, 0.005) and 2*ap12 - a - RE > 370)

print("B1'. phasing on an ellipse a = 10000 km, e = 0.3, 30 deg")
ae, ee = 10000.0, 0.3; ne = np.sqrt(mu/ae**3); Te = 2*np.pi/ne
def t_from_peri(f):
    E = 2*np.arctan(np.sqrt((1 - ee)/(1 + ee))*np.tan(f/2)); M = E - ee*np.sin(E); return E, M, M/ne
E30, M30, dt30 = t_from_peri(np.radians(30))
print(f"    T = {Te:.2f} s, n = {ne:.6e} rad/s, E = {E30:.6f}, M = {M30:.6f}, dt = {dt30:.2f} s")
ok("E = 0.388289, M = 0.274707, n = 6.313481e-4, dt = 435.11 s",
   near(E30, 0.388289, 1e-6) and near(M30, 0.274707, 1e-6) and near(ne, 6.313481e-4, 1e-10) and near(dt30, 435.11, 0.005))
def ell_phase(r, dt):
    Tp = Te + dt; ap = (mu*(Tp/(2*np.pi))**2)**(1/3)
    return Tp, ap, abs(np.sqrt(mu*(2/r - 1/ap)) - np.sqrt(mu*(2/r - 1/ae)))*1e3
Tp, ap, dvp = ell_phase(ae*(1 - ee), dt30)
dt_apo = Te/2 - t_from_peri(np.radians(150))[2]
_, ap_a, dva = ell_phase(ae*(1 + ee), dt_apo)
print(f"    periapsis: T_ph = {Tp:.2f} s, a_ph = {ap:.2f} km, 2 x {dvp:.3f} = {2*dvp:.2f} m/s")
print(f"    apoapsis : dt = {dt_apo:.2f} s ({dt_apo/dt30:.2f} x), a_ph = {ap_a:.2f} km, total {2*dva:.2f} m/s")
ok("periapsis: T_ph = 10387.13, a_ph = 10289.39, 2 x 64.904 = 129.81",
   near(Tp, 10387.13, 0.005) and near(ap, 10289.39, 0.005) and near(dvp, 64.904, 5e-4) and near(2*dvp, 129.81, 0.005))
ok("apoapsis: 1415.28 s, 3.3 times longer, 703.17 m/s",
   near(dt_apo, 1415.28, 0.005) and near(dt_apo/dt30, 3.25, 0.01) and near(2*dva, 703.17, 0.005))

# ================================================================== B2. circular orbits
print("B2. circular 300 -> 420 km")
r1, r2 = RE + 300.0, RE + 420.0
n1, n2 = np.sqrt(mu/r1**3), np.sqrt(mu/r2**3)
at = 0.5*(r1 + r2); tH = np.pi*np.sqrt(at**3/mu)
dv1H = np.sqrt(mu*(2/r1 - 1/at)) - np.sqrt(mu/r1); dv2H = np.sqrt(mu/r2) - np.sqrt(mu*(2/r2 - 1/at))
lead = np.pi - n2*tH; rate = D(n1 - n2)*3600; Tsyn = 2*np.pi/(n1 - n2)
print(f"    n1 = {n1:.6e}, n2 = {n2:.6e}, t_H = {tH:.2f} s = {tH/60:.2f} min")
print(f"    dv1 = {1e3*dv1H:.3f}, dv2 = {1e3*dv2H:.3f}, total {1e3*(dv1H + dv2H):.3f} m/s")
print(f"    n2 t_H = {D(n2*tH):.3f} deg, theta* = {D(lead):.3f} deg, rate {rate:.3f} deg/h, T_syn = {Tsyn/3600:.2f} h = {Tsyn/86400:.2f} d")
ok("Example 2 rates, t_H, burns", near(n1, 1.156874e-3, 1e-9) and near(n2, 1.126378e-3, 1e-9) and near(tH, 2752.27, 0.005)
   and near(1e3*dv1H, 34.321, 5e-4) and near(1e3*dv2H, 34.168, 5e-4) and near(1e3*(dv1H + dv2H), 68.489, 5e-4))
ok("theta* = 2.378 deg, 6.290 deg/h, T_syn = 57.23 h = 2.38 d",
   near(D(n2*tH), 177.622, 5e-4) and near(D(lead), 2.378, 5e-4) and near(rate, 6.290, 5e-4)
   and near(Tsyn/3600, 57.23, 0.005) and near(Tsyn/86400, 2.38, 0.005))
tw = (40 - D(lead))/rate; tw0 = (360 - D(lead))/rate
print(f"    wait from 40 deg: {tw:.2f} h; from 0 deg: {tw0:.2f} h; one degree = {60/rate:.2f} min")
ok("waits 5.98 h and 56.85 h; 9.54 min per degree", near(tw, 5.98, 0.005) and near(tw0, 56.85, 0.005) and near(60/rate, 9.54, 0.005))

R1c, V1c = np.array([r1, 0.0]), np.array([0.0, np.sqrt(mu/r1)])
def circ_dv(thd, dt):
    al = np.radians(thd) + n2*dt
    R2 = r2*np.array([np.cos(al), np.sin(al)]); V2 = np.sqrt(mu/r2)*np.array([-np.sin(al), np.cos(al)])
    return solve(R1c, V1c, R2, V2, dt)
def circ_best(thd, kind, lo=30.0):
    """Least cost over 0-rev arcs (transfer angle < 360 deg) with time of flight >= lo seconds."""
    tmax = (2*np.pi - np.radians(thd))/n2*(1 - 1e-4)
    cost = lambda dt: (lambda d: d[0] + d[1] if kind == "r" else d[0])(circ_dv(thd, dt))
    dts = np.linspace(lo, tmax, 1500); vals = np.array([cost(t) for t in dts])
    if np.all(np.isnan(vals)):
        return np.nan, np.nan
    j = np.nanargmin(vals)
    res = minimize_scalar(lambda t: 1e9 if np.isnan(cost(t)) else cost(t),
                          bounds=(dts[max(j - 1, 0)], dts[min(j + 1, len(dts) - 1)]), method="bounded",
                          options=dict(xatol=1e-3))
    return 1e3*res.fun, res.x/60
table = {-20: (499.6, 187.5), -10: (348.3, 122.7), 0: (149.4, 52.4), D(lead): (68.5, 34.3),
         5: (119.6, 75.9), 10: (224.5, 149.7)}
good = True
for thd, (rq, iq) in table.items():
    (rb, rt), (ib, it) = circ_best(thd, "r"), circ_best(thd, "i")
    print(f"    theta = {thd:6.2f}: rendezvous {rb:7.2f} m/s ({rt:5.2f} min), intercept {ib:7.2f} m/s ({it:5.2f} min)")
    good &= near(rb, rq, 0.051) and near(ib, iq, 0.051)
ok("porkchop table (minimised over time of flight)", good)
b87 = circ_best(D(lead) + rate, "r")[0]
print(f"    leaving 1 h early: theta = {D(lead) + rate:.2f} deg, rendezvous {b87:.1f} m/s = {b87/1e3/(dv1H + dv2H):.2f} x Hohmann")
ok("1 h early: theta ~ 8.7 deg, about three times the Hohmann cost", near(D(lead) + rate, 8.67, 0.005) and 2.7 < b87/1e3/(dv1H + dv2H) < 3.1)
feas_any = lambda thd, lo, N: any(np.isfinite(circ_dv(thd, t)[0]) for t in
                                  np.linspace(lo, (2*np.pi - np.radians(thd))/n2*(1 - 1e-4), N))
ok("from theta = 40 deg, every 0-rev arc (1 s .. 360 deg) dips below 100 km", not feas_any(40.0, 1.0, 4000))
lo_, hi_ = 12.0, 13.0
for _ in range(30):
    m = 0.5*(lo_ + hi_)
    lo_, hi_ = (m, hi_) if feas_any(m, 1800.0, 600) else (lo_, m)
print(f"    arcs longer than 30 min exist only for theta < {lo_:.2f} deg")
s13 = circ_best(13.0, "r", lo=10.0)
print(f"    theta = 13 deg: best rendezvous {s13[0]:.0f} m/s on a {s13[1]:.2f} min arc")
ok("long-arc family ends at theta = 12.66 deg; beyond it only sub-10-min arcs costing km/s",
   near(lo_, 12.66, 0.005) and s13[1] < 10 and s13[0] > 5000)
# the widths of the two valleys (cost below twice its own minimum), in degrees of phase
def edge(kind, cap, inside, outside):
    """Bisect for the phase at which the best cost crosses cap."""
    for _ in range(14):
        m = 0.5*(inside + outside)
        inside, outside = (m, outside) if circ_best(m, kind)[0] < cap else (inside, m)
    return 0.5*(inside + outside)
L0 = D(lead)
wr = (edge("r", 2e3*(dv1H + dv2H), L0, -6.0), edge("r", 2e3*(dv1H + dv2H), L0, 10.0))
wi = (edge("i", 2e3*dv1H, L0, -6.0), edge("i", 2e3*dv1H, L0, 10.0))
print(f"    within 2x of the optimum: rendezvous {wr[0]:.2f}..{wr[1]:.2f} deg, intercept {wi[0]:.2f}..{wi[1]:.2f} deg")
WR, WI = wr[1] - wr[0], wi[1] - wi[0]
ok("intercept valley wider than rendezvous valley (2x-of-optimum width)", WI > WR)

# ================================================================== B3. elliptic orbits
print("B3. elliptic chase")
a1, e1, a2, e2 = 6800.0, 0.02, 10000.0, 0.3
m1, m2 = np.sqrt(mu/a1**3), np.sqrt(mu/a2**3); T1, T2 = 2*np.pi/m1, 2*np.pi/m2
print(f"    T1 = {T1/3600:.4f} h, T2 = {T2/3600:.4f} h")
ok("T1 = 1.5501 h, T2 = 2.7644 h", near(T1/3600, 1.5501, 5e-5) and near(T2/3600, 2.7644, 5e-5))
ok(f"synodic period of the elliptic pair {2*np.pi/(m1 - m2)/3600:.3f} h (3.53; 24 h holds {24*3600*(m1 - m2)/(2*np.pi):.1f})",
   near(2*np.pi/(m1 - m2)/3600, 3.53, 0.005))
vis = lambda r, aa: np.sqrt(mu*(2/r - 1/aa))
routes = {}
for name, ra, rb in (("i", a1*(1 - e1), a2*(1 + e2)), ("ii", a1*(1 + e1), a2*(1 - e2))):
    att = 0.5*(ra + rb); tt = np.pi*np.sqrt(att**3/mu)
    d1, d2 = abs(vis(ra, att) - vis(ra, a1))*1e3, abs(vis(rb, a2) - vis(rb, att))*1e3
    routes[name] = (tt, d1, d2)
    print(f"    route {name}: {ra:.0f} -> {rb:.0f} km, t_H = {tt/3600:.4f} h, dv1 = {d1:.2f}, dv2 = {d2:.2f}, sum {d1 + d2:.2f} m/s")
ok("route i: 1.3475 h, 1082.17 + 74.10 = 1156.27", near(routes["i"][0]/3600, 1.3475, 5e-5) and near(routes["i"][1], 1082.17, 0.005)
   and near(routes["i"][2], 74.10, 0.005) and near(sum(routes["i"][1:]), 1156.27, 0.005))
ok("route ii: 0.8040 h, 93.58 + 1075.12 = 1168.70", near(routes["ii"][0]/3600, 0.8040, 5e-5) and near(routes["ii"][1], 93.58, 0.005)
   and near(routes["ii"][2], 1075.12, 0.005) and near(sum(routes["ii"][1:]), 1168.70, 0.005))
ok("intercept ratio 11.6", near(routes["i"][1]/routes["ii"][1], 11.6, 0.05))
M20 = np.pi/2
def miss(name, kk):
    off, Mt = (0.0, np.pi) if name == "i" else (0.5, 0.0)
    t0 = (kk + off)*T1
    Mx = np.mod(M20 + m2*(t0 + routes[name][0]) - Mt + np.pi, 2*np.pi) - np.pi
    return t0, Mx/m2                   # negative: the chaser arrives before the target
calls = {nm: min((miss(nm, kk) for kk in range(16) if miss(nm, kk)[0] < 24*3600), key=lambda z: abs(z[1])) for nm in ("i", "ii")}
for nm, (t0, ms) in calls.items():
    print(f"    route {nm}: closest call departs {t0/3600:.2f} h, chaser {-ms:.0f} s early")
ok("closest calls: ii at 17.83 h (106 s early), i at 18.60 h (335 s early)",
   near(calls["ii"][0]/3600, 17.83, 0.005) and near(-calls["ii"][1], 106, 0.5) and
   near(calls["i"][0]/3600, 18.60, 0.005) and near(-calls["i"][1], 335, 0.5))
t0c, tHc = 11.5*T1, routes["ii"][0]
revs = (t0c + tHc)/T2; M2a = np.mod(90 + 360*revs, 360)
print(f"    route ii call: t0 = {t0c/3600:.3f} h, arrival {(t0c + tHc)/3600:.3f} h = {revs:.4f} T2, M2 = {90 + 360*revs:.1f} = {M2a:.1f} deg,"
      f" short by {(360 - M2a)/360*T2:.0f} s")
ok("route ii working: 17.827 h, arrival 18.631 h, 6.7395 rev, M2 356.2 deg, ~105-106 s",
   near(t0c/3600, 17.827, 5e-4) and near((t0c + tHc)/3600, 18.631, 5e-4) and near(revs, 6.7395, 5e-4)
   and near(M2a, 356.2, 0.05) and near((360 - M2a)/360*T2, 106, 1))
def st(t0, dt):
    R1, V1, _ = state_planar(a1, e1, 0.0, m1*t0); R2, V2, _ = state_planar(a2, e2, 0.0, M20 + m2*(t0 + dt))
    return R1, V1, R2, V2
def ecost(x, kind):
    d1, d2 = solve(*st(x[0]*3600, x[1]*3600), x[1]*3600)
    v = d1 + d2 if kind == "r" else d1
    return 1e9 if np.isnan(v) else 1e3*v
opt = {}
for kind, x0 in (("r", (21.75, 2.0625)), ("i", (17.60, 1.0625))):      # grid optima, then refined
    r_ = minimize(ecost, x0, args=(kind,), method="Nelder-Mead", options=dict(xatol=1e-8, fatol=1e-9, maxiter=4000))
    t0, dt = r_.x*3600; R1, V1, R2, V2 = st(t0, dt); v1, v2, p, e = lambert_vec(R1, R2, dt)
    sweep = D(np.mod(np.arctan2(R2[1], R2[0]) - np.arctan2(R1[1], R1[0]), 2*np.pi))
    opt[kind] = (r_.x, 1e3*np.linalg.norm(v1 - V1), 1e3*np.linalg.norm(V2 - v2), p, e, sweep)
    print(f"    best {'rendezvous' if kind == 'r' else 'intercept '}: t0 = {r_.x[0]:.3f} h, dt = {r_.x[1]:.3f} h, "
          f"dv1 = {opt[kind][1]:.2f}, arrival {opt[kind][2]:.2f} m/s, p = {p:.2f} km, e = {e:.4f}, sweep {sweep:.1f} deg")
(xr, d1r, d2r, pr, er, swr), (xi, d1i, d2i, *_ ) = opt["r"], opt["i"]
ok("best rendezvous 21.757 h, 2.058 h, 952.50 + 211.90 = 1164.40, p 8557.10, e 0.2835, 265.7 deg",
   near(xr[0], 21.757, 5e-4) and near(xr[1], 2.058, 5e-4) and near(d1r, 952.50, 0.005) and near(d2r, 211.90, 0.005)
   and near(d1r + d2r, 1164.40, 0.005) and near(pr, 8557.10, 0.005) and near(er, 0.2835, 5e-5) and near(swr, 265.7, 0.05))
ok("0.7% above route i", near((d1r + d2r)/sum(routes["i"][1:]) - 1, 0.007, 5e-4))
ok("best intercept 17.623 h, 1.048 h, 114.46 m/s, arrival 1.087 km/s, 21 m/s above route ii",
   near(xi[0], 17.623, 5e-4) and near(xi[1], 1.048, 5e-4) and near(d1i, 114.46, 0.005) and near(d2i/1e3, 1.087, 5e-4)
   and near(d1i - routes["ii"][1], 21, 0.5))
ok("the two optima are about four hours apart", near(xr[0] - xi[0], 4.13, 0.01))

# ================================================================== B4. terminal phase (CW)
print("B4. CW targeting from (-1, -10) km at 420 km")
X0 = np.array([-1.0, -10.0, 0.0, -1.5*n*(-1.0)])
print(f"    co-circular drift ydot0 = -(3/2) n x0 = {1e3*X0[3]:.3f} m/s; {X0[3]*Tc:.2f} km per orbit")
ok("ydot0 = 1.690 m/s, closing 9.42 km per orbit", near(1e3*X0[3], 1.690, 5e-4) and near(X0[3]*Tc, 9.42, 0.005))
def cw_target(tf):
    P = cw_stm(n, tf)
    vp = -np.linalg.solve(P[:2, 2:], P[:2, :2] @ X0[:2]); vf = P[2:, :2] @ X0[:2] + P[2:, 2:] @ vp
    return 1e3*np.linalg.norm(vp - X0[2:]), 1e3*np.linalg.norm(vf)
cwrows = {0.25: (23.2, 6.401, 7.154), 0.5: (46.5, 2.171, 2.171), 0.75: (69.7, 1.222, 0.618),
          1.25: (116.2, 1.158, 0.580), 1.5: (139.5, 0.872, 0.872)}
good = True
for fr, (mq, d1q, d2q) in cwrows.items():
    d1, d2 = cw_target(fr*Tc)
    print(f"    t_f = {fr:4.2f} T = {fr*Tc/60:6.1f} min: dv1 = {d1:.3f}, dv2 = {d2:.3f}, sum = {d1 + d2:.3f} m/s")
    good &= near(fr*Tc/60, mq, 0.05) and near(d1, d1q, 5e-4) and near(d2, d2q, 5e-4)
ok("Example 4 table", good)
res = minimize_scalar(lambda x: sum(cw_target(x*Tc)), bounds=(1.45, 1.95), method="bounded")
print(f"    cheapest rendezvous within two periods: t_f = {res.x:.3f} T, {res.fun:.3f} m/s")
ok("cheapest within 2T: 0.87 m/s near 1.63 T", near(res.fun, 0.87, 0.005) and near(res.x, 1.63, 0.005))
P = cw_stm(n, 0.5*Tc)
vp = -np.linalg.solve(P[:2, 2:], P[:2, :2] @ X0[:2])
print(f"    T/2 by hand: Phi_rr r0 = {np.round(P[:2, :2] @ X0[:2], 4).tolist()} km, v0+ = {np.round(1e3*vp, 4).tolist()} m/s, "
      f"dv1 = {np.round(1e3*(vp - X0[2:]), 4).tolist()} m/s; v0+/n = {np.round(vp/n, 5).tolist()}")
ok("T/2: Phi_rr r0 = (-7, 8.8496); v0+ = (-2.1525, 1.9712) = n (-1.91095, 7/4); dv1 = (-2.1525, 0.2816)",
   np.allclose(P[:2, :2] @ X0[:2], [-7, 6*np.pi - 10]) and near(6*np.pi - 10, 8.8496, 5e-5)
   and np.allclose(1e3*vp, [-2.1525, 1.9712], atol=5e-5) and near(vp[1]/n, 1.75, 1e-12) and near(vp[0]/n, -1.91095, 5e-6)
   and np.allclose(1e3*(vp - X0[2:]), [-2.1525, 0.2816], atol=5e-5))
# the same geometry by Lambert: chaser at (a + x0, y0) in the target's rectilinear LVLH axes at t = 0
R1l = np.array([a + X0[0], X0[1]])
V1l = np.array([0.0, vc]) + n*np.array([-X0[1], X0[0]]) + X0[2:]      # v_target + omega x rho + rho_dot
lam = {}
for fr in (0.25, 0.5, 0.75):
    tf = fr*Tc; ang = n*tf
    R2 = a*np.array([np.cos(ang), np.sin(ang)]); V2 = vc*np.array([-np.sin(ang), np.cos(ang)])
    v1, v2, *_ = lambert_vec(R1l, R2, tf)
    sweep = D(np.mod(np.arctan2(R2[1], R2[0]) - np.arctan2(R1l[1], R1l[0]), 2*np.pi))
    lam[fr] = (1e3*np.linalg.norm(v1 - V1l), 1e3*np.linalg.norm(V2 - v2), sweep)
    print(f"    Lambert t_f = {fr} T: dv1 = {lam[fr][0]:.3f}, dv2 = {lam[fr][1]:.3f} m/s, sweep {sweep:.2f} deg")
ok("Lambert (6.401, 7.156), (2.171, 2.174), (1.219, 0.618); T/2 sweeps 180.08 deg",
   all(near(lam[f][0], q1, 5e-4) and near(lam[f][1], q2, 5e-4) for f, q1, q2 in
       ((0.25, 6.401, 7.156), (0.5, 2.171, 2.174), (0.75, 1.219, 0.618))) and near(lam[0.5][2], 180.08, 0.005))
worst = max(abs(lam[f][j] - cw_target(f*Tc)[j])/cw_target(f*Tc)[j] for f in lam for j in (0, 1))
print(f"    worst CW-Lambert difference {100*worst:.2f} %")
ok("CW and Lambert agree to better than 0.3 %", worst < 3e-3)

# ================================================================== B5. outer chaser
print("B5. time reversal")
# a generic inner -> outer Lambert arc and its mirror image outer -> inner, same time of flight
dt, thd = 3600.0, 0.0
al = np.radians(thd) + n2*dt
Rf2 = r2*np.array([np.cos(al), np.sin(al)]); Vf2 = np.sqrt(mu/r2)*np.array([-np.sin(al), np.cos(al)])
fwd = solve(R1c, V1c, Rf2, Vf2, dt)
R2b, V2b = np.array([r2, 0.0]), np.array([0.0, np.sqrt(mu/r2)])
Rb1 = r1*np.array([np.cos(al), np.sin(al)]); Vb1 = np.sqrt(mu/r1)*np.array([-np.sin(al), np.cos(al)])
bwd = solve(R2b, V2b, Rb1, Vb1, dt)
print(f"    1 -> 2: dv1 = {1e3*fwd[0]:.3f}, dv2 = {1e3*fwd[1]:.3f};  2 -> 1: dv1 = {1e3*bwd[0]:.3f}, dv2 = {1e3*bwd[1]:.3f} m/s")
ok("the mirrored arc swaps the two burns", np.allclose(fwd, bwd[::-1], rtol=1e-6))
rG = 42164.137
atG = 0.5*(r1 + rG)
dG1 = (np.sqrt(mu*(2/r1 - 1/atG)) - np.sqrt(mu/r1))*1e3; dG2 = (np.sqrt(mu/rG) - np.sqrt(mu*(2/rG - 1/atG)))*1e3
print(f"    300 km -> GEO ({rG} km): {dG1:.1f} and {dG2:.1f} m/s, ratio {dG1/dG2:.2f}; 300 <-> 420: ratio {dv1H/dv2H:.4f}")
ok("LEO-GEO 2425.7 / 1466.8 m/s, ratio 1.65; 300-420 asymmetry 0.4 %",
   near(dG1, 2425.7, 0.05) and near(dG2, 1466.8, 0.05) and near(dG1/dG2, 1.65, 0.005) and near(dv1H/dv2H - 1, 0.004, 5e-4))
print(f"    outer chaser lead angle pi - n_inner t_H = {D(np.pi - n1*tH):.3f} deg")
ok("420 -> 300 km: target trails by 2.431 deg", near(D(np.pi - n1*tH), -2.431, 5e-4))

print(f"\nvalley widths (2x optimum): rendezvous {WR:.1f} deg, intercept {WI:.1f} deg")

print("\nAdded checks")
# the explicit inverse of Phi_rv
nn = 2*np.pi/5400.0
worst_inv = 0.0
for tau_ in (0.3, 1.0, np.pi, 4.0, 7.0):
    c_, s_ = np.cos(tau_), np.sin(tau_)
    Prv = np.array([[s_, 2*(1 - c_)], [-2*(1 - c_), 4*s_ - 3*tau_]])/nn
    d_ = 8*(1 - c_) - 3*tau_*s_
    Pinv = nn/d_*np.array([[4*s_ - 3*tau_, -2*(1 - c_)], [2*(1 - c_), s_]])
    worst_inv = max(worst_inv, np.abs(Pinv @ Prv - np.eye(2)).max())
ok(f"Phi_rv^-1 = (n/d) [[4s - 3tau, -2(1-c)], [2(1-c), s]] (worst error {worst_inv:.1e})", worst_inv < 1e-12)
# Exercise 3: target 30 deg ahead of a chaser at periapsis
a3, e3 = 10000.0, 0.3
n3 = np.sqrt(mu/a3**3); T3 = 2*np.pi/n3
E3 = 2*np.arctan(np.sqrt((1 - e3)/(1 + e3))*np.tan(np.radians(15))); dt3 = (E3 - e3*np.sin(E3))/n3
Tph3 = T3 - dt3; aph3 = a3*(Tph3/T3)**(2/3)
dv3 = np.sqrt(mu*(2/7000 - 1/a3)) - np.sqrt(mu*(2/7000 - 1/aph3))
ok(f"Ex 3: T_ph {Tph3:.2f} s, a_ph {aph3:.2f} km, apoapsis {2*aph3 - 7000:.0f} km, 2 x {1000*dv3:.2f} = {2000*dv3:.2f} m/s",
   near(Tph3, 9516.90, 0.005) and near(aph3, 9706.36, 0.005) and near(2*aph3 - 7000, 12413, 0.5) and near(1000*dv3, 70.36, 0.005) and near(2000*dv3, 140.73, 0.005))

# =================================================================================== the animations (codes/anim-chase.py)
print("The animations: each scenario rebuilds the note's numbers from the orbits, and the target reaches the meeting point in time")
import importlib.util
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
_spec = importlib.util.spec_from_file_location("anim_chase", os.path.join(os.path.dirname(os.path.abspath(__file__)), "anim-chase.py"))
_ac = importlib.util.module_from_spec(_spec); _spec.loader.exec_module(_ac)
for _name in _ac.SCENARIOS:
    try:                                                 # building asserts the quoted burns, times, lead angles and the meeting
        _panels, _kw = _ac.build(_name)
        _ok = True
        _desc = "; ".join(f"{P.info['total']*1000:.2f} m/s in {len(P.info['burns'])} burns" for P in _panels[:2] if P.readout)
    except AssertionError as _e:
        _ok, _desc = False, str(_e)[:160]
    ok(f"  {_name}: {_desc}", _ok)

print("Worked solutions of the exercises")
close = lambda x, y, tol: abs(x - y) <= tol
aG = 42164.0; TG = 2*np.pi*np.sqrt(aG**3/mu)
TphG = TG*(1 + 5/1080); aphG = aG*(TphG/TG)**(2/3); vG = np.sqrt(mu/aG); dvG = np.sqrt(mu*(2/aG - 1/aphG)) - vG
ok(f"Ex 1: T = {TG:.1f} s (86163.6) = {TG/3600:.3f} h (23.934)", close(TG, 86163.6, 0.05) and close(TG/3600, 23.934, 5e-4))
ok(f"Ex 1: T_ph = {TphG:.1f} (86562.5), {(TphG-TG)/60:.2f} min longer (6.65), 3 T_ph = {3*TphG/86400:.3f} d (3.006)",
   close(TphG, 86562.5, 0.05) and close((TphG - TG)/60, 6.65, 0.005) and close(3*TphG/86400, 3.006, 5e-4))
ok(f"Ex 1: a_ph = {aphG:.1f} (42294.0), apogee {2*aphG-aG:.1f} (42424.1), {2*aphG-2*aG:.0f} km above (260)",
   close(aphG, 42294.0, 0.05) and close(2*aphG - aG, 42424.1, 0.05) and close(2*aphG - 2*aG, 260, 0.5))
ok(f"Ex 1: v_c {vG:.5f} (3.07467), burn {1e3*dvG:.3f} m/s (4.723), total {2e3*dvG:.2f} (9.45), rule {1e3*vG*(TphG-TG)/TG/3:.3f} (4.745)",
   close(vG, 3.07467, 5e-6) and close(1e3*dvG, 4.723, 5e-4) and close(2e3*dvG, 9.45, 0.005) and close(1e3*vG*(TphG - TG)/TG/3, 4.745, 5e-4))
ok(f"Ex 1: over 15 days ~ {2e3*dvG*3/15:.1f} m/s (1.9)", close(2e3*dvG*3/15, 1.9, 0.05))
nn = lambda r: np.sqrt(mu/r**3)
def hoh(ra, rb):
    at = (ra + rb)/2; tH = np.pi*np.sqrt(at**3/mu)
    return tH, abs(np.sqrt(mu*(2/ra - 1/at)) - np.sqrt(mu/ra))*1e3, abs(np.sqrt(mu/rb) - np.sqrt(mu*(2/rb - 1/at)))*1e3
q1, q2, q3 = RE + 300, RE + 420, RE + 250
td, d1, d2 = hoh(q1, q3); tu, u1, u2 = hoh(q3, q2)
ok(f"Ex 2: descent {td:.1f} s (2700.4), burns {d1:.3f}, {d2:.3f} (14.529, 14.556), total {d1+d2:.3f} (29.085)",
   close(td, 2700.4, 0.05) and close(d1, 14.529, 5e-4) and close(d2, 14.556, 5e-4) and close(d1 + d2, 29.085, 5e-4))
swp = np.degrees(nn(q2)*td); th1 = 40 + swp - 180
ok(f"Ex 2: target sweeps {swp:.2f} deg (174.27), lead after descent {th1:.2f} (34.27)", close(swp, 174.27, 0.005) and close(th1, 34.27, 0.005))
ld = 180 - np.degrees(nn(q2)*tu)
ok(f"Ex 2: climb t_H = {tu:.1f} s (2737.0), lead {ld:.3f} deg (3.365)", close(tu, 2737.0, 0.05) and close(ld, 3.365, 5e-4))
rt = np.degrees(nn(q3) - nn(q2))*3600; tw = (th1 - ld)/rt
ok(f"Ex 2: rate {rt:.3f} deg/h (8.995), wait {tw:.2f} h (3.44)", close(rt, 8.995, 5e-4) and close(tw, 3.44, 0.005))
ok(f"Ex 2: climb burns {u1:.3f}, {u2:.3f} (48.940, 48.632), total {u1+u2:.3f} (97.572)",
   close(u1, 48.940, 5e-4) and close(u2, 48.632, 5e-4) and close(u1 + u2, 97.572, 5e-4))
ttot = td/3600 + tw + tu/3600
ok(f"Ex 2: times {td/3600:.2f} + {tw:.2f} + {tu/3600:.2f} = {ttot:.2f} h (0.75, 3.44, 0.76, 4.95); old 6.75; saves {6.744-ttot:.2f} (1.80)",
   close(td/3600, 0.75, 0.005) and close(tu/3600, 0.76, 0.005) and close(ttot, 4.95, 0.005) and close(5.981 + 2752.27/3600, 6.75, 0.005)
   and close(5.981 + 2752.27/3600 - ttot, 1.80, 0.005))
tc = d1 + d2 + u1 + u2
ok(f"Ex 2: total {tc:.2f} m/s (126.66), extra {tc-68.489:.1f} (58.2), per hour {(tc-68.489)/1.80:.0f} (32)",
   close(tc, 126.66, 0.005) and close(tc - 68.489, 58.2, 0.05) and close((tc - 68.489)/1.80, 32, 0.5))
ae, ee = 10000.0, 0.3; Te = 2*np.pi*np.sqrt(ae**3/mu)
Ee = 2*np.arctan(np.sqrt((1 - ee)/(1 + ee))*np.tan(np.radians(15))); dte = (Ee - ee*np.sin(Ee))/np.sqrt(mu/ae**3)
Tph3 = Te - dte; aph3 = ae*(Tph3/Te)**(2/3); rp3 = ae*(1 - ee)
v3a, v3b = np.sqrt(mu*(2/rp3 - 1/ae)), np.sqrt(mu*(2/rp3 - 1/aph3))
ok(f"Ex 3: T_ph = {Tph3:.2f} (9516.90), a_ph = {aph3:.2f} (9706.36), apoapsis {2*aph3-rp3:.0f} (12413)",
   close(Tph3, 9516.90, 0.005) and close(aph3, 9706.36, 0.005) and close(2*aph3 - rp3, 12413, 0.5))
ok(f"Ex 3: speeds {v3a:.5f} (8.60382), {v3b:.5f} (8.53346), burn {1e3*(v3a-v3b):.2f} (70.36), total {2e3*(v3a-v3b):.2f} (140.73), perigee alt {rp3-RE:.0f} (622)",
   close(v3a, 8.60382, 5e-6) and close(v3b, 8.53346, 5e-6) and close(1e3*(v3a - v3b), 70.36, 0.005) and close(2e3*(v3a - v3b), 140.73, 0.005) and close(rp3 - RE, 622, 0.5))
n4 = 2*np.pi/5400
P4 = cw_stm(n4, np.pi/n4)
r40 = np.array([0.0, -5.0])
v4p = -np.linalg.solve(P4[0:2, 2:4], P4[0:2, 0:2] @ r40)
vf4 = P4[2:4, 0:2] @ r40 + P4[2:4, 2:4] @ v4p
ok(f"Ex 4: n = {n4:.5e} (1.16355e-3)", close(n4, 1.16355e-3, 5e-9))
ok(f"Ex 4: v0+ = {1e3*v4p} m/s (-1.454, 0) = -5n/4", np.allclose(1e3*v4p, [-1.454, 0], atol=5e-4) and close(v4p[0], -1.25*n4, 1e-12))
ok(f"Ex 4: arrival {1e3*vf4} m/s (+1.454, 0), rendezvous {2e3*np.linalg.norm(v4p):.3f} (2.909)",
   np.allclose(1e3*vf4, [1.454, 0], atol=5e-4) and close(2e3*np.linalg.norm(v4p), 2.909, 5e-4))
taus = np.linspace(0, 2*np.pi, 9)
path = np.array([cw_stm(n4, t/n4)[0:2, :] @ np.concatenate([r40, v4p]) for t in taus])
ok("Ex 4: x = -5/4 sin tau, y = -5 + 5/2 (1 - cos tau), closed loop after one period",
   np.allclose(path[:, 0], -1.25*np.sin(taus), atol=1e-12) and np.allclose(path[:, 1], -5 + 2.5*(1 - np.cos(taus)), atol=1e-12) and np.allclose(path[-1], r40, atol=1e-12))
fq = sp.symbols("f", real=True); eq_ = sp.symbols("e", positive=True)
Mf = lambda F, E_: (lambda Ea: Ea - E_*np.sin(Ea))(2*np.arctan(np.sqrt((1 - E_)/(1 + E_))*np.tan(F/2)))
ok("Ex 5: r(f) even in f; M(f) odd in f", all(close(Mf(-F, 0.3), -Mf(F, 0.3), 1e-14) for F in np.linspace(-3, 3, 13)))
