r"""
Larmor's formula: the power radiated by an accelerated charge
=============================================================

In 1897 Joseph Larmor worked out how fast a slowly moving electron loses
energy when it accelerates. Its radiation field falls off as :math:`1/r`,
is proportional to the acceleration, and carries the power

.. math::

    P = \frac{q^2a^2}{6\pi\varepsilon_0c^3},

spread over angle as the doughnut

.. math::

    \frac{dP}{d\Omega} = \frac{q^2a^2}{16\pi^2\varepsilon_0c^3}\sin^2\theta,

which is zero along the acceleration and largest across it. The same
formula, applied to an electron orbiting a nucleus, made Rutherford's atom
collapse in a fraction of a nanosecond, one of the puzzles that led to the
Bohr model.

This example gets both results in two independent ways. First it
integrates :func:`~physicskit.fields.linear_acceleration_pattern` at
:math:`\beta = 0` over the sphere. Then it computes the full
:func:`~physicskit.fields.lienard_wiechert_fields` of a charge momentarily
at rest, on a sphere far away, and integrates the Poynting flux
:math:`\mathbf E\times\mathbf B/\mu_0` through it. Units are natural
(:math:`c = \varepsilon_0 = 1`).
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.fields import larmor_power, lienard_wiechert_fields, linear_acceleration_pattern

q, a = 1.0, 1e-3

# %%
# A charge momentarily at rest
# ----------------------------
# Hyperbolic motion is the relativistic constant-acceleration trajectory.
# At t_r = 0 the charge is at rest at the origin with acceleration a along
# z. Light emitted then reaches the sphere of radius Rs at t = Rs.


def trajectory(tr):
    s = np.sqrt(1 + (a * tr) ** 2)
    return np.array([0, 0, (s - 1) / a]), np.array([0, 0, a * tr / s]), np.array([0, 0, a / s**3])


Rs = 1e4
x, w = np.polynomial.legendre.leggauss(64)
theta, w = 0.5 * np.pi * (x + 1), 0.5 * np.pi * w
pts = Rs * np.column_stack([np.sin(theta), np.zeros_like(theta), np.cos(theta)])
E, B = lienard_wiechert_fields(trajectory, pts, Rs, q=q, c=1.0, eps=1.0)
S_r = np.sum(np.cross(E, B) * pts / Rs, axis=1)  # mu0 = 1 / (eps0 c^2) = 1
dP_flux = Rs**2 * S_r
P_flux = np.sum(w * 2 * np.pi * np.sin(theta) * dP_flux)

dP_larmor = linear_acceleration_pattern(theta, 0.0, q=q, a=a, c=1.0, eps=1.0)
P_pattern = np.sum(w * 2 * np.pi * np.sin(theta) * dP_larmor)
P_larmor = larmor_power(q, a, c=1.0, eps=1.0)
print(f"Larmor power        {P_larmor:.6e}")
print(f"pattern integrated  {P_pattern:.6e}")
print(f"Poynting flux       {P_flux:.6e}")

# %%
# The sin-squared doughnut
# ------------------------

th = np.linspace(0, 2 * np.pi, 361)
fig = plt.figure(figsize=(11, 4.5))
ax0 = fig.add_subplot(1, 2, 1, projection="polar")
ax0.plot(th, np.abs(linear_acceleration_pattern(th, 0.0, q=q, a=a, c=1.0, eps=1.0)) / P_larmor, "k-")
ax0.set_theta_zero_location("N")
ax0.set_title(r"$dP/d\Omega$, acceleration up")
ax1 = fig.add_subplot(1, 2, 2)
ax1.plot(np.degrees(theta), dP_larmor / P_larmor, "k-", label=r"$\sin^2\theta$ pattern")
ax1.plot(np.degrees(theta), dP_flux / P_larmor, "o", ms=4, label=r"$R^2 S_r$ from Liénard-Wiechert")
ax1.set_xlabel(r"$\theta$ (degrees from the acceleration)")
ax1.set_ylabel(r"$(dP/d\Omega)\,/\,P$")
ax1.legend()
fig.tight_layout()
plt.show()

# %%
# Check
# -----
# The sin^2 pattern integrates to Larmor's q^2 a^2 / (6 pi eps0 c^3), and
# so does the Poynting flux of the Lienard-Wiechert field through a far
# sphere, angle by angle.
assert abs(P_pattern / P_larmor - 1) < 1e-12
assert abs(P_flux / P_larmor - 1) < 1e-3
assert np.max(np.abs(dP_flux - dP_larmor)) < 2e-3 * np.max(dP_larmor)
