# Moral's Mark - TOE 5.20 "The Moon From the Dents Alone".
# The Sun, the Earth and the Moon as three dents that add. Nothing else.
# Tunes the month to 27.3217 days and the average stretch so the main ellipse term is 6.289 deg,
# starts the tilt at 5.31 deg (average 5.145 deg), runs six years, and prints the perigee and node
# periods and the classical lunar terms against their observed values.  Needs numpy and scipy.
import numpy as np
from scipy.integrate import solve_ivp
G=6.67430e-11; Ms=1.98847e30; Me=5.9722e24; Mm=7.342e22
AU=1.495978707e11; DAY=86400.0
mu_em=G*(Me+Mm)

def rhs(t,y,sun=True):
    rE=y[0:3]; rM=y[3:6]; vE=y[6:9]; vM=y[9:12]
    d=rM-rE; r3=np.linalg.norm(d)**3
    aE=G*Mm*d/r3; aM=-G*Me*d/r3
    if sun:
        aE+= -G*Ms*rE/np.linalg.norm(rE)**3
        aM+= -G*Ms*rM/np.linalg.norm(rM)**3
    return np.concatenate([vE,vM,aE,aM])

def init(e,inc_deg,a=3.844e8):
    # Earth-Moon barycentre on a circular orbit about the Sun
    vB=np.sqrt(G*(Ms+Me+Mm)/AU)
    rB=np.array([AU,0,0]); vBv=np.array([0,vB,0])
    rp=a*(1-e); vp=np.sqrt(mu_em*(1+e)/rp)
    inc=np.radians(inc_deg)
    rrel=np.array([rp,0,0])
    vrel=vp*np.array([0,np.cos(inc),np.sin(inc)])
    fE=Mm/(Me+Mm); fM=Me/(Me+Mm)
    return np.concatenate([rB-fE*rrel, rB+fM*rrel, vBv-fE*vrel, vBv+fM*vrel])

def run(e,inc,years,sun=True,step=0.05):
    T=years*365.25*DAY
    te=np.arange(0,T,step*DAY)
    s=solve_ivp(rhs,(0,T),init(e,inc),t_eval=te,args=(sun,),method='DOP853',rtol=1e-12,atol=1e-3)
    return s.t/DAY, s.y

def elements(y):
    rE=y[0:3].T; rM=y[3:6].T; vE=y[6:9].T; vM=y[9:12].T
    r=rM-rE; v=vM-vE
    h=np.cross(r,v)
    rn=np.linalg.norm(r,axis=1)[:,None]
    evec=np.cross(v,h)/mu_em - r/rn
    e=np.linalg.norm(evec,axis=1)
    peri=np.degrees(np.arctan2(evec[:,1],evec[:,0]))
    node=np.degrees(np.arctan2(h[:,0],-h[:,1]))
    lam=np.degrees(np.arctan2(r[:,1],r[:,0]))
    lam_sun=np.degrees(np.arctan2(-rE[:,1],-rE[:,0]))
    return e,peri,node,lam,lam_sun,np.linalg.norm(r,axis=1)


import numpy as np
eE=0.0167086
def init_real(a,e,inc):
    rB=AU*(1-eE); vB=np.sqrt(G*(Ms+Me+Mm)*(1+eE)/rB)
    rp=a*(1-e); vp=np.sqrt(mu_em*(1+e)/rp); i=np.radians(inc)
    rrel=np.array([rp,0,0]); vrel=vp*np.array([0,np.cos(i),np.sin(i)])
    fE=Mm/(Me+Mm); fM=Me/(Me+Mm); B=np.array([rB,0,0]); VB=np.array([0,vB,0])
    return np.concatenate([B-fE*rrel,B+fM*rrel,VB-fE*vrel,VB+fM*vrel])
def go(a,e0,years,step=0.05):
    T=years*365.25*DAY; te=np.arange(0,T,step*DAY)
    s=solve_ivp(rhs,(0,T),init_real(a,e0,5.31),t_eval=te,method='DOP853',rtol=1e-12,atol=1e-3)
    return s.t/DAY,s.y
def analyse(t,y,show=False):
    rE=y[0:3].T; rM=y[3:6].T; vE=y[6:9].T; vM=y[9:12].T
    r=rM-rE; v=vM-vE; h=np.cross(r,v); rn=np.linalg.norm(r,axis=1)
    evec=np.cross(v,h)/mu_em-r/rn[:,None]; e=np.linalg.norm(evec,axis=1)
    lam=np.unwrap(np.arctan2(r[:,1],r[:,0])); lams=np.unwrap(np.arctan2(-rE[:,1],-rE[:,0]))
    peri=np.unwrap(np.arctan2(evec[:,1],evec[:,0])); node=np.unwrap(np.arctan2(h[:,0],-h[:,1]))
    pl=np.polyfit(t,lam,1); Lm=np.polyval(pl,t); Ls=np.polyval(np.polyfit(t,lams,1),t)
    pp=np.polyfit(t,peri,1); Wp=np.polyval(pp,t); pn=np.polyfit(t,node,1); Wn=np.polyval(pn,t)
    M=Lm-Wp; D=Lm-Ls; F=Lm-Wn; Mp=Ls-np.pi
    S=[np.sin(M),np.sin(2*D-M),np.sin(2*D),np.sin(2*M),np.sin(Mp),np.sin(2*F)]
    C=[np.cos(M),np.cos(2*D-M),np.cos(2*D),np.cos(2*M),np.cos(Mp),np.cos(2*F)]
    A=np.vstack(S+C+[np.ones_like(t)]).T
    c=np.linalg.lstsq(A,lam-Lm,rcond=None)[0]
    return dict(month=2*np.pi/pl[0],peri=360/(np.degrees(pp[0])*365.25),node=360/abs(np.degrees(pn[0])*365.25),
                terms=np.degrees(c[:6]),left=np.degrees(np.std(lam-Lm-A@c)),emin=e.min(),emax=e.max(),e=e,t=t,D=D,Ls=Ls,Wp=Wp)
a=386594108.97; e0=0.0549
for it in range(4):
    for j in range(2):
        t,y=go(a,e0,1.0,0.1); R=analyse(t,y); a*=(27.321661/R['month'])**(2/3)
    t,y=go(a,e0,2.0,0.1); R=analyse(t,y)
    print(f"e0={e0:.5f} month {R['month']:.4f} d  centre {R['terms'][0]:.3f}")
    e0+= (6.289-R['terms'][0])/(2*57.29578)*0.9
t,y=go(a,e0,6.0,0.05); R=analyse(t,y)
names=['Equation of the centre  sin M','Evection  sin(2D-M)','Variation  sin 2D','Second centre  sin 2M',"Annual equation  sin M'",'Reduction to ecliptic  sin 2F']
obs=[6.289,1.274,0.658,0.214,-0.186,-0.114]
print(f"\nFINAL  a={a/1e3:,.1f} km  e0={e0:.5f}  sidereal month {R['month']:.4f} d (27.3217)")
print(f"PERIGEE full circle {R['peri']:.2f} yr (observed 8.85)   NODES {R['node']:.2f} yr (observed 18.61)")
for n,v,o in zip(names,R['terms'],obs): print(f"  {n:32s} dents {v:+.3f}   observed {o:+.3f}   ratio {v/o:.3f}")
print(f"  left over {R['left']:.3f} deg ;  eccentricity swings {R['emin']:.4f} to {R['emax']:.4f}")
