"""
概要:
    交流電場で駆動される1次元調和ポテンシャル中の電子を可視化します。
詳細説明:
    計算には無次元化された振動子単位を使用します。
    xi = x / sqrt(hbar/(m omega0)), tau = omega0 t,
    H/(hbar omega0) = -1/2 d^2/dxi^2 + 1/2 xi^2 + f0 xi cos(Omega tau)
    ここで f0 = e E0 sqrt(hbar/(m omega0))/(hbar omega0) です。
    符号は電子に対応し、そのポテンシャルエネルギーは +e E(t) x となります。
    波動関数は2次のスプリットオペレータ法を用いて伝播されます。
    減衰は現象論的な重心摩擦 q'' + gamma q' + q = -f(t) として扱われます。
    数値モードでは一様な運動量キックを適用し、解析モードでは定数パラメータステップごとに重心を厳密に伝播させ、ガウシアン波束を使用します。
    これは熱緩和や一般的な開放量子系モデルではありません。
    波動関数の垂直オフセットの1と2は表示用のベースラインであり、エネルギーではありません。
"""

# Labeled version: numerical and analytic animation modes.

import argparse

import numpy as np
from scipy.linalg import expm
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.widgets import Button, RadioButtons, Slider


class DrivenOscillator:
    """
    概要:
        駆動される1次元調和振動子を数値的に解くためのクラスです。
    詳細説明:
        FFTベースのスプリットオペレータ法を用いて波動関数の時間発展を計算します。
    引数:
        :param ngrid: 空間グリッドの点数
        :type ngrid: int
        :param xmax: 空間グリッドの最大値
        :type xmax: float
        :param dt: 時間ステップ
        :type dt: float
        :param f0: 電場振幅
        :type f0: float
        :param omega: 駆動角振動数
        :type omega: float
        :param initial_n: 初期状態の調和振動子量子数
        :type initial_n: int
    """
    def __init__(self, ngrid=1024, xmax=9.0, dt=0.004, f0=0.20, omega=1.0,
                 initial_n=0):
        self.x = np.linspace(-xmax, xmax, ngrid, endpoint=False)
        self.dx = self.x[1] - self.x[0]
        self.k = 2.0 * np.pi * np.fft.fftfreq(ngrid, d=self.dx)
        self.dt = dt
        self.f0 = f0
        self.omega = omega
        self.tau = 0.0
        self.gamma = 0.0

        # Harmonic-oscillator eigenfunctions generated by the recurrence.
        psi = np.pi ** (-0.25) * np.exp(-self.x**2 / 2.0)
        if initial_n > 0:
            psi1 = np.sqrt(2.0) * self.x * psi
            for n in range(1, initial_n):
                psi, psi1 = psi1, (
                    np.sqrt(2.0 / (n + 1.0)) * self.x * psi1
                    - np.sqrt(n / (n + 1.0)) * psi
                )
            psi = psi1
        self.psi = psi.astype(complex)
        self._normalize()
        self.kinetic_half = np.exp(-1j * (self.k**2 / 2.0) * dt)

    def _normalize(self):
        """
        概要:
            波動関数のノルムを1に正規化します。
        """
        self.psi /= np.sqrt(np.sum(np.abs(self.psi) ** 2) * self.dx)

    def potential(self, tau):
        """
        概要:
            指定された時刻におけるポテンシャルエネルギーを計算します。
        引数:
            :param tau: 無次元化された時間
            :type tau: float
        戻り値:
            :returns: ポテンシャルの配列
            :rtype: numpy.ndarray
        """
        return 0.5 * self.x**2 + self.f0 * self.x * np.cos(self.omega * tau)

    def damp(self, duration):
        """
        概要:
            波束の形状を保ちながら、重心の運動量に対して減衰を適用します。
        引数:
            :param duration: 減衰を適用する時間
            :type duration: float
        """
        # Uniform momentum kick damps only the centroid, preserving packet shape.
        derivative = np.fft.ifft(1j * self.k * np.fft.fft(self.psi))
        momentum = float(np.real(np.sum(self.psi.conj() * (-1j * derivative)) * self.dx))
        delta = momentum * np.expm1(-self.gamma * duration)
        self.psi *= np.exp(1j * delta * self.x)

    def step(self, nsteps=1):
        """
        概要:
            指定されたステップ数だけ波動関数を時間発展させます。
        詳細説明:
            各ステップの途中でポテンシャルを評価するスプリットオペレータ法を使用します。
        引数:
            :param nsteps: 進めるステップ数
            :type nsteps: int
        """
        for _ in range(nsteps):
            if self.gamma:
                self.damp(self.dt / 2)
            mid = self.tau + 0.5 * self.dt
            phase_v = np.exp(-0.5j * self.potential(mid) * self.dt)
            self.psi *= phase_v
            self.psi = np.fft.ifft(self.kinetic_half * np.fft.fft(self.psi))
            self.psi *= phase_v
            if self.gamma:
                self.damp(self.dt / 2)
            self.tau += self.dt
        self._normalize()  # suppress accumulated FFT round-off error

    def expectation_x(self):
        """
        概要:
            位置xの期待値を計算します。
        戻り値:
            :returns: 位置の期待値
            :rtype: float
        """
        return float(np.sum(self.x * np.abs(self.psi) ** 2) * self.dx)


class AnalyticDrivenOscillator:
    """
    概要:
        初期基底状態の振動子に対するコヒーレント状態の厳密解を提供するクラスです。
    詳細説明:
        電場により中心がq(t)だけシフトします。q(t)は q''+q=-f0 cos(Omega t) の解です。
        減衰は現象論的な重心摩擦であり、バスのマスター方程式ではありません。
        表示されるn=0とn=1の曲線は、このコヒーレント状態の最初の2つの定常基底項であり、その和は一般に完全な状態とはなりません。
    引数:
        :param x: 空間グリッドの配列
        :type x: numpy.ndarray
        :param dt: 時間ステップ
        :type dt: float
        :param f0: 電場振幅
        :type f0: float
        :param omega: 駆動角振動数
        :type omega: float
    """
    def __init__(self, x, dt=0.004, f0=0.20, omega=1.0):
        self.x, self.dt, self.f0, self.omega = x, dt, f0, omega
        self.dx = x[1] - x[0]
        self.tau = 0.0
        self.gamma = 0.0
        self.q = self.p = 0.0
        self._key = None
        self.phi0 = np.pi ** (-0.25) * np.exp(-x**2 / 2.0)
        self.phi1 = np.sqrt(2.0) * x * self.phi0

    def potential(self, tau):
        """
        概要:
            指定された時刻におけるポテンシャルエネルギーを計算します。
        引数:
            :param tau: 無次元化された時間
            :type tau: float
        戻り値:
            :returns: ポテンシャルの配列
            :rtype: numpy.ndarray
        """
        return 0.5 * self.x**2 + self.f0 * self.x * np.cos(self.omega * tau)

    def qp(self):
        """
        概要:
            現在位置と運動量を返します。
        戻り値:
            :returns: 位置と運動量のタプル
            :rtype: tuple
        """
        return self.q, self.p

    def wavefunction(self):
        """
        概要:
            現在の波動関数を計算します。
        戻り値:
            :returns: 波動関数の配列
            :rtype: numpy.ndarray
        """
        q, p = self.qp()
        # An overall phase is immaterial for density and omitted deliberately.
        return np.exp(1j * p * (self.x - q / 2.0)) * np.pi**(-0.25) * np.exp(-(self.x-q)**2 / 2.0)

    def components_01(self):
        """
        概要:
            基底状態と第1励起状態の成分を計算します。
        戻り値:
            :returns: 状態0の波、状態1の波、状態0の係数、状態1の係数のタプル
            :rtype: tuple
        """
        q, p = self.qp()
        alpha = (q + 1j * p) / np.sqrt(2.0)
        c0 = np.exp(-0.5 * abs(alpha)**2)
        c1 = alpha * c0
        # Same phase convention as wavefunction(); c_n already includes motion.
        psi0 = c0 * self.phi0
        psi1 = c1 * self.phi1
        return psi0, psi1, c0, c1

    def step(self, nsteps=1):
        """
        概要:
            指定されたステップ数だけ状態を時間発展させます。
        引数:
            :param nsteps: 進めるステップ数
            :type nsteps: int
        """
        duration = nsteps * self.dt
        key = (self.f0, self.omega, self.gamma, duration)
        if key != self._key:
            matrix = np.array([[0, 1, 0, 0], [-1, -self.gamma, -self.f0, 0],
                               [0, 0, 0, -self.omega], [0, 0, self.omega, 0]])
            self._propagator = expm(matrix * duration)
            self._key = key
        state = self._propagator @ [self.q, self.p, np.cos(self.omega*self.tau),
                                     np.sin(self.omega*self.tau)]
        self.q, self.p = state[:2]
        self.tau += duration

    def expectation_x(self):
        """
        概要:
            位置の期待値を返します。
        戻り値:
            :returns: 位置の期待値
            :rtype: float
        """
        return self.qp()[0]


def main():
    """
    概要:
        コマンドライン引数を解析し、駆動調和振動子のシミュレーションとアニメーションを実行します。
    """
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--field", type=float, default=0.20,
                        help="dimensionless field amplitude f0 (default: 0.20)")
    parser.add_argument("--omega", type=float, default=1.0,
                        help="drive angular frequency Omega/omega0 (default: 1.0)")
    parser.add_argument("--state", type=int, default=0,
                        help="initial harmonic-oscillator quantum number (default: 0)")
    parser.add_argument("--mode", choices=("numerical", "analytic"), default="numerical",
                        help="propagation mode (analytic is exact for initial n=0)")
    parser.add_argument("--damping", type=float, default=0.0,
                        help="centroid damping gamma/omega0 (default: 0)")
    args = parser.parse_args()
    if not 0 <= args.damping <= 2:
        parser.error("--damping must be between 0 and 2")

    numerical = DrivenOscillator(f0=args.field, omega=args.omega, initial_n=args.state)
    analytic = AnalyticDrivenOscillator(numerical.x, f0=args.field, omega=args.omega)
    numerical.gamma = analytic.gamma = args.damping
    sim = numerical if args.mode == "numerical" else analytic
    initial_numerical_psi = numerical.psi.copy()
    steps_per_frame = 8
    density_scale = 3.0
    running = True

    fig, ax = plt.subplots(figsize=(12, 8))
    fig.subplots_adjust(bottom=0.38)
    ax.set(xlim=(-7, 7), ylim=(-0.8, 5.3), xlabel=r"$\xi=x/x_0$",
           ylabel=r"energy / probability density",
           title="Driven 1D harmonic oscillator (dimensionless units)")
    ax.grid(alpha=0.25)
    fixed_potential, = ax.plot(sim.x, 0.5 * sim.x**2, color="gray", lw=0.8,
                               label=r"fixed $V_0(\xi)=\xi^2/2$")
    potential_line, = ax.plot(sim.x, sim.potential(0), color="black", lw=0.7,
                              label=r"total $V(\xi,\tau)$")
    initial_psi = numerical.psi if sim is numerical else analytic.wavefunction()
    density_line, = ax.plot(sim.x, density_scale * np.abs(initial_psi)**2,
                             color="tab:blue", lw=2.0, label=r"$3|\psi|^2$")
    real_line, = ax.plot(sim.x, 1.0 + np.real(initial_psi), color="tab:orange", alpha=0.8,
                          label=r"$1+\mathrm{Re}\,\psi$")
    imag_line, = ax.plot(sim.x, 1.0 + np.imag(initial_psi), color="tab:green", alpha=0.8,
                          label=r"$1+\mathrm{Im}\,\psi$")
    component0_line, = ax.plot([], [], color="tab:purple", lw=1.6, ls="--",
                                label=r"$2+\mathrm{Re}\,\psi_{n=0}$")
    component1_line, = ax.plot([], [], color="tab:brown", lw=1.6, ls="--",
                                label=r"$2+\mathrm{Re}\,\psi_{n=1}$")
    xmean_line = ax.axvline(sim.expectation_x(), color="tab:red", ls="--",
                            label=r"$\langle\xi\rangle$")
    ax.axvline(0, color="0.25", lw=1.5, zorder=2)
    ax.axhline(1, color="0.7", lw=0.6, ls=":")
    ax.axhline(2, color="0.7", lw=0.6, ls=":")
    minimum_line = ax.axvline(-sim.f0, color="tab:cyan", ls="-.", lw=1.5,
                              label=r"potential minimum $\xi_{\min}$")
    minimum_dot, = ax.plot([], [], "o", color="tab:cyan", ms=6)
    info = ax.text(0.02, 0.96, "", transform=ax.transAxes, va="top",
                   bbox={"facecolor": "white", "alpha": 0.85, "edgecolor": "none"})
    ax.legend(loc="upper right")

    # Labels are separate figure text so they remain visible beside the mode box.
    fig.text(0.17, 0.245, r"External field amplitude:  $f_0=eE_0x_0/(\hbar\omega_0)$",
             fontsize=10)
    fig.text(0.17, 0.165, r"Photon energy / level spacing:  $E_\gamma/(\hbar\omega_0)=\Omega/\omega_0$",
             fontsize=10)
    ax_field = fig.add_axes((0.25, 0.210, 0.55, 0.03))
    ax_omega = fig.add_axes((0.25, 0.130, 0.55, 0.03))
    field_slider = Slider(ax_field, "", 0.0, 1.0, valinit=sim.f0, valstep=0.01)
    omega_slider = Slider(ax_omega, "", 0.1, 2.0,
                          valinit=sim.omega, valstep=0.01)
    fig.text(0.17, 0.085, r"Centroid damping: $\gamma/\omega_0$", fontsize=10)
    ax_damping = fig.add_axes((0.25, 0.050, 0.40, 0.025))
    damping_slider = Slider(ax_damping, "", 0.0, 2.0,
                            valinit=args.damping, valstep=0.01)
    button_ax = fig.add_axes((0.72, 0.035, 0.11, 0.06))
    button = Button(button_ax, "Pause")
    restart_ax = fig.add_axes((0.84, 0.035, 0.11, 0.06))
    restart_button = Button(restart_ax, "Restart")
    mode_ax = fig.add_axes((0.015, 0.115, 0.13, 0.115))
    mode_choice = RadioButtons(mode_ax, ("numerical", "analytic"), active=(args.mode == "analytic"))

    def on_slider(_):
        for engine in (numerical, analytic):
            engine.f0 = field_slider.val
            engine.omega = omega_slider.val
            engine.gamma = damping_slider.val

    def on_mode(label):
        nonlocal sim
        old = sim
        sim = numerical if label == "numerical" else analytic
        if sim is old:
            return
        if sim is analytic:
            analytic.q = numerical.expectation_x()
            derivative = np.fft.ifft(1j * numerical.k * np.fft.fft(numerical.psi))
            analytic.p = float(np.real(np.sum(numerical.psi.conj() * (-1j*derivative))*numerical.dx))
        else:
            numerical.psi = analytic.wavefunction().copy()
            numerical._normalize()
        sim.tau = old.tau

    def toggle(_):
        nonlocal running
        running = not running
        button.label.set_text("Pause" if running else "Resume")

    def restart(_):
        nonlocal running
        numerical.tau = analytic.tau = 0.0
        numerical.psi = initial_numerical_psi.copy()
        analytic.q = analytic.p = 0.0
        running = True
        button.label.set_text("Pause")
        draw_frame()
        fig.canvas.draw_idle()

    restart_button.on_clicked(restart)
    damping_slider.on_changed(on_slider)
    field_slider.on_changed(on_slider)
    omega_slider.on_changed(on_slider)
    button.on_clicked(toggle)
    mode_choice.on_clicked(on_mode)

    def draw_frame():
        psi = sim.psi if sim is numerical else sim.wavefunction()
        rho = np.abs(psi) ** 2
        potential_line.set_ydata(sim.potential(sim.tau))
        density_line.set_ydata(density_scale * rho)
        real_line.set_ydata(1.0 + np.real(psi))
        imag_line.set_ydata(1.0 + np.imag(psi))
        xmean_line.set_xdata([sim.expectation_x()] * 2)
        minimum = -sim.f0 * np.cos(sim.omega * sim.tau)
        minimum_line.set_xdata([minimum] * 2)
        minimum_dot.set_data([minimum], [-0.5 * minimum**2])
        norm = np.sum(rho) * sim.dx
        if sim is analytic:
            psi0, psi1, c0, c1 = analytic.components_01()
            component0_line.set_data(sim.x, 2.0 + np.real(psi0))
            component1_line.set_data(sim.x, 2.0 + np.real(psi1))
            component_text = rf"$|c_0|^2={abs(c0)**2:.3f},\ |c_1|^2={abs(c1)**2:.3f}$"
        else:
            component0_line.set_data([], [])
            component1_line.set_data([], [])
            component_text = ""
        photon_energy = sim.omega              # E_gamma/(hbar omega0)
        level_spacing = 1.0                    # (E1-E0)/(hbar omega0)
        detuning = photon_energy - level_spacing
        if abs(detuning) < 0.02:
            resonance = "on resonance"
        elif abs(detuning) < 0.10:
            resonance = "near resonance"
        else:
            resonance = "off resonance"
        info.set_text(
            f"{('analytic' if sim is analytic else 'numerical')} mode;  tau = omega0 t = {sim.tau:.2f}" + "\n"
            + rf"$\langle\xi\rangle={sim.expectation_x():.3f},\ \xi_{{\min}}={minimum:.3f},\ \gamma/\omega_0={sim.gamma:.2f}$" + "\n"
            + rf"$E_\gamma/(\hbar\omega_0)={photon_energy:.3f}$,  $(E_1-E_0)/(\hbar\omega_0)={level_spacing:.3f}$" + "\n"
            + rf"$[E_\gamma-(E_1-E_0)]/(\hbar\omega_0)={detuning:+.3f}$  ({resonance})" + "\n"
            + rf"$\int |\psi|^2d\xi={norm:.8f}$" + ("\n" + component_text if component_text else "")
        )
        return (fixed_potential, potential_line, density_line, real_line, imag_line,
                component0_line, component1_line, xmean_line, minimum_line, minimum_dot, info)

    def update(_):
        if running:
            sim.step(steps_per_frame)
        return draw_frame()

    animation = FuncAnimation(fig, update, init_func=draw_frame, interval=30, blit=False, cache_frame_data=False)
    # Keep a reference alive until the GUI closes.
    _ = animation
    plt.show()


if __name__ == "__main__":
    main()