r"""
Euler's forced oscillator: resonance of a driven, damped spring
===============================================================

Euler (1739) found that a spring driven at its own natural frequency
grows without bound. With damping the growth stops at a finite
amplitude. :class:`~physicskit.classical.systems.newtonian.DrivenDampedOscillator`
solves :math:`\ddot x + 2\beta\dot x + \omega_0^2 x = (F_0/m)\cos\omega t`.
After the transient decays, the oscillator moves at the drive frequency
with amplitude
:math:`A(\omega) = (F_0/m)/\sqrt{(\omega_0^2-\omega^2)^2 + 4\beta^2\omega^2}`
and lags the drive by a phase :math:`\delta` that passes :math:`\pi/2`
at :math:`\omega_0`. The absorbed power has a peak of full width
:math:`2\beta`, so a high-:math:`Q` oscillator (:math:`Q = \omega_0/2\beta`)
responds only close to resonance.
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.classical.systems.newtonian import DrivenDampedOscillator

omega0 = 1.0

# %%
# Transient and steady state
# --------------------------
#
# Started from rest and driven exactly at resonance, the oscillator builds
# up over a time of order :math:`1/\beta`. The integration follows the
# exact solution (transient plus steady state) to round-off.

osc = DrivenDampedOscillator(0.0, 0.0, omega0=omega0, beta=0.05, F0=0.1, omega=omega0)
res = osc.integrate((0.0, 150.0), 0.01, method="rk4")
fig, ax = plt.subplots(figsize=(9, 3.8))
ax.plot(res.t, res.y[:, 0], lw=1, label="integrated")
ax.plot(res.t, osc.analytic_solution(res.t), "k:", lw=1, label="exact")
env = osc.amplitude_response() * (1 - np.exp(-osc.beta * res.t))
ax.plot(res.t, env, "C3--", lw=1, label=r"$A(1 - e^{-\beta t})$")
ax.plot(res.t, -env, "C3--", lw=1)
ax.set_xlabel("t")
ax.set_ylabel("x")
ax.set_title(r"Build-up at resonance ($\omega = \omega_0$, $Q = 10$)")
ax.legend(fontsize=8, loc="lower right")
fig.tight_layout()

# %%
# Resonance curves
# ----------------
#
# Less damping gives a taller, narrower peak. The peak moves down to
# :math:`\sqrt{\omega_0^2 - 2\beta^2}`. The phase lag steepens into a step
# at :math:`\omega_0`.

w = np.linspace(0.01, 2.0, 2000)
fig2, (a1, a2) = plt.subplots(1, 2, figsize=(12, 4.2))
for beta in (0.05, 0.1, 0.2, 0.4):
    o = DrivenDampedOscillator(0.0, 0.0, omega0=omega0, beta=beta, F0=1.0)
    a1.plot(w, o.amplitude_response(w), label=rf"$Q = {o.quality_factor:.2g}$")
    a1.plot(o.resonance_frequency, o.amplitude_response(o.resonance_frequency), "k.", ms=5)
    a2.plot(w, o.phase_lag(w) / np.pi)
a1.set_yscale("log")
a1.set_xlabel(r"$\omega/\omega_0$")
a1.set_ylabel(r"$A\,m\omega_0^2/F_0$")
a1.set_title("Amplitude")
a1.legend(fontsize=8)
a2.axhline(0.5, color="0.6", ls=":")
a2.set_xlabel(r"$\omega/\omega_0$")
a2.set_ylabel(r"$\delta/\pi$")
a2.set_title("Phase lag behind the drive")
fig2.tight_layout()

# %%
# Absorbed power and the width :math:`2\beta`
# -------------------------------------------
#
# The drive's mean power :math:`m\beta\omega^2A^2` falls to half its peak
# at :math:`\omega_\pm = \sqrt{\omega_0^2+\beta^2} \pm \beta`, which are
# exactly :math:`2\beta` apart.

o = DrivenDampedOscillator(0.0, 0.0, omega0=omega0, beta=0.1, F0=1.0)
P = o.mean_power(w)
w_plus = np.sqrt(omega0**2 + o.beta**2) + o.beta
w_minus = np.sqrt(omega0**2 + o.beta**2) - o.beta
fig3, ax3 = plt.subplots(figsize=(8, 4))
ax3.plot(w, P / P.max(), lw=2)
ax3.axhline(0.5, color="0.6", ls=":")
ax3.axvspan(w_minus, w_plus, color="C1", alpha=0.2, label=rf"width $= 2\beta = {w_plus - w_minus:.2f}$")
ax3.set_xlabel(r"$\omega/\omega_0$")
ax3.set_ylabel(r"$\langle P\rangle / P_\max$")
ax3.set_title("Power resonance (Q = 5)")
ax3.legend()
fig3.tight_layout()

# %%
# Check
# -----
# The RK4 integration matches the exact solution (to 1e-7); the steady amplitude at
# resonance is F0/(2 m beta omega0); the lag is pi/2 at omega0; the
# half-power points are 2 beta apart and the peak sits at omega0.
assert np.max(np.abs(res.y[:, 0] - osc.analytic_solution(res.t))) < 1e-7
assert abs(osc.amplitude_response() - 0.1 / (2 * 0.05 * omega0)) < 1e-12
assert abs(osc.phase_lag() - np.pi / 2) < 1e-12
assert abs(o.mean_power(w_plus) / o.mean_power(omega0) - 0.5) < 1e-12
assert abs(o.mean_power(w_minus) / o.mean_power(omega0) - 0.5) < 1e-12
assert abs((w_plus - w_minus) - 2 * o.beta) < 1e-12
assert abs(w[np.argmax(P)] - omega0) < 1e-3
