r"""
Wigner's coupling coefficients: adding two angular momenta
==========================================================

Wigner (1931) built the states of definite total angular momentum
:math:`|J M\rangle` out of products :math:`|j_1 m_1\rangle|j_2 m_2\rangle`
with the coupling (Clebsch-Gordan) coefficients
:math:`\langle j_1 m_1; j_2 m_2|J M\rangle`.
:func:`~physicskit.quantum.chapters.angular_momentum.clebsch_gordan`
evaluates Racah's closed formula for them, and
:func:`~physicskit.quantum.chapters.angular_momentum.couple_spins` assembles
the whole change of basis. Two spins 1/2 give a triplet (:math:`J = 1`)
and a singlet (:math:`J = 0`); spin 1 with spin 1 gives :math:`J = 2, 1, 0`.
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.quantum.chapters.angular_momentum import clebsch_gordan, couple_spins


def label(m):
    return f"{m:+g}" if float(m).is_integer() else f"{int(2 * m):+d}/2"


# %%
# The coupling matrices
# ---------------------
#
# Each column is one :math:`|J M\rangle` written in the product basis. The
# matrix is block diagonal in :math:`M = m_1 + m_2`, and real orthogonal.

fig, axes = plt.subplots(1, 2, figsize=(13, 5.5), gridspec_kw={"width_ratios": [1, 2.2]})
for ax, (j1, j2) in zip(axes, [(0.5, 0.5), (1, 1)]):
    basis = couple_spins(j1, j2)
    im = ax.imshow(basis.matrix, cmap="RdBu_r", vmin=-1, vmax=1)
    ax.set_xticks(range(len(basis.coupled_labels)))
    ax.set_xticklabels([f"|{label(J)}, {label(M)}⟩" for J, M in basis.coupled_labels], rotation=90, fontsize=8)
    ax.set_yticks(range(len(basis.product_labels)))
    ax.set_yticklabels([f"|{label(a)}⟩|{label(b)}⟩" for a, b in basis.product_labels], fontsize=8)
    ax.set_title(f"$j_1 = {label(j1)}$, $j_2 = {label(j2)}$")
fig.colorbar(im, ax=axes, shrink=0.8, label=r"$\langle j_1 m_1; j_2 m_2 | J M\rangle$")

# %%
# Singlet and triplet of two spins 1/2
# ------------------------------------
#
# The coupled states are eigenstates of :math:`\mathbf S_1\cdot\mathbf S_2
# = \tfrac12[J(J+1) - \tfrac32]`: :math:`+1/4` for the triplet and
# :math:`-3/4` for the singlet.

basis = couple_spins(0.5, 0.5)
U = basis.matrix
S1S2 = (U.T @ basis.s1_dot_s2_operator() @ U).real
for (J, M), value in zip(basis.coupled_labels, np.diag(S1S2)):
    print(f"J = {J:g}, M = {M:+g}:  <S1.S2> = {value:+.4f}")

# %%
# Check
# -----
# Two spins 1/2: S1.S2 = +1/4 (triplet) and -3/4 (singlet), the singlet is
# (|+-> - |-+>)/sqrt(2), and <1/2 1/2; 1/2 -1/2 | 1 0> = 1/sqrt(2). For
# 1 x 1 the coupling matrix is orthogonal, and the textbook value
# <1 1; 1 -1 | 0 0> = 1/sqrt(3).
assert np.allclose(np.diag(S1S2), [0.25, 0.25, 0.25, -0.75])
assert np.allclose(S1S2, np.diag(np.diag(S1S2)))
assert np.allclose(U[:, 3], [0, 1 / np.sqrt(2), -1 / np.sqrt(2), 0])
assert abs(clebsch_gordan(0.5, 0.5, 0.5, -0.5, 1, 0) - 1 / np.sqrt(2)) < 1e-12
U11 = couple_spins(1, 1).matrix
assert np.allclose(U11.T @ U11, np.eye(9))
assert abs(clebsch_gordan(1, 1, 1, -1, 0, 0) - 1 / np.sqrt(3)) < 1e-12
