r"""
The Jones calculus: wave plates and polarizers as 2x2 matrices
==============================================================

In 1941 R. Clark Jones, at Polaroid, wrote a fully polarized beam as a
two-component complex vector :math:`(E_x, E_y)` and every polarizer,
retarder and rotator as a :math:`2\times2` complex matrix, so that a train
of elements is a single matrix product read right to left. A linear
retarder of retardance :math:`\Gamma` with fast axis at :math:`\theta` is

.. math::

    W(\Gamma, \theta) = R(\theta)\begin{pmatrix}1 & 0 \\ 0 & e^{i\Gamma}\end{pmatrix}R(-\theta).

Two facts follow at once: a half-wave plate (:math:`\Gamma = \pi`) at
:math:`\theta` reflects linear polarization about its fast axis, turning
light at angle 0 to :math:`2\theta`, and a quarter-wave plate at 45
degrees makes linear light circular. The example draws the polarization
ellipse after a quarter-wave plate at several angles, checks the
half-wave rotation, and multiplies the matrices of a half-wave plate
between crossed polarizers.
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.optics import jones_vector, linear_polarizer, rotator, stokes_parameters, wave_plate

fig, axes = plt.subplots(1, 3, figsize=(15, 4.4))
E_h = jones_vector(0.0)
phase = np.linspace(0, 2 * np.pi, 200)

# %%
# Polarization ellipses after a quarter-wave plate
# ------------------------------------------------
# The real field Re[E e^{-i omega t}] traces an ellipse. Horizontal light
# through a quarter-wave plate at theta becomes an ellipse with axes along
# the plate and axis ratio tan(theta); at 45 degrees it is a circle.
plate_angles = [0, 15, 30, 45, 60]
colors = plt.cm.viridis(np.linspace(0, 0.9, len(plate_angles)))
for k, (deg, col) in enumerate(zip(plate_angles, colors)):
    E = wave_plate(np.pi / 2, np.radians(deg)) @ E_h
    field = np.real(np.outer(E, np.exp(-1j * phase)))
    axes[0].plot(field[0] + 2.4 * k, field[1], color=col, lw=2)
    axes[0].text(2.4 * k, -1.35, f"{deg} deg", ha="center", fontsize=8)
axes[0].set_aspect("equal")
axes[0].set_ylim(-1.6, 1.2)
axes[0].axis("off")
axes[0].set_title("Horizontal light after a quarter-wave plate at theta")

# %%
# A half-wave plate rotates linear polarization by twice its angle
# ----------------------------------------------------------------
theta = np.radians(np.linspace(0, 90, 91))
out_angle = []
for t in theta:
    S = stokes_parameters(wave_plate(np.pi, t) @ E_h)
    out_angle.append(0.5 * np.arctan2(S[2], S[1]) % np.pi)
out_angle = np.unwrap(np.array(out_angle), period=np.pi)
axes[1].plot(np.degrees(theta), np.degrees(out_angle), color="crimson", lw=2, label="Jones calculus")
axes[1].plot(np.degrees(theta[::10]), 2 * np.degrees(theta[::10]), "ko", ms=4, label=r"$2\theta$")
axes[1].set_xlabel(r"half-wave plate fast axis $\theta$ (deg)")
axes[1].set_ylabel("output polarization angle (deg)")
axes[1].set_title("Half-wave plate as a polarization rotator")
axes[1].legend(fontsize=8)

# %%
# A wave plate between crossed polarizers
# ---------------------------------------
# One matrix product, P(90) W(Gamma, theta) P(0), gives the transmitted
# intensity sin^2(2 theta) sin^2(Gamma / 2): the basis of the
# polariscope and of every liquid-crystal display pixel.
for gamma, col in [(np.pi, "steelblue"), (np.pi / 2, "seagreen"), (np.pi / 4, "orange")]:
    I = []
    for t in theta * 2:
        system = linear_polarizer(np.pi / 2) @ wave_plate(gamma, t) @ linear_polarizer(0.0)
        E = system @ E_h
        I.append(np.vdot(E, E).real)
    axes[2].plot(np.degrees(theta * 2), I, color=col, lw=2, label=rf"$\Gamma = {gamma / np.pi:g}\pi$")
axes[2].set_xlabel(r"plate fast axis $\theta$ (deg)")
axes[2].set_ylabel(r"$I/I_0$")
axes[2].set_title("Retarder between crossed polarizers")
axes[2].legend(fontsize=8)
plt.tight_layout()
plt.show()

# %%
# Check
# -----
S_qwp = stokes_parameters(wave_plate(np.pi / 2, np.pi / 4) @ E_h)
assert abs(abs(S_qwp[3]) - 1) < 1e-12
assert np.allclose(out_angle, 2 * theta, atol=1e-12)
qwp = wave_plate(np.pi / 2, 0.3)
assert np.allclose(qwp @ qwp, wave_plate(np.pi, 0.3), atol=1e-12)
# two half-wave plates at a and b make a rotator by 2(b - a)
assert np.allclose(wave_plate(np.pi, 0.5) @ wave_plate(np.pi, 0.2), rotator(2 * (0.5 - 0.2)), atol=1e-12)
gamma, t = np.pi / 3, 0.4
E = linear_polarizer(np.pi / 2) @ wave_plate(gamma, t) @ E_h
assert abs(np.vdot(E, E).real - np.sin(2 * t) ** 2 * np.sin(gamma / 2) ** 2) < 1e-12
