r"""
Taylor-Couette flow: Rayleigh's criterion and the onset of Taylor vortices
==========================================================================

Fluid between two rotating cylinders, the inner one of radius :math:`R_1`
turning at :math:`\Omega_1` and the outer one of radius :math:`R_2` at
:math:`\Omega_2`, moves in circles at :math:`v = Ar + B/r` (circular
Couette flow). Rayleigh (1917) showed that without viscosity this flow is
stable only if the angular momentum :math:`r^2\Omega` grows outward, that
is when :math:`\Omega_2 R_2^2 > \Omega_1 R_1^2`. G. I. Taylor (1923)
solved the viscous problem and built the apparatus to test it: when the
Taylor number

.. math::

    T = -\frac{4 A \Omega_1 d^4}{\nu^2}, \qquad d = R_2 - R_1,

passes a critical value, the flow breaks into stacked, counter-rotating
toroidal vortices. In a narrow gap with co-rotating cylinders the
problem is the same as convection between rigid plates, so
:math:`T_c = 1707.8` at axial wavenumber :math:`a_c = 3.12`. With the outer
cylinder at rest, :math:`T_c = 3389.9`.
"""

import matplotlib.pyplot as plt
import numpy as np

from physicskit.fluids.systems.convection import rayleigh_benard_critical
from physicskit.fluids.systems.instabilities import (
    circular_couette_velocity,
    rayleigh_criterion,
    taylor_couette_critical,
    taylor_couette_marginal_taylor,
)

R1, R2 = 1.0, 1.5
eta = R1 / R2

# %%
# Circular Couette profiles and Rayleigh's criterion
# --------------------------------------------------
#
# Left: the velocity between the cylinders for a few ratios
# :math:`\mu = \Omega_2/\Omega_1`. Right: in the
# :math:`(\Omega_1, \Omega_2)` plane, each grid point is coloured by
# :func:`~physicskit.fluids.systems.instabilities.rayleigh_criterion`. The
# inviscid stability boundary is the line :math:`\Omega_2 = \eta^2\Omega_1`
# (with :math:`\eta = R_1/R_2`), together with :math:`\Omega_1 = 0`.

r = np.linspace(R1, R2, 200)
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
for mu in (-0.5, 0.0, eta**2, 1.0):
    axes[0].plot(r, circular_couette_velocity(r, R1, R2, 1.0, mu), lw=2, label=rf"$\mu = {mu:.3g}$")
axes[0].set_xlabel("r")
axes[0].set_ylabel(r"$v(r)$ for $\Omega_1 = 1$")
axes[0].set_title(r"Circular Couette flow $v = Ar + B/r$")
axes[0].legend(fontsize=8)

W = np.linspace(-1, 1, 121)
W1, W2 = np.meshgrid(W, W)
stable = np.array([[rayleigh_criterion(R1, R2, w1, w2) for w1 in W] for w2 in W])
axes[1].contourf(W1, W2, stable, levels=[-0.5, 0.5, 1.5], colors=["#f4a582", "#92c5de"])
axes[1].plot(W, eta**2 * W, "k--", label=r"$\Omega_2 = \eta^2\Omega_1$")
axes[1].set_xlabel(r"$\Omega_1$")
axes[1].set_ylabel(r"$\Omega_2$")
axes[1].set_title("Rayleigh: stable (blue) and unstable (red)")
axes[1].legend(fontsize=8, loc="lower right")
fig.tight_layout()

# %%
# Marginal stability in the narrow gap
# ------------------------------------
#
# Each curve is the Taylor number at which axisymmetric vortices of axial
# wavenumber :math:`a` neither grow nor decay, from a Chebyshev
# collocation solution of the narrow-gap equations. The minimum of each
# curve is the onset. For :math:`\mu \to 1` the curve is the one for
# Rayleigh-Bénard convection between rigid plates.

a = np.linspace(1.6, 6.0, 60)
fig2, axes2 = plt.subplots(1, 2, figsize=(12, 4.5))
for mu, color in [(0.0, "C0"), (0.5, "C1"), (1.0, "C2")]:
    axes2[0].plot(a, [taylor_couette_marginal_taylor(ai, mu) for ai in a], color=color, lw=2, label=rf"$\mu = {mu:g}$")
    T_c, a_c = taylor_couette_critical(mu)
    axes2[0].plot(a_c, T_c, "o", color=color)
axes2[0].set_xlabel("axial wavenumber a (units of 1/d)")
axes2[0].set_ylabel("marginal Taylor number")
axes2[0].set_ylim(1000, 9000)
axes2[0].set_title("Neutral curves; Taylor vortices above them")
axes2[0].legend(fontsize=8)

mus = np.linspace(0.0, 1.0, 11)
crit = np.array([taylor_couette_critical(m) for m in mus])
axes2[1].plot(mus, crit[:, 0], "o-", lw=2, label="narrow-gap eigenvalue problem")
axes2[1].plot(mus, 2 * 1707.76 / (1 + mus), "k--", label=r"$2 \times 1708/(1 + \mu)$")
axes2[1].set_xlabel(r"$\mu = \Omega_2/\Omega_1$")
axes2[1].set_ylabel(r"$T_c$")
axes2[1].set_title("Critical Taylor number against the rotation ratio")
axes2[1].legend(fontsize=8)
fig2.tight_layout()

# %%
# Check
# -----
# Rayleigh's boundary is mu = eta^2. In the narrow gap, co-rotation (mu -> 1)
# gives the rigid Rayleigh-Benard onset, T_c = 1707.8 at a_c = 3.12, and the
# outer cylinder at rest gives T_c = 3389.9 at a_c = 3.13.
Ra_c, a_rb = rayleigh_benard_critical("rigid")
assert not rayleigh_criterion(R1, R2, 1.0, eta**2 - 1e-9) and rayleigh_criterion(R1, R2, 1.0, eta**2 + 1e-9)
assert abs(crit[-1, 0] - Ra_c) < 1e-3 and abs(crit[-1, 1] - a_rb) < 1e-3
assert round(crit[-1, 0], 1) == 1707.8 and round(crit[-1, 1], 2) == 3.12
assert abs(crit[0, 0] - 3389.9) < 0.1 and round(crit[0, 1], 2) == 3.13
assert np.max(np.abs(crit[:, 0] / (2 * 1707.76 / (1 + mus)) - 1)) < 0.01
