r"""
Einstein, 1905: velocity addition, the Doppler shift and aberration
===================================================================

Sections 5 and 7 of the 1905 paper apply the Lorentz transformation to
velocities and to light. Velocities do not add; they compose as

.. math::

    w = \frac{u + v}{1 + uv},

which never exceeds 1 and leaves the speed of light unchanged. The
frequency of light from a source moving at :math:`\beta` at angle
:math:`\theta` to the line of sight is multiplied by
:math:`1/[\gamma(1 - \beta\cos\theta)]`, which is
:math:`\sqrt{(1+\beta)/(1-\beta)}` head on and the pure time-dilation
factor :math:`1/\gamma` at right angles. An observer moving at
:math:`\beta` sees a source at angle :math:`\theta` shifted forward, to
:math:`\cos\theta' = (\cos\theta + \beta)/(1 + \beta\cos\theta)`.
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.relativity.chapters.special import (
    aberration_angle,
    lorentz_transform,
    relativistic_doppler,
    velocity_addition,
)

# %%
# Two boosts make one boost
# -------------------------
b1, b2 = 0.5, 0.7
event = np.array([2.0, 0.3])
twice = lorentz_transform(lorentz_transform(event, b1), b2)
once = lorentz_transform(event, velocity_addition(b1, b2))
print(f"0.5 c then 0.7 c = {float(velocity_addition(b1, b2)):.4f} c")
print(f"event after two boosts: {twice}, after one: {once}")

u = np.linspace(-1.0, 1.0, 300)
fig, ax = plt.subplots(figsize=(6, 4.5))
for v in (0.0, 0.5, 0.9, 0.99):
    ax.plot(u, velocity_addition(u, v), label=f"v = {v}")
ax.plot(u, np.clip(u + 0.9, -2, 2), "k:", linewidth=0.8, label="Galileo, v = 0.9")
ax.set_ylim(-1.1, 1.1)
ax.set_xlabel("u (velocity in the moving frame)")
ax.set_ylabel("w (velocity in the lab)")
ax.set_title("Relativistic velocity addition")
ax.legend(fontsize=8)
plt.tight_layout()

# %%
# The Doppler factor around a moving source
# -----------------------------------------
theta = np.linspace(0.0, np.pi, 300)
fig, ax = plt.subplots(figsize=(6, 4.5))
for beta in (0.2, 0.5, 0.8):
    ax.plot(np.degrees(theta), relativistic_doppler(beta, theta), label=f"beta = {beta}")
ax.axhline(1.0, color="gray", linewidth=0.5)
ax.set_yscale("log")
ax.set_xlabel("angle between source velocity and line of sight [degrees]")
ax.set_ylabel(r"$f_{obs}/f_{src}$")
ax.set_title("Relativistic Doppler shift")
ax.legend()
plt.tight_layout()

# %%
# Aberration: the sky crowds forward
# ----------------------------------
# A uniform ring of stars, as seen by observers at rest, at :math:`0.5c` and
# at :math:`0.9c` along :math:`+x`.
stars = np.linspace(0.0, 2.0 * np.pi, 36, endpoint=False)
fig, axes = plt.subplots(1, 3, figsize=(11, 4), subplot_kw={"projection": "polar"})
for ax, beta in zip(axes, (0.0, 0.5, 0.9)):
    seen = aberration_angle(stars, beta) if beta > 0 else stars
    ax.scatter(seen, np.ones_like(seen), s=12)
    ax.set_yticks([])
    ax.set_title(f"beta = {beta}")
plt.tight_layout()
plt.show()

# %%
# Check
# -----
# Two boosts compose to :math:`(b_1 + b_2)/(1 + b_1 b_2)`, light stays at
# :math:`c`, the head-on Doppler factor at :math:`0.8c` is 3, and a star
# at 90 degrees appears at 60 degrees to an observer at :math:`0.5c`.
assert np.allclose(twice, once, atol=1e-12)
assert abs(velocity_addition(b1, b2) - (b1 + b2) / (1 + b1 * b2)) < 1e-15
assert abs(velocity_addition(1.0, 0.9) - 1.0) < 1e-15
assert abs(relativistic_doppler(0.8) - 3.0) < 1e-12
assert abs(np.degrees(aberration_angle(np.pi / 2, 0.5)) - 60.0) < 1e-10
