r"""
Landau-Zener transitions at an avoided crossing
===============================================

Landau and Zener (1932) solved the two-level problem
:math:`H(t) = \tfrac12 v t\,\sigma_z + \Delta\,\sigma_x`, whose levels would
cross at :math:`t = 0` without the coupling :math:`\Delta`, and found the
probability of jumping the gap :math:`2\Delta`,
:math:`P = \exp(-2\pi\Delta^2/\hbar v)`
(:func:`~physicskit.quantum.chapters.adiabatic.landau_zener_probability`).
A slow sweep follows the adiabatic level, as Born and Fock's adiabatic
theorem says; a fast one is sudden and keeps the diabatic state.
:func:`~physicskit.quantum.chapters.adiabatic.landau_zener_sweep`
integrates the Schrodinger equation through the crossing.
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.quantum.chapters.adiabatic import landau_zener_probability, landau_zener_sweep

v = 1.0

# %%
# The avoided crossing and three sweeps
# -------------------------------------

t = np.linspace(-8, 8, 400)
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
for Delta in (0.15, 0.5):
    E = np.sqrt((v * t / 2) ** 2 + Delta**2)
    axes[0].plot(t, E, "C0", alpha=0.4 + Delta)
    axes[0].plot(t, -E, "C0", alpha=0.4 + Delta)
axes[0].plot(t, v * t / 2, "k:", lw=1, label="diabatic levels")
axes[0].plot(t, -v * t / 2, "k:", lw=1)
axes[0].set_xlabel("t")
axes[0].set_ylabel("E")
axes[0].set_title(r"Adiabatic levels $\pm\sqrt{(vt/2)^2 + \Delta^2}$")
axes[0].legend()

for Delta in (0.15, 0.35, 0.7):
    res = landau_zener_sweep(Delta, v, T=30)
    line = axes[1].plot(res.t, res.adiabatic_population, label=rf"$\Delta = {Delta}$")[0]
    axes[1].axhline(1 - landau_zener_probability(Delta, v), color=line.get_color(), ls="--", lw=1)
axes[1].set_xlabel("t")
axes[1].set_ylabel("population of the adiabatic level")
axes[1].set_title("Through the crossing: dashed lines are 1 - P_LZ")
axes[1].legend()
fig.tight_layout()

# %%
# From the sudden to the adiabatic limit
# --------------------------------------
#
# The adiabaticity parameter :math:`\Delta^2/\hbar v` sets everything.

Deltas = np.linspace(0.0, 1.2, 25)
P_sim = np.array([landau_zener_sweep(D, v).transition_probability for D in Deltas])
P_lz = np.array([landau_zener_probability(D, v) for D in Deltas])
fig2, ax2 = plt.subplots(figsize=(7, 4.5))
ax2.plot(Deltas**2 / v, P_lz, lw=2, label=r"$e^{-2\pi\Delta^2/\hbar v}$")
ax2.plot(Deltas**2 / v, P_sim, "o", label="integrated sweep")
ax2.set_xlabel(r"$\Delta^2/\hbar v$")
ax2.set_ylabel("probability of a diabatic passage")
ax2.set_yscale("log")
ax2.set_ylim(1e-4, 1.5)
ax2.legend()
fig2.tight_layout()

# %%
# Check
# -----
# The integrated sweep agrees with exp(-2 pi Delta^2 / v) over the whole
# range: P = 1 with no gap (sudden), and P < 1e-3 once Delta^2/v > 1.1
# (adiabatic).
assert np.max(np.abs(P_sim - P_lz)) < 1e-4
assert abs(P_sim[0] - 1) < 1e-9
assert P_sim[-1] < 1e-3
