r"""
Davis and Heller's dynamical tunnelling
=========================================

Davis and Heller (1981) studied two coupled oscillators, a symmetric
stretch :math:`s` and an unsymmetric stretch :math:`u`,

.. math::

    H=\tfrac12(p_s^2+p_u^2)+\tfrac12(\omega_s^2s^2+\omega_u^2u^2)+\lambda s u^2,

with :math:`\omega_s=1`, :math:`\omega_u=1.1`, :math:`\lambda=-0.11` and
:math:`\hbar=1`. The potential is symmetric under :math:`u\to-u`, and below
dissociation there is no energy barrier between the two sides. Even so,
above a certain energy the classical phase space splits into two mirror
regions of regular motion that no trajectory crosses. Quantum mechanically
the eigenstates still have definite parity, so they come in even/odd
doublets. A state localized on one side tunnels to the mirror side in the
time :math:`\pi/\Delta E`. Davis and Heller called this *dynamical
tunnelling*: tunnelling through a barrier in phase space, not in the
potential.

The functions used here are in
:mod:`physicskit.semiclassical.systems.dynamical_tunnelling`.
"""

# %%
import matplotlib.pyplot as plt
import numpy as np

from physicskit.semiclassical.systems.dynamical_tunnelling import (
    davis_heller_dissociation_energy,
    davis_heller_eigenstates,
    davis_heller_surface_of_section,
    davis_heller_wavefunction,
    local_mode_asymmetry,
    symmetric_stretch_instability_energy,
    symmetric_stretch_monodromy_trace,
    tunnelling_doublets,
)

# %%
# Classical phase space splits in two
# -----------------------------------
# On the symmetric-stretch orbit :math:`u=0` the unsymmetric stretch obeys
# a Mathieu equation. The orbit turns unstable where the Mathieu
# characteristic value :math:`a_2(q)` reaches :math:`4\omega_u^2/\omega_s^2`.
# Above that energy the section :math:`s=0` at :math:`E=9` shows two mirror
# islands around a hyperbolic point at the origin, one for each local
# stretch. Black orbits start at :math:`(u,p_u)`, red ones at the mirror
# point :math:`(-u,-p_u)`.
E_inst = symmetric_stretch_instability_energy()
E_dis = davis_heller_dissociation_energy()
print(f"symmetric stretch unstable above E = {E_inst:.4f}  (dissociation at {E_dis})")
print(f"monodromy trace at threshold: {symmetric_stretch_monodromy_trace(E_inst):.10f}")

E_sec = 9.0
fig1, ax = plt.subplots(figsize=(6, 5))
starts = [(0.85, 2.2), (0.6, 1.6), (0.4, 1.1), (1.2, 0.5), (0.3, -2.6), (2.0, 0.0), (0.05, 0.05)]
island = np.empty(0)
for u0, pu0 in starts:
    for sign in (1, -1):
        u, pu = davis_heller_surface_of_section(E_sec, sign * u0, sign * pu0, n_crossings=300)
        ax.plot(u, pu, ".", ms=1, color="k" if sign > 0 else "firebrick")
        if (u0, pu0, sign) == (0.85, 2.2, 1):
            island = pu
ax.plot(0, 0, "x", color="royalblue", ms=8, mew=2, label="unstable symmetric stretch")
ax.set_xlabel(r"$u$")
ax.set_ylabel(r"$p_u$")
ax.set_title(rf"Surface of section $s=0$, $E={E_sec:g}$")
ax.legend(loc="lower right", fontsize=8)
fig1.tight_layout()

# %%
# Tunnelling doublets
# -------------------
# Diagonalizing :math:`H` in a harmonic basis gives states of definite
# parity in :math:`u`. Pairing each state with its nearest opposite-parity
# neighbour picks out the doublets. The lowest pair of each polyad splits
# less and less as the energy rises past :math:`E_\mathrm{inst}`: the
# islands move apart and the phase-space barrier widens. States 37 and 38
# in Davis and Heller's numbering (36 and 37 here, counting from zero) are
# the doublet they studied.
n_s, n_u = 30, 40
E, V, P = davis_heller_eigenstates(n_s, n_u)
pairs = tunnelling_doublets(E[:68], P[:68])
Ed = np.array([E[i] for i, _, _ in pairs])
dE = np.array([d for _, _, d in pairs])
lowest = np.isin(np.round(Ed, 2), [2.04, 3.04, 4.04, 5.03, 6.03, 7.02, 8.01, 8.99, 9.96, 10.91, 11.83])

fig2, ax = plt.subplots(figsize=(7, 4))
ax.semilogy(Ed, dE, "o", color="0.5", mfc="none", label="all doublets")
ax.semilogy(Ed[lowest], dE[lowest], "o-", color="firebrick", label="lowest pair of each polyad")
ax.axvline(E_inst, color="royalblue", ls="--", label=r"$E_\mathrm{inst}$")
ax.set_xlabel("energy")
ax.set_ylabel(r"splitting $\Delta E$")
ax.set_title("Dynamical tunnelling splittings")
ax.legend(fontsize=8)
fig2.tight_layout()

# %%
# A local state tunnels to its mirror image
# -----------------------------------------
# The sum of the doublet 36/37 is localized on one side, with
# :math:`\langle su\rangle\neq0`. Evolving it, :math:`\langle su\rangle`
# swings to the opposite sign after :math:`\pi/\Delta E`, about 150 time
# units or 24 vibrational periods, although no classical trajectory makes
# that trip.
i, j = 36, 37
gap = E[j] - E[i]
psi0 = (V[:, i] + V[:, j]) / np.sqrt(2)
c = V.T @ psi0
T = np.pi / gap
ts = np.linspace(0, 2 * T, 201)
asym = np.array([local_mode_asymmetry(V @ (c * np.exp(-1j * E * t)), n_s, n_u) for t in ts])
print(f"doublet 36/37: E = {E[i]:.4f}, Delta E = {gap:.5f}, transfer time pi/Delta E = {T:.1f}")

s = np.linspace(-5, 6, 221)
x = np.linspace(-6, 6, 201)
fig3, axes = plt.subplots(1, 3, figsize=(12, 3.8))
for ax, t, label in [(axes[0], 0.0, "$t=0$"), (axes[1], T, r"$t=\pi/\Delta E$")]:
    psi_t = V @ (c * np.exp(-1j * E * t))
    dens = davis_heller_wavefunction(psi_t.real, s, x, n_s, n_u) ** 2 + davis_heller_wavefunction(psi_t.imag, s, x, n_s, n_u) ** 2
    ax.pcolormesh(s, x, dens, shading="auto", cmap="magma")
    ax.set_xlabel(r"$s$")
    ax.set_ylabel(r"$u$")
    ax.set_title(label)
axes[2].plot(ts / T, asym, color="k", label="quantum")
axes[2].plot(ts / T, asym[0] * np.cos(gap * ts), "--", color="firebrick", label=r"$\cos\Delta E\,t$")
axes[2].set_xlabel(r"$t\,\Delta E/\pi$")
axes[2].set_ylabel(r"$\langle su\rangle$")
axes[2].legend(fontsize=8)
fig3.tight_layout()
plt.show()

# %%
# Check
# -----
# The Mathieu threshold is where the monodromy trace reaches 2; the island
# orbit at :math:`E=9` never reaches the mirror island; the splittings of
# the lowest pairs fall above :math:`E_\mathrm{inst}`; the paper's doublet
# 37/38 is split by about 0.021; and the local state moves fully to the
# mirror side.
assert abs(symmetric_stretch_monodromy_trace(E_inst) - 2.0) < 1e-8
assert 6.7 < E_inst < 6.75 and abs(E_dis - 15.125) < 1e-10
assert len(island) == 300 and np.all(island > 0)
above = dE[lowest][Ed[lowest] > E_inst]
assert len(above) == 6 and np.all(np.diff(above) < 0) and above[-1] < 1e-3
assert abs(gap - 0.02085) < 1e-4
assert np.allclose(asym, asym[0] * np.cos(gap * ts), atol=1e-10)
assert asym[0] < -3 and abs(asym[100] + asym[0]) < 1e-10
