r"""
Liénard and Wiechert: the fields of a fast-moving charge
========================================================

In 1898 Alfred-Marie Liénard, and independently Emil Wiechert in 1900,
found the potentials of a point charge in arbitrary motion. The charge
is seen where it was at the retarded time :math:`t_r`, when light that
reaches the observer at time :math:`t` set out. Differentiating gives the
fields

.. math::

    \mathbf E = \frac{q}{4\pi\varepsilon_0}
    \frac{\mathscr r}{(\boldsymbol{\mathscr r}\cdot\mathbf u)^3}
    \left[(c^2 - v^2)\mathbf u + \boldsymbol{\mathscr r}\times(\mathbf u\times\mathbf a)\right],
    \qquad \mathbf u = c\hat{\boldsymbol{\mathscr r}} - \mathbf v.

A charge in uniform motion carries along a Coulomb field squeezed toward
the plane through its present position, weaker by :math:`1/\gamma^2`
ahead and behind and stronger by :math:`\gamma` to the side. When the
charge accelerates, the radiation term beams forward, into lobes at
:math:`\theta_{\max} \to 1/(2\gamma)` for acceleration along the
motion. Liénard's generalization of Larmor's power grows as
:math:`\gamma^6` for linear acceleration and :math:`\gamma^4` for
circular motion, the synchrotron loss that limits electron storage rings.

:func:`~physicskit.fields.lienard_wiechert_fields` finds the retarded
time by root finding and evaluates these fields directly. Units are
natural (:math:`c = \varepsilon_0 = 1`).
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.fields import (
    larmor_power,
    lienard_power,
    lienard_wiechert_fields,
    linear_acceleration_pattern,
    peak_emission_angle,
)

# %%
# The flattened field of a charge in uniform motion
# -------------------------------------------------
# The charge moves along x at 0.9c and passes the origin at t = 0. Its
# field at t = 0 points radially away from its *present* position, but its
# strength depends on the angle to the motion (Griffiths eq. 10.75).

beta = 0.9
gamma = 1 / np.sqrt(1 - beta**2)


def uniform(tr):
    return np.array([beta * tr, 0.0, 0.0]), np.array([beta, 0.0, 0.0]), np.zeros(3)


ang = np.linspace(0, 2 * np.pi, 181)
ring = np.column_stack([np.cos(ang), np.sin(ang), np.zeros_like(ang)])
E_ring, B_ring = lienard_wiechert_fields(uniform, ring, 0.0, c=1.0, eps=1.0)
E_mag = 4 * np.pi * np.linalg.norm(E_ring, axis=1)
E_exact = (1 - beta**2) / (1 - beta**2 * np.sin(ang) ** 2) ** 1.5
print(f"along the motion |E| = {E_mag[0]:.4f} (1/gamma^2 = {1 / gamma**2:.4f}); across it {E_mag[45]:.4f} (gamma = {gamma:.4f})")

# %%
# Forward beaming of the radiation
# --------------------------------
# For acceleration along the velocity the pattern is
# sin^2 theta / (1 - beta cos theta)^5. Its lobes close in on the forward
# direction, and gamma * theta_max tends to 1/2.

th = np.linspace(-np.pi, np.pi, 2001)
gammas = np.geomspace(1.01, 1e3, 40)
betas = np.sqrt(1 - gammas**-2)
lobe = gammas * peak_emission_angle(betas)

# %%
# Synchrotron losses grow as gamma to the fourth
# ----------------------------------------------
# A charge circling at radius 1 has a = v^2 and a perpendicular to v.
# Liénard's formula gives gamma^4 times Larmor's power.

ratio = np.array([lienard_power(1.0, [0, b, 0], [-(b**2), 0, 0], c=1.0, eps=1.0) / larmor_power(1.0, b**2, c=1.0, eps=1.0) for b in betas])

fig = plt.figure(figsize=(15, 4.5))
ax0 = fig.add_subplot(1, 3, 1, projection="polar")
ax0.plot(ang, E_mag, label=r"$\beta = 0.9$")
ax0.plot(ang, np.ones_like(ang), "k--", label="Coulomb (at rest)")
ax0.set_title(r"$4\pi\varepsilon_0 r^2|E|$, motion along $\theta = 0$")
ax0.legend(loc="lower right", fontsize=8)
ax1 = fig.add_subplot(1, 3, 2, projection="polar")
for b in (0.0, 0.3, 0.6):
    p = linear_acceleration_pattern(th, b, c=1.0, eps=1.0)
    ax1.plot(th, p / p.max(), label=rf"$\beta = {b}$")
ax1.set_title("radiation pattern, a parallel to v (normalized)")
ax1.legend(loc="lower right", fontsize=8)
ax2 = fig.add_subplot(1, 3, 3)
ax2.loglog(gammas, ratio, label=r"$P_{\rm Li\'enard}/P_{\rm Larmor}$, circular")
ax2.loglog(gammas, gammas**4, "k--", label=r"$\gamma^4$")
ax2.loglog(gammas, lobe, label=r"$\gamma\,\theta_{\max}$, linear")
ax2.axhline(0.5, color="gray", ls=":")
ax2.set_xlabel(r"$\gamma$")
ax2.legend(fontsize=8)
fig.tight_layout()
plt.show()

# %%
# Check
# -----
# Uniform motion gives the flattened Coulomb field (1/gamma^2 ahead, gamma
# to the side) with B = v x E / c^2; the lobe angle tends to 1/(2 gamma);
# circular-motion power grows as gamma^4; the beamed pattern still
# integrates to Liénard's gamma^6 Larmor power.
assert np.allclose(E_mag, E_exact, rtol=1e-9, atol=0)
assert abs(E_mag[0] * gamma**2 - 1) < 1e-9 and abs(E_mag[45] / gamma - 1) < 1e-9
assert np.allclose(B_ring, np.cross([beta, 0, 0], E_ring), rtol=1e-9, atol=1e-15)
assert abs(lobe[-1] - 0.5) < 1e-3
assert np.allclose(ratio, gammas**4, rtol=1e-8)  # 1 - beta^2 loses digits at gamma = 1e3
x, w = np.polynomial.legendre.leggauss(400)
tq = 0.5 * np.pi * (x + 1)
P_num = np.sum(0.5 * np.pi * w * 2 * np.pi * np.sin(tq) * linear_acceleration_pattern(tq, 0.6, c=1.0, eps=1.0))
assert abs(P_num / lienard_power(1.0, [0.6, 0, 0], [1.0, 0, 0], c=1.0, eps=1.0) - 1) < 1e-10
