"""Can an Earth made of point masses imitate J2? (further-questions.qmd)

The Earth is replaced by a central point mass and N equal point masses on a ring of radius b in the
equatorial plane, turning with the Earth. The ring mass is chosen so that the quadrupole matches J2,
m/M = 2 J2 (R/b)^2, and the central mass is M - m, so the total mass is unchanged. A satellite starts on
a circular orbit at 700 km altitude with i = 98.19 deg, the sun-synchronous inclination of the J2 theory.
We integrate 15 orbits (about one day) and fit a straight line to the osculating node.

Panel (a): the mean nodal rate against b/R, for N = 2, 3, 4, with the rate of the same orbit around a
point mass plus J2 (integrated the same way) and the J2 secular formula.
Panel (b): the node against time for the J2 model and two rings with N = 3.

Run from courses/sfm/sfm-slides/:   python3 codes/fig-a05-ring.py
Writes img/fig-a05-ring.png and codes/ring-rates.json (read by further-questions-verify.py).
"""
import json
import os
import sys
import numpy as np
from scipy.integrate import solve_ivp

HERE = os.path.dirname(os.path.abspath(__file__))
SLIDES = os.path.normpath(os.path.join(HERE, ".."))
sys.path.insert(0, os.path.join(SLIDES, "codes"))
import matplotlib
matplotlib.rc_file(os.path.join(SLIDES, "matplotlibrc"))   # Pagella with old-style figures
import _figfont                                             # noqa: F401  all figure text at one scale
import matplotlib.pyplot as plt
from _manstyle import INK, MAROON, BLUE, GREEN, AMBER, despine

MU, R, J2, WE = 398600.4418, 6378.137, 1.08263e-3, 7.2921151e-5
H, INC = 700.0, np.radians(98.19)
A = R + H
T = 2*np.pi*np.sqrt(A**3/MU)
TF = 15*T
BMIN = np.sqrt(2*J2)                     # b/R at which the ring holds the whole mass


def initial_state():
    r = np.array([A, 0.0, 0.0])                                   # node on the x axis, Omega = 0
    v = np.sqrt(MU/A)*np.array([0.0, np.cos(INC), np.sin(INC)])
    return np.r_[r, v]


def node(y):
    h = np.cross(y[:3], y[3:])
    return np.arctan2(h[0], -h[1])


def ring_rhs(N, b):
    mfrac = 2*J2/(b/R)**2
    mc, mk = MU*(1 - mfrac), MU*mfrac/N

    def f(t, y):
        r = y[:3]
        acc = -mc*r/np.linalg.norm(r)**3
        for k in range(N):
            th = WE*t + 2*np.pi*k/N
            d = r - np.array([b*np.cos(th), b*np.sin(th), 0.0])
            acc = acc - mk*d/np.linalg.norm(d)**3
        return np.r_[y[3:], acc]
    return f


def j2_rhs(t, y):
    r = y[:3]
    x, yy, z = r
    rn = np.linalg.norm(r)
    k = 1.5*J2*MU*R**2/rn**5
    zz = 5*z*z/rn**2
    acc = -MU*r/rn**3 + k*np.array([x*(zz - 1), yy*(zz - 1), z*(zz - 3)])
    return np.r_[y[3:], acc]


def node_history(rhs):
    sol = solve_ivp(rhs, (0, TF), initial_state(), method="DOP853", rtol=1e-11, atol=1e-9,
                    dense_output=True)
    ts = np.linspace(0, TF, 3000)
    om = np.unwrap([node(sol.sol(t)) for t in ts])
    rate = np.degrees(np.polyfit(ts, om, 1)[0])*86400.0          # deg/day
    return ts, np.degrees(om), rate


n = np.sqrt(MU/A**3)
rate_formula = np.degrees(-1.5*n*J2*(R/A)**2*np.cos(INC))*86400
t_j2, om_j2, rate_j2 = node_history(j2_rhs)

BS = [BMIN, 0.07, 0.1, 0.15, 0.2, 0.3, 0.5, 0.7, 1.0]
rates = {}
for N in (2, 3, 4):
    rates[N] = [node_history(ring_rhs(N, bb*R))[2] for bb in BS]
    print("N =", N, " ".join(f"{bb:.4f}:{rr:.4f}" for bb, rr in zip(BS, rates[N])))
t1, om1, _ = node_history(ring_rhs(3, 0.1*R))
t2, om2, _ = node_history(ring_rhs(3, 1.0*R))
print(f"formula {rate_formula:.4f}  J2 integrated {rate_j2:.4f} deg/day")

with open(os.path.join(HERE, "ring-rates.json"), "w") as fh:
    json.dump(dict(b_over_R=BS, rates={str(k): v for k, v in rates.items()},
                   rate_j2=rate_j2, rate_formula=rate_formula), fh, indent=1)

fig, (ax, bx) = plt.subplots(2, 1, figsize=(8.2, 10.2))

ax.axhline(rate_j2, color=INK, lw=1.2, label=r"point mass $+\,J_2$")
ax.axvline(BMIN, color=INK, lw=0.8, ls=":")
ax.text(BMIN*1.08, 0.66, r"$b=R\sqrt{2J_2}$" + "\nwhole mass\nin the ring", fontsize=13, va="bottom")
for N, col, mk in ((2, AMBER, "s"), (3, MAROON, "o"), (4, BLUE, "^")):
    ax.plot(BS, rates[N], color=col, marker=mk, lw=1.4, ms=6, label=f"ring of {N} masses")
ax.set_xscale("log")
ax.set_xticks([0.05, 0.1, 0.2, 0.5, 1.0])
ax.set_xticklabels(["0.05", "0.1", "0.2", "0.5", "1"])
ax.set_xlabel(r"ring radius $b/R_\oplus$")
ax.set_ylabel(r"mean $\dot\Omega$ (deg/day, eastward)")
ax.set_ylim(0.2, 1.1)
ax.legend(loc="lower left", frameon=False)
ax.set_title("(a) nodal rate of a 700 km orbit, $i=98.19^\\circ$", loc="left")
despine(ax)

bx.plot(t_j2/3600, om_j2, color=INK, lw=1.4, label=r"point mass $+\,J_2$")
bx.plot(t1/3600, om1, color=MAROON, lw=1.4, ls="--", label=r"3 masses, $b=0.1R_\oplus$")
bx.plot(t2/3600, om2, color=GREEN, lw=1.4, label=r"3 masses, $b=R_\oplus$")
bx.set_xlabel("time (h)")
bx.set_ylabel(r"node $\Omega$ (deg)")
bx.legend(loc="upper left", frameon=False)
bx.set_title("(b) the node over one day", loc="left")
despine(bx)

fig.tight_layout()
fig.savefig(os.path.join(SLIDES, "img", "fig-a05-ring.png"), dpi=200)
print("wrote img/fig-a05-ring.png")
