"""Run with Python 3.8 or newer: python3 orbit_reference.py

A synthetic Earth orbit in fixed, Earth-centered equatorial axes. Lengths are
in kilometers and times in seconds unless the output says otherwise.
Earth constants: https://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html
Node rate: https://science.nasa.gov/wp-content/uploads/2023/05/GDC_OrbitPrimer.pdf
"""

from math import atan2, cos, degrees, dist, hypot, pi, radians, sin, sqrt


MU = 398600.0  # km^3/s^2, rounded as in NASA's Earth Fact Sheet
EARTH_RADIUS = 6378.137  # equatorial km
J2 = 0.00108263  # dimensionless
ORBIT_RADIUS = EARTH_RADIUS + 400.0  # initial geocentric radius in km
CIRCULAR_SPEED = sqrt(MU / ORBIT_RADIUS)  # km/s
MEAN_MOTION = sqrt(MU / ORBIT_RADIUS**3)  # rad/s, two-body case
PERIOD = 2 * pi / MEAN_MOTION  # s, two-body case
SECONDS_PER_DAY = 86400


def circular_state(inclination_deg):
    """Start at the ascending node on +x. North is +z."""
    angle = radians(inclination_deg)
    return (
        ORBIT_RADIUS, 0.0, 0.0,
        0.0, CIRCULAR_SPEED * cos(angle), CIRCULAR_SPEED * sin(angle),
    )


def derivative(state, j2):
    """Return velocity in km/s and acceleration in km/s^2."""
    x, y, z, vx, vy, vz = state
    radius = hypot(x, y, z)
    central = -MU / radius**3
    bulge = 1.5 * j2 * MU * EARTH_RADIUS**2 / radius**5
    latitude_term = 5 * (z / radius)**2
    horizontal = central + bulge * (latitude_term - 1)
    vertical = central + bulge * (latitude_term - 3)
    return (vx, vy, vz, horizontal * x, horizontal * y, vertical * z)


def advance(state, rate, duration):
    return tuple(value + duration * change for value, change in zip(state, rate))


def rk4_step(state, dt, j2):
    k1 = derivative(state, j2)
    k2 = derivative(advance(state, k1, dt / 2), j2)
    k3 = derivative(advance(state, k2, dt / 2), j2)
    k4 = derivative(advance(state, k3, dt), j2)
    mean_rate = [(a + 2 * b + 2 * c + d) / 6 for a, b, c, d in zip(k1, k2, k3, k4)]
    return advance(state, mean_rate, dt)


def trajectory(initial, dt, steps, j2=0.0):
    """Yield (elapsed seconds, state) including the starting point."""
    state = initial
    yield 0.0, state
    for step in range(1, steps + 1):
        state = rk4_step(state, dt, j2)
        yield step * dt, state


def two_body_energy(state):
    speed_squared = sum(component**2 for component in state[3:])
    return speed_squared / 2 - MU / hypot(*state[:3])


def closure_check(steps):
    """After one exact two-body period, the reference position is the start."""
    initial = circular_state(45)
    dt = PERIOD / steps
    initial_energy = two_body_energy(initial)
    max_energy_change = 0.0
    for _, state in trajectory(initial, dt, steps):
        change = abs((two_body_energy(state) - initial_energy) / initial_energy)
        max_energy_change = max(max_energy_change, change)
    return dt, 1000 * dist(state[:3], initial[:3]), max_energy_change


def node_rate(inclination_deg, revolutions=10, steps_per_orbit=360):
    """Average node drift over successive south-to-north equator crossings."""
    initial = circular_state(inclination_deg)
    previous = initial
    dt = PERIOD / steps_per_orbit
    crossings = 0
    accumulated_angle = 0.0
    last_angle = 0.0  # the initial node points along +x
    for elapsed, state in trajectory(initial, dt, (revolutions + 1) * steps_per_orbit, J2):
        if previous[2] < 0 <= state[2]:
            # Interpolate to z = 0, then read the inertial angle of the node.
            fraction = -previous[2] / (state[2] - previous[2])
            x = previous[0] + fraction * (state[0] - previous[0])
            y = previous[1] + fraction * (state[1] - previous[1])
            angle = atan2(y, x)
            delta = angle - last_angle
            accumulated_angle += atan2(sin(delta), cos(delta))
            last_angle = angle
            crossings += 1
            if crossings == revolutions:
                crossing_time = elapsed - (1 - fraction) * dt
                return degrees(accumulated_angle) * SECONDS_PER_DAY / crossing_time
        previous = state
    raise ValueError('Could not find the requested ascending nodes in this orbit.')


def first_order_rate(inclination_deg):
    rate = -1.5 * J2 * MEAN_MOTION * (EARTH_RADIUS / ORBIT_RADIUS)**2
    return degrees(rate * cos(radians(inclination_deg))) * SECONDS_PER_DAY


def main():
    print(f'Initial radius {ORBIT_RADIUS:.3f} km, circular speed {CIRCULAR_SPEED:.6f} km/s')
    print(f'Two-body period {PERIOD:.3f} s ({PERIOD / 60:.4f} min)')
    print('\nTwo-body orbit at 45 deg; errors use the analytic circular solution')
    print('steps    dt (s)    final position error (m)    max fractional energy change')
    for steps in (90, 180, 360):
        dt, error_m, energy_change = closure_check(steps)
        print(f'{steps:5d}   {dt:7.3f}    {error_m:24.4f}    {energy_change:.3e}')

    print('\nJ2 gravity; node rates in deg/day, averaged over 10 node intervals')
    print('inclination    first-order rate    integrated rate')
    for inclination in (45, 90):
        predicted = first_order_rate(inclination)
        integrated = node_rate(inclination)
        print(f'{inclination:8d}       {predicted:10.5g}         {integrated:10.5g}')


if __name__ == '__main__':
    main()
