r"""
Minkowski, 1908: the invariant interval and the twin paradox
============================================================

"Henceforth space by itself, and time by itself, are doomed to fade away
into mere shadows," Minkowski told the Cologne meeting of German
scientists in September 1908, "and only a kind of union of the two will
preserve an independent reality." Observers disagree about times and
distances, but all of them agree on the interval

.. math::

    s^2 = -\Delta t^2 + \Delta x^2 + \Delta y^2 + \Delta z^2,

and the time a clock records along its worldline is
:math:`\tau = \int \sqrt{dt^2 - dx^2}`. On a Minkowski diagram the twin
paradox is then plain geometry: the straight worldline between two events
is the longest in proper time, so the twin who stays home ages more than
the one who travels out at :math:`0.8c` and back (Langevin 1911). The
travelling twin is not equivalent to the one at home, because the traveller
changes frame at the turnaround, where the traveller's lines of simultaneity swing across the
diagram.
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.relativity.chapters.special import (
    lorentz_factor,
    lorentz_transform,
    proper_time,
    rindler_worldline,
    spacetime_interval,
)
from physicskit.relativity.visualizers.spacetime_diagrams import plot_minkowski_diagram

# %%
# Every frame measures the same interval
# --------------------------------------
rng = np.random.default_rng(1908)
events = rng.uniform(-10.0, 10.0, size=(200, 4))
s2 = spacetime_interval(events)
betas = np.linspace(-0.99, 0.99, 41)
worst = max(np.max(np.abs(spacetime_interval(lorentz_transform(events, b)) - s2)) for b in betas)
relative_error = worst / np.max(np.abs(s2))
print(f"largest change in s^2 over 41 boosts: {relative_error:.1e} (relative)")

# %%
# The twin paradox at 0.8 c
# -------------------------
# One twin stays at :math:`x = 0` for 10 years; the other flies to a star
# 4 light-years away at :math:`0.8c` and comes straight back.
home = np.array([[0.0, 0.0], [10.0, 0.0]])
trip = np.array([[0.0, 0.0], [5.0, 4.0], [10.0, 0.0]])
tau_home = proper_time(home)
tau_trip = proper_time(trip)
print(f"stay-at-home twin ages {tau_home:.2f} years, traveller {tau_trip:.2f} years")

# Lines of simultaneity of the traveller just before and just after the turn:
# the lines of constant t' through the turnaround in the outbound (+0.8) and
# return (-0.8) frames.
s = np.linspace(-20.0, 20.0, 2)
turn_out, turn_back = lorentz_transform(trip[1], 0.8), lorentz_transform(trip[1], -0.8)
out_line = lorentz_transform(np.stack([np.full_like(s, turn_out[0]), s], axis=-1), -0.8)
back_line = lorentz_transform(np.stack([np.full_like(s, turn_back[0]), s], axis=-1), 0.8)

fig, ax = plt.subplots(figsize=(6.5, 6.5))
plot_minkowski_diagram(
    ax=ax,
    worldlines={"stay at home (10 yr)": home, "traveller (6 yr)": trip},
    events={"turnaround": (5.0, 4.0)},
    lim=10.5,
)
ax.plot(out_line[:, 1], out_line[:, 0], "g--", linewidth=1, label="traveller's 'now', outbound")
ax.plot(back_line[:, 1], back_line[:, 0], "m--", linewidth=1, label="traveller's 'now', inbound")
ax.set_xlim(-2.0, 10.5)
ax.set_ylim(-0.5, 10.5)
ax.legend(loc="upper right", fontsize=8)
ax.set_title("The twin paradox on a Minkowski diagram")
# A line of constant t' meets the home worldline x = 0 at t = t'/gamma: the
# home clock reading the traveller assigns to the turnaround, just before and
# just after it.
gamma = float(lorentz_factor(0.8))
home_now_out, home_now_back = turn_out[0] / gamma, turn_back[0] / gamma
print(f"home clock at the turn, by the traveller's reckoning: {home_now_out:.2f} yr outbound, {home_now_back:.2f} yr inbound")

# %%
# A smooth trip: hyperbolic motion
# --------------------------------
# A rocket at constant proper acceleration :math:`a` follows
# :math:`x^2 - t^2 = 1/a^2`. Four such arcs -- speed up, slow down, speed
# up home, slow down -- make a trip with no instant turnaround. With
# :math:`a = 1` light-year per year squared (about 0.97 g) and 1.5 years of
# ship time per arc, the ship clock reads 6 years on return and the home
# clock :math:`4\sinh(1.5) \approx 8.5` years.
a, tau1 = 1.0, 1.5
quarter = rindler_worldline(a, np.linspace(0.0, tau1, 4001)) - np.array([0.0, 1.0 / a])
t1, x1 = quarter[-1]
half = np.vstack([quarter, (2.0 * quarter[-1] - quarter)[::-1][1:]])
T = half[-1, 0]
smooth = np.vstack([half, (np.array([2.0 * T, 0.0]) + np.array([-1.0, 1.0]) * half)[::-1][1:]])
tau_smooth = proper_time(smooth)
t_home_smooth = smooth[-1, 0]
print(f"smooth trip: ship {tau_smooth:.4f} yr, home {t_home_smooth:.4f} yr")

fig, ax = plt.subplots(figsize=(6, 6))
plot_minkowski_diagram(
    ax=ax,
    worldlines={"accelerating twin": smooth, "home": np.array([[0.0, 0.0], [t_home_smooth, 0.0]])},
    lim=9.0,
)
tau_marks = proper_time(smooth, cumulative=True)
for k in range(1, 6):
    i = np.searchsorted(tau_marks, k)
    ax.plot(smooth[i, 1], smooth[i, 0], "k.", markersize=6)
ax.set_xlim(-1.0, 8.0)
ax.set_ylim(-0.5, 9.0)
ax.set_title("Twin paradox with constant proper acceleration (dots: ship years)")
plt.tight_layout()
plt.show()

# %%
# Check
# -----
# The interval is invariant to 1e-12, the twin who travels at :math:`0.8c`
# ages 6 years in 10, the traveller's 'now' at home jumps from 1.8 to 8.2
# years at the turnaround, and the smooth trip's ship clock reads the sum of
# its four arcs' proper times, :math:`4\tau_1`, while the home clock reads
# :math:`4\sinh(a\tau_1)/a`.
assert relative_error < 1e-12
assert abs(tau_trip - 6.0) < 1e-12 and abs(tau_home - 10.0) < 1e-12
assert abs(tau_smooth - 4 * tau1) < 1e-6
assert abs(t_home_smooth - 4 * np.sinh(a * tau1) / a) < 1e-12
assert abs(home_now_out - 1.8) < 1e-12 and abs(home_now_back - 8.2) < 1e-12
