{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "partial-diff-00",
   "metadata": {},
   "source": [
    "# When diffusion destabilises a uniform state\n",
    "Two linearly coupled scalar signals evolve on a periodic ring. The operator for each spatial Fourier mode is only two by two. Compare the wavelengths selected by the continuum equation with those selected by a finite-difference grid. The model describes small deviations; it contains no nonlinear saturation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "partial-diff-01",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "length = 2*np.pi                  # nondimensional circumference\n",
    "cells = 32                       # even number of grid cells\n",
    "slow_diffusion = .02\n",
    "fast_diffusion = 1.\n",
    "assert 4 <= length <= 12 and cells % 2 == 0 and 16 <= cells <= 120\n",
    "assert .01 <= slow_diffusion <= .3 and .2 <= fast_diffusion <= 2.\n",
    "J = np.array([[1., 1.],[-3., -2.]])\n",
    "D = np.diag([slow_diffusion,fast_diffusion])\n",
    "\n",
    "def growth(q):\n",
    "    q = np.asarray(q)\n",
    "    trace = np.trace(J) - (slow_diffusion+fast_diffusion)*q\n",
    "    det = 1 - (fast_diffusion-2*slow_diffusion)*q + slow_diffusion*fast_diffusion*q*q\n",
    "    return (trace+np.sqrt((trace**2-4*det).astype(complex))).real/2\n",
    "\n",
    "indices = np.arange(cells//2+1)\n",
    "k = 2*np.pi*indices/length\n",
    "h = length/cells\n",
    "continuum = growth(k*k)\n",
    "q_mesh = (2*np.sin(k*h/2)/h)**2\n",
    "mesh = growth(q_mesh)\n",
    "print(\"Amplifying continuum modes on this mode list:\", indices[continuum>1e-10])\n",
    "print(\"Amplifying finite-grid modes:\", indices[mesh>1e-10])\n",
    "assert np.allclose(mesh,[np.linalg.eigvals(J-q*D).real.max() for q in q_mesh])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "partial-diff-02",
   "metadata": {},
   "source": [
    "## Compare a dispersion curve with an exact linear wave experiment\n",
    "For each mode prepare the real part of its leading eigenvector and evolve the complex eigenmode before taking the real part. The phase and growth rates in this experiment follow the finite-grid operator exactly. The panels distinguish an incorrect spatial eigenvalue from time-stepping error. Initial amplitudes are small and intentionally comparable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "partial-diff-03",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, (curve, traceplot) = plt.subplots(1,2,figsize=(10,4),layout=\"constrained\")\n",
    "mode_range = np.linspace(0,min(14,cells//2),350)\n",
    "curve.axhline(0,color=\"grey\",lw=.8)\n",
    "curve.plot(mode_range,growth((2*np.pi*mode_range/length)**2),color=\"#145c71\",label=\"continuum dispersion\")\n",
    "visible = indices <= mode_range.max()\n",
    "curve.scatter(indices[visible],mesh[visible],s=20,color=\"#b94626\",label=\"mesh rates\")\n",
    "curve.set(xlabel=\"Spatial mode number\",ylabel=\"Growth rate\",title=\"Which wavelengths can grow?\")\n",
    "curve.legend(fontsize=9)\n",
    "x = np.arange(cells)*h\n",
    "def state_at(t):\n",
    "    profile = np.zeros_like(x)\n",
    "    for j in range(1,min(10,cells//2)+1):\n",
    "        vals,vecs = np.linalg.eig(J-q_mesh[j]*D)\n",
    "        idx = vals.real.argmax()\n",
    "        vec = vecs[:,idx] / vecs[0,idx]\n",
    "        profile += 1e-4*np.real(vec[0]*np.exp(vals[idx]*t+1j*(k[j]*x+.27*j*j)))\n",
    "    return profile\n",
    "for t,color in [(0.,\"#59686a\"),(3.,\"#b94626\"),(7.,\"#145c71\")]:\n",
    "    traceplot.plot(x,state_at(t),color=color,label=f\"t = {t:g}\")\n",
    "traceplot.set(xlabel=\"Position on ring\",ylabel=\"First-field deviation\",title=\"Small signals after mode selection\")\n",
    "traceplot.legend(fontsize=9)\n",
    "for ax in (curve,traceplot): ax.grid(alpha=.2)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "partial-diff-04",
   "metadata": {},
   "source": [
    "## Verify the spatial operator independently\n",
    "Assemble the full periodic matrix for the selected grid. Its most rapidly growing eigenvalue should agree with the Fourier block calculation. In OneSimulation the optional comparison uses its general dense eigensolver. A small positive cut-off avoids classifying roundoff at a neutral boundary as physical growth."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "partial-diff-05",
   "metadata": {},
   "outputs": [],
   "source": [
    "lap = (np.roll(np.eye(cells),1,axis=0) - 2*np.eye(cells) + np.roll(np.eye(cells),-1,axis=0))/h**2\n",
    "full = np.kron(np.eye(cells),J) + np.kron(lap,D)\n",
    "try:\n",
    "    from onesim.numerics.linear.matrices.dense_linear_algebra import eigenvalues_dense as complete_spectrum\n",
    "except ImportError:\n",
    "    complete_spectrum = np.linalg.eigvals\n",
    "rate = complete_spectrum(full).real.max()\n",
    "assert np.isclose(rate,mesh.max(),atol=3e-10)\n",
    "print(f\"Full grid {rate:.8f}; fastest Fourier block {mesh.max():.8f}.\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
