r"""
Einstein, 1905: simultaneity, time dilation and length contraction
==================================================================

From two postulates -- the laws of physics are the same in every inertial
frame, and light has the same speed :math:`c` in all of them -- Einstein
derived the Lorentz transformation, in :math:`c = 1`,

.. math::

    t' = \gamma(t - \beta x), \qquad x' = \gamma(x - \beta t), \qquad
    \gamma = \frac{1}{\sqrt{1-\beta^2}},

and read three consequences off it. Events simultaneous in one frame are
not simultaneous in another: :math:`\Delta t' = -\gamma\beta\,\Delta x`.
A moving clock runs slow by :math:`\gamma`. A moving rod is shorter by
:math:`1/\gamma` along its motion. On a Minkowski diagram the first is the
tilt of the primed frame's lines of constant :math:`t'`, and the other two
follow from it.
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.relativity.chapters.special import (
    length_contraction,
    lorentz_factor,
    lorentz_transform,
    time_dilation,
)
from physicskit.relativity.visualizers.spacetime_diagrams import plot_minkowski_diagram

beta = 0.6
gamma = float(lorentz_factor(beta))

# %%
# The relativity of simultaneity
# ------------------------------
# Two lightning strikes at :math:`x = \pm 2` and :math:`t = 0` are
# simultaneous in the lab. In the frame moving at :math:`0.6c` the front
# one happens first.
A = np.array([0.0, -2.0])
B = np.array([0.0, 2.0])
A_p, B_p = lorentz_transform(np.array([A, B]), beta)
print(f"t'(A) = {A_p[0]:+.3f},  t'(B) = {B_p[0]:+.3f}")

# %%
# Time dilation and length contraction
# ------------------------------------
# A clock at rest at :math:`x' = 0` ticks at :math:`t' = 1`; in the lab that
# tick is at :math:`t = \gamma`. A rod at rest in the primed frame from
# :math:`x' = 0` to :math:`x' = 1` is measured at one lab time, and its far
# end is then at :math:`x = 1/\gamma`.
tick = lorentz_transform([1.0, 0.0], -beta)  # primed -> lab is the boost by -beta
far_end = lorentz_transform([0.0, 1.0], -beta)
far_end_at_t0 = far_end[1] - beta * far_end[0]  # slide along the end's worldline to t = 0
print(f"clock tick seen at t = {tick[0]:.3f} (gamma = {gamma:.3f})")
print(f"rod length in the lab = {far_end_at_t0:.3f} (1/gamma = {1 / gamma:.3f})")

s = np.linspace(-6.0, 6.0, 2)
rod_back = np.stack([s, beta * s], axis=-1)
rod_front = np.stack([s, beta * s + 1.0 / gamma], axis=-1)
fig, axes = plt.subplots(1, 2, figsize=(11, 5.5))
plot_minkowski_diagram(
    beta=beta,
    ax=axes[0],
    events={"A": tuple(A), "B": tuple(B)},
    lim=3.0,
)
axes[0].set_title("simultaneous in the lab, not at 0.6 c")
plot_minkowski_diagram(
    beta=beta,
    ax=axes[1],
    worldlines={"rod, back end": rod_back, "rod, front end": rod_front},
    events={"tick t'=1": (tick[0], tick[1])},
    lim=3.0,
)
axes[1].set_title("a moving clock and a moving rod")
plt.tight_layout()

# %%
# How large the effects are
# -------------------------
betas = np.linspace(0.0, 0.99, 300)
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(betas, time_dilation(1.0, betas), label=r"$\gamma$ (time dilation)")
ax.plot(betas, length_contraction(1.0, betas), label=r"$1/\gamma$ (length contraction)")
ax.set_yscale("log")
ax.set_xlabel(r"$\beta = v/c$")
ax.legend()
plt.tight_layout()
plt.show()

# %%
# Check
# -----
# At :math:`0.6c`, :math:`\gamma = 1.25`: strikes 4 apart are
# :math:`\gamma\beta \cdot 4 = 3` apart in primed time, a unit tick lasts
# 1.25 and a unit rod measures 0.8.
assert abs((A_p[0] - B_p[0]) - gamma * beta * 4.0) < 1e-12
assert abs(tick[0] - 1.25) < 1e-12 and abs(far_end_at_t0 - 0.8) < 1e-12
