r"""
Airy's water waves: dispersion, group velocity and the slowest ripple
=====================================================================

Airy (1841) worked out small-amplitude waves on water of any depth
:math:`h`. A wave :math:`\eta \propto \cos(kx - \omega t)` must satisfy

.. math::

    \omega^2 = \left(g k + \frac{\sigma k^3}{\rho}\right)\tanh(k h),

where the surface-tension term (added by Kelvin in 1871) matters only for
ripples of a centimetre or less. Long waves (:math:`kh \ll 1`) all travel
at :math:`\sqrt{gh}`, the speed in Saint-Venant's shallow-water equations.
Short gravity waves are dispersive: their phase velocity is
:math:`\sqrt{g/k}`, and a group of them travels at half that speed.
Between the gravity and capillary regimes the phase velocity has a
minimum, 23.1 cm/s at a wavelength of 1.71 cm, so no wave on clean water
is slower.
"""

import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import hilbert

from physicskit.fluids.systems.water_waves import (
    WATER_SURFACE_TENSION,
    capillary_gravity_minimum,
    group_velocity,
    linear_wave_evolution,
    phase_velocity,
)

g = 9.81
sigma = WATER_SURFACE_TENSION

# %%
# Phase and group velocity against wavelength
# -------------------------------------------
#
# Each finite depth bends the deep-water curve over to its own long-wave
# speed :math:`\sqrt{gh}`. At short wavelengths surface tension takes over
# and the speed rises again, with the group velocity now *faster* than the
# crests (:math:`3c/2`).

lam = np.logspace(-3, 3, 600)
k = 2 * np.pi / lam
k_m, c_min, lam_min = capillary_gravity_minimum()

fig, axes = plt.subplots(1, 2, figsize=(13, 4.5))
for h, color in [(np.inf, "k"), (10.0, "C0"), (1.0, "C1"), (0.1, "C2")]:
    label = "deep" if np.isinf(h) else f"h = {h:g} m"
    axes[0].loglog(lam, phase_velocity(k, h, sigma), color=color, lw=2, label=f"$c$, {label}")
    axes[0].loglog(lam, group_velocity(k, h, sigma), color=color, lw=1, ls="--")
    if np.isfinite(h):
        axes[0].axhline(np.sqrt(g * h), color=color, ls=":", lw=1)
axes[0].plot(lam_min, c_min, "ro", label=f"minimum {100 * c_min:.1f} cm/s at {100 * lam_min:.2f} cm")
axes[0].set_xlabel("wavelength (m)")
axes[0].set_ylabel("speed (m/s)")
axes[0].set_title("Phase (solid) and group (dashed) velocity")
axes[0].legend(fontsize=8)

ratio = group_velocity(k, 1.0, sigma) / phase_velocity(k, 1.0, sigma)
axes[1].semilogx(lam, ratio, lw=2)
for y, text in [(0.5, "deep-water gravity: 1/2"), (1.0, "shallow water: 1"), (1.5, "capillary: 3/2")]:
    axes[1].axhline(y, color="0.5", ls=":")
    axes[1].text(1.2e-3, y + 0.03, text, fontsize=8)
axes[1].set_xlabel("wavelength (m)")
axes[1].set_ylabel(r"$c_g / c$")
axes[1].set_title("Group over phase velocity, h = 1 m")
fig.tight_layout()

# %%
# A packet of deep-water swell
# ----------------------------
#
# A group of 2 m waves is evolved exactly, mode by mode, with
# :func:`~physicskit.fluids.systems.water_waves.linear_wave_evolution`.
# The envelope (from the analytic signal) moves at :math:`c_g = c/2`, so
# crests appear at its back, run through it and die out at its front. The
# packet also spreads, because :math:`\omega'' = -\sqrt g/(4k^{3/2})` is
# not zero.

k0, s = 2 * np.pi / 2.0, 3.0
x = np.linspace(-40, 360, 2**13, endpoint=False)
eta0 = np.exp(-(x**2) / (4 * s**2)) * np.cos(k0 * x)
times = np.array([0.0, 40.0, 80.0, 120.0])
eta = linear_wave_evolution(eta0, x, times)
cg, cp = group_velocity(k0), phase_velocity(k0)

fig2, ax2 = plt.subplots(figsize=(13, 4))
centroids, widths = [], []
for i, (t, e) in enumerate(zip(times, eta)):
    env = np.abs(hilbert(e))
    w = env**2 / np.sum(env**2)
    m = np.sum(w * x)
    centroids.append(m)
    widths.append(np.sqrt(np.sum(w * (x - m) ** 2)))
    ax2.plot(x, e - 1.5 * i, color="C0", lw=0.8)
    ax2.plot(x, env - 1.5 * i, color="C3", lw=1.2)
    ax2.text(-38, 0.4 - 1.5 * i, f"t = {t:.0f} s", fontsize=8)
ax2.plot(cg * times, -1.5 * np.arange(times.size) + 1.1, "k^", label=f"$c_g t$, $c_g$ = {cg:.2f} m/s")
ax2.plot(cp * times[:2], -1.5 * np.arange(2) + 1.1, "gv", label=f"$c t$, $c$ = {cp:.2f} m/s")
ax2.set_xlabel("x (m)")
ax2.set_yticks([])
ax2.set_title("A deep-water packet travels at half the crest speed and spreads")
ax2.legend(fontsize=8, loc="upper right")
fig2.tight_layout()

w2 = -0.25 * np.sqrt(g) * k0**-1.5
widths_theory = s * np.sqrt(1 + (w2 * times / (2 * s**2)) ** 2)
for t, m, sd, sdt in zip(times, centroids, widths, widths_theory):
    print(f"t = {t:5.0f} s   centroid {m:7.2f} m (c_g t = {cg * t:7.2f})   width {sd:5.2f} m (theory {sdt:5.2f})")

# %%
# Check
# -----
# Deep water: c_g = c/2. Shallow water: c -> sqrt(gh). The slowest ripple:
# 23.1 cm/s at 1.71 cm, where c_g = c. The packet centroid moves at c_g and
# its width grows as s sqrt(1 + (omega'' t / 2 s^2)^2).
assert abs(group_velocity(0.7) / phase_velocity(0.7) - 0.5) < 1e-12
assert abs(phase_velocity(1e-6, 4.0) - np.sqrt(g * 4.0)) < 1e-6
assert round(100 * c_min, 1) == 23.1 and round(100 * lam_min, 2) == 1.71
assert abs(group_velocity(k_m, sigma=sigma) - c_min) < 1e-12
assert np.max(np.abs(np.array(centroids) - cg * times)) < 0.2
assert np.max(np.abs(np.array(widths) / widths_theory - 1)) < 0.02
