r"""
Stokes parameters and partly polarized light
============================================

Natural light is neither polarized nor unpolarized but somewhere between,
and an amplitude-and-phase description cannot say where. In 1852 George
Gabriel Stokes described any beam, whatever its coherence, by four
measurable intensities,

.. math::

    S_0 = I_{0^\circ} + I_{90^\circ}, \quad S_1 = I_{0^\circ} - I_{90^\circ}, \quad
    S_2 = I_{45^\circ} - I_{135^\circ}, \quad S_3 = I_{\circlearrowleft} - I_{\circlearrowright},

read through a linear polarizer at four angles and through a quarter-wave
plate and polarizer. They add for incoherent beams, and the degree of
polarization :math:`P = \sqrt{S_1^2 + S_2^2 + S_3^2}/S_0` runs from 0 for
natural light to 1 for a pure state. Poincaré (1892) drew the normalized
:math:`(S_1, S_2, S_3)/S_0` as a point on a sphere: linear states on the
equator, circular ones at the poles, partly polarized light inside.

This example measures the Stokes vector of a partly polarized beam with
the four-polarizer recipe, follows linear light through a rotating
quarter-wave plate on the Poincaré sphere, and computes how polarized
sunlight becomes after reflection from glass.
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.optics import (
    brewster_angle,
    degree_of_polarization,
    fresnel_coefficients,
    jones_vector,
    linear_polarizer,
    mueller_matrix,
    stokes_parameters,
    stokes_vector,
    wave_plate,
)

fig = plt.figure(figsize=(15, 4.6))
ax_meas = fig.add_subplot(1, 3, 1)
ax_sphere = fig.add_subplot(1, 3, 2, projection="3d")
ax_refl = fig.add_subplot(1, 3, 3)

# %%
# Measuring a Stokes vector with polarizers and a quarter-wave plate
# ------------------------------------------------------------------
# A beam that is 60% polarized, its polarized part an ellipse at 30 deg with
# ellipticity angle 15 deg. Each measured intensity is the first row of a
# Mueller matrix product, exactly what a detector behind the optics reads.
S_true = stokes_vector(1.0, 0.6, np.radians(30), np.radians(15))


def detect(*elements):
    S = S_true
    for J in elements:
        S = mueller_matrix(J) @ S
    return S[0]


I0, I45, I90, I135 = (detect(linear_polarizer(np.radians(a))) for a in (0, 45, 90, 135))
qwp = wave_plate(np.pi / 2, 0.0)
I_plus = detect(qwp, linear_polarizer(-np.pi / 4))  # S3 = +1 light leaves the plate at -45 deg
I_minus = detect(qwp, linear_polarizer(np.pi / 4))
S_meas = 2 * np.array([(I0 + I90) / 2, (I0 - I90) / 2, (I45 - I135) / 2, (I_plus - I_minus) / 2])
x = np.arange(4)
ax_meas.bar(x - 0.18, S_true, 0.36, color="0.6", label="true")
ax_meas.bar(x + 0.18, S_meas, 0.36, color="steelblue", label="from six intensities")
ax_meas.set_xticks(x, ["$S_0$", "$S_1$", "$S_2$", "$S_3$"])
ax_meas.axhline(0, color="k", lw=0.8)
ax_meas.set_title(f"Measured Stokes vector, P = {degree_of_polarization(S_meas):.2f}")
ax_meas.legend(fontsize=8)

# %%
# Linear light through a rotating quarter-wave plate on the Poincaré sphere
# ---------------------------------------------------------------------------
# Horizontal light meets a quarter-wave plate whose fast axis turns through
# 180 degrees. The output traces a figure eight, touching the poles
# (circular light) when the plate is at +-45 degrees.
u, v = np.meshgrid(np.linspace(0, 2 * np.pi, 40), np.linspace(0, np.pi, 20))
ax_sphere.plot_wireframe(np.cos(u) * np.sin(v), np.sin(u) * np.sin(v), np.cos(v), color="0.85", lw=0.5)
plate = np.radians(np.linspace(0, 180, 361))
path = np.array([stokes_parameters(wave_plate(np.pi / 2, t) @ jones_vector(0.0)) for t in plate])
ax_sphere.plot(path[:, 1], path[:, 2], path[:, 3], color="crimson", lw=2)
S_45 = stokes_parameters(wave_plate(np.pi / 2, np.pi / 4) @ jones_vector(0.0))
ax_sphere.scatter(*S_45[1:], color="k", s=30)
ax_sphere.text(*S_45[1:], "  QWP at 45 deg", fontsize=8)
ax_sphere.set_xlabel("$S_1$")
ax_sphere.set_ylabel("$S_2$")
ax_sphere.set_zlabel("$S_3$")
ax_sphere.set_box_aspect((1, 1, 1))
ax_sphere.set_title("Poincaré sphere")

# %%
# Polarization by reflection
# --------------------------
# Unpolarized light reflected from glass. The reflecting surface acts on
# the (s, p) components with the diagonal Jones matrix diag(r_p, r_s)
# (p along x, s along y), and its Mueller matrix carries the unpolarized
# Stokes vector to a partly polarized one with P = (R_s - R_p)/(R_s + R_p).
theta = np.radians(np.linspace(0, 89, 179))
P_refl = []
for t in theta:
    c = fresnel_coefficients(1.0, 1.5, t)
    S_r = mueller_matrix(np.diag([c["r_p"], c["r_s"]])) @ stokes_vector(1.0, 0.0)
    P_refl.append(degree_of_polarization(S_r))
P_refl = np.array(P_refl)
R = fresnel_coefficients(1.0, 1.5, theta)
ax_refl.plot(np.degrees(theta), P_refl, color="seagreen", lw=2, label="Mueller calculus")
ax_refl.plot(np.degrees(theta[::10]), ((R["R_s"] - R["R_p"]) / (R["R_s"] + R["R_p"]))[::10], "ko", ms=4, label=r"$(R_s - R_p)/(R_s + R_p)$")
ax_refl.axvline(np.degrees(brewster_angle(1.0, 1.5)), color="k", ls=":", lw=1)
ax_refl.set_xlabel("angle of incidence (deg)")
ax_refl.set_ylabel("degree of polarization P")
ax_refl.set_title("Reflected natural light, glass n = 1.5")
ax_refl.legend(fontsize=8)
plt.tight_layout()
plt.show()

# %%
# Check
# -----
assert np.allclose(S_meas, S_true, atol=1e-12)
assert abs(degree_of_polarization(S_meas) - 0.6) < 1e-12
assert abs(abs(S_45[3]) - 1) < 1e-12 and abs(S_45[1]) < 1e-12 and abs(S_45[2]) < 1e-12
assert np.allclose(np.linalg.norm(path[:, 1:], axis=1), 1, atol=1e-12)
assert np.allclose(P_refl, (R["R_s"] - R["R_p"]) / (R["R_s"] + R["R_p"]), atol=1e-12)
assert abs(P_refl[0]) < 1e-12
B = fresnel_coefficients(1.0, 1.5, brewster_angle(1.0, 1.5))
assert abs(degree_of_polarization(mueller_matrix(np.diag([B["r_p"], B["r_s"]])) @ stokes_vector(1.0, 0.0)) - 1) < 1e-12
