"""Lecture 2, the two apparent accelerations along the rider's curved path (eq-newton-rot with F = 0, steady spin): the
ball of anim-02-merry-go-round rolls straight out at 1 m/s on a platform turning anticlockwise once every 4 s, so in
the platform's components r_B(t) = V t (cos wt, -sin wt). At five points: the Coriolis term -2 w x v_B (blue, at
right angles to the path), the centrifugal term -w x (w x r) (amber, straight out from the axis) and their sum,
which equals the path's own acceleration a_B (black, from differentiating r_B). Writes img/fig-02-apparent-accel.png."""
import numpy as np
from matplotlib.patches import Circle
from _visual import plt, save, INK, MAROON, BLUE, AMBER, GREY

OMEGA, V, RAD = 2 * np.pi / 4.0, 1.0, 2.5
W = np.array([0.0, 0.0, OMEGA])
T_ALL = np.linspace(0, RAD / V, 400)
TIMES = np.array([0.6, 1.2, 1.8, 2.4])


def state(t):
    """(r_B, v_B, a_B) of the ball in the platform's components, by differentiating r_B = V t (cos wt, -sin wt)."""
    c, s = np.cos(OMEGA * t), np.sin(OMEGA * t)
    r = V * t * np.array([c, -s, 0.0])
    v = V * np.array([c, -s, 0.0]) + V * t * OMEGA * np.array([-s, -c, 0.0])
    a = 2 * V * OMEGA * np.array([-s, -c, 0.0]) - V * t * OMEGA**2 * np.array([c, -s, 0.0])
    return r, v, a


def apparent(t):
    r, v, a = state(t)
    return -2 * np.cross(W, v), -np.cross(W, np.cross(W, r)), a


MISMATCH = max(np.linalg.norm(sum(apparent(t)[:2]) - apparent(t)[2]) for t in T_ALL)   # zero: the two terms make a_B

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10.5, 4.9))
    ax.add_patch(Circle((0, 0), RAD, facecolor="#efe9dd", edgecolor=GREY, lw=1))
    path = np.array([state(t)[0] for t in T_ALL])
    ax.plot(path[:, 0], path[:, 1], color=MAROON, lw=2.4)
    sc = 0.12
    kw = dict(arrowstyle="-|>", lw=2.2, mutation_scale=15)
    for t in TIMES:
        r = state(t)[0][:2]
        cor, cen, a = (x[:2] for x in apparent(t))
        ax.plot(*r, "o", color=MAROON, ms=8, zorder=5)
        ax.annotate("", xy=r + sc * cor, xytext=r, arrowprops=dict(color=BLUE, **kw))
        ax.annotate("", xy=r + sc * cor + sc * cen, xytext=r + sc * cor, arrowprops=dict(color=AMBER, **kw))
        ax.annotate("", xy=r + sc * a, xytext=r, arrowprops=dict(color=INK, lw=1.6, arrowstyle="-|>", mutation_scale=13, ls="--"))
    ax.plot(0, 0, "+", color=INK, ms=12)
    ax.text(3.0, 1.0, "Coriolis, $-2\\boldsymbol{\\omega}\\times\\mathbf{v}_B$:\nacross the path", fontsize=12, color=BLUE)
    ax.text(3.0, -0.1, "centrifugal, $-\\boldsymbol{\\omega}\\times(\\boldsymbol{\\omega}\\times\\mathbf{r})$:\nout from the axis", fontsize=12, color=AMBER)
    ax.text(3.0, -1.2, "their sum (dashed):\nthe path's own acceleration $\\mathbf{a}_B$", fontsize=12, color=INK)
    ax.text(0, -2.85, "seen by a rider on the platform", ha="center", fontsize=12)
    ax.set_xlim(-2.8, 7.4); ax.set_ylim(-2.95, 2.6); ax.set_aspect("equal"); ax.axis("off")
    save(fig, "fig-02-apparent-accel")
