{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Oblique whistler waves in Hall MHD\n",
    "\n",
    "A uniform plasma is threaded by a magnetic field $\\mathbf B_0$ along $z$. On scales below the ion\n",
    "inertial length $d_i$ the Hall term splits the Alfvén wave into two branches: the fast\n",
    "**whistler** wave and the slower **ion-cyclotron** wave. Their frequency depends on the angle\n",
    "$\\theta$ between the wave vector $\\mathbf k$ and $\\mathbf B_0$.\n",
    "\n",
    "This notebook launches six such waves together in a periodic box, measures their frequencies in\n",
    "a three-dimensional Hall-MHD simulation and compares them with theory."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from onesim.meshing import TensorCollocationMesh\n",
    "from onesim.numerics.discretization import CenteredDifferences, FourierCollocation\n",
    "from onesim.numerics.time import ClassicalRungeKutta4TimeIntegrator\n",
    "from onesim.physics.magnetohydrodynamics import LinearMHDWaves, ResistiveMHD3DSolver\n",
    "from onesim.results import oscillation_fit\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plasma and waves\n",
    "\n",
    "Units with $\\mu_0=1$: density 1, field strength 1 (Alfvén speed $v_A=1$), sound speed\n",
    "$c_s=0.5$ and ion inertial length $d_i=0.5$. `LinearMHDWaves` describes the small-amplitude\n",
    "waves of this plasma. The box has the side $2\\pi$, so wave vectors are integer triples; all six\n",
    "have $|\\mathbf k|=3$ and differ in their angle to the field."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "gamma, hall_coefficient = 5 / 3, 0.5\n",
    "waves = LinearMHDWaves(\n",
    "    density=1.0,\n",
    "    pressure=0.15,\n",
    "    magnetic_field=(0, 0, 1),\n",
    "    gamma=gamma,\n",
    "    hall_coefficient=hall_coefficient,\n",
    ")\n",
    "modes = [\n",
    "    ((0, 0, 3), \"whistler\"),\n",
    "    ((1, 2, 2), \"whistler\"),\n",
    "    ((2, 2, 1), \"whistler\"),\n",
    "    ((0, 3, 0), \"whistler\"),\n",
    "    ((2, 1, 2), \"ion_cyclotron\"),\n",
    "    ((2, -2, 1), \"ion_cyclotron\"),\n",
    "]\n",
    "angles = np.array([np.degrees(np.arccos(abs(k[2]) / 3)) for k, _ in modes])\n",
    "exact = np.array([waves.frequency(k, branch) for k, branch in modes])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reference from the literature\n",
    "\n",
    "Independently of the library, the frequencies follow from the dispersion relation of Hameiri,\n",
    "Ishizawa and Ishida (*Phys. Plasmas* 12, 072109, 2005), a cubic equation for $\\omega^2$:\n",
    "\n",
    "$$\\left(\\omega^2-k_\\parallel^2v_A^2\\right)\\left(\\omega^4-k^2(v_A^2+c_s^2)\\,\\omega^2+k^2k_\\parallel^2v_A^2c_s^2\\right)\n",
    "  =\\omega^2\\,k_\\parallel^2k^2\\,v_A^2\\,d_i^2\\left(\\omega^2-k^2c_s^2\\right),\\qquad k_\\parallel=k\\cos\\theta .$$"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "def literature_frequencies(k, angle):\n",
    "    \"\"\"Slow, ion-cyclotron and whistler frequency from the dispersion relation of Hameiri et al.\"\"\"\n",
    "    va2, cs2, di2 = (\n",
    "        waves.alfven_speed**2,\n",
    "        waves.sound_speed**2,\n",
    "        waves.ion_inertial_length**2,\n",
    "    )\n",
    "    k2, kp2 = k**2, (k * np.cos(np.radians(angle))) ** 2\n",
    "    cubic = [\n",
    "        1.0,\n",
    "        -(k2 * (va2 + cs2) + kp2 * va2 * (1 + k2 * di2)),\n",
    "        k2 * kp2 * va2 * (va2 + 2 * cs2 + k2 * di2 * cs2),\n",
    "        -k2 * kp2**2 * va2**2 * cs2,\n",
    "    ]\n",
    "    return np.sqrt(np.sort(np.abs(np.roots(cubic).real)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulation\n",
    "\n",
    "The mesh is a periodic box with `points` samples per direction. The solver receives the mesh, the\n",
    "spatial discretisation and the time integrator from outside. It starts from the uniform plasma\n",
    "plus the six waves, each with a magnetic amplitude of $10^{-7}$, and advances it for two Alfvén\n",
    "crossing times of the box. While it runs, `observe` records the complex amplitude of every\n",
    "wave; `oscillation_fit` turns each recorded signal into a frequency."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "def measure_frequencies(spatial, points):\n",
    "    \"\"\"Simulate the six waves on points^3 mesh samples and return their measured frequencies.\"\"\"\n",
    "    axis = np.arange(points) * (2 * np.pi / points)\n",
    "    mesh = TensorCollocationMesh(\n",
    "        axes=(axis, axis, axis),\n",
    "        coordinate_system=\"cartesian\",\n",
    "        periodic=(True, True, True),\n",
    "    )\n",
    "    solver = ResistiveMHD3DSolver(\n",
    "        mesh=mesh,\n",
    "        spatial=spatial,\n",
    "        time_integrator=ClassicalRungeKutta4TimeIntegrator(),\n",
    "        gamma=gamma,\n",
    "        hall_coefficient=hall_coefficient,\n",
    "        resistivity=0.0,\n",
    "        final_time=4 * np.pi,\n",
    "        time_step=0.008,\n",
    "    )\n",
    "    grid = np.meshgrid(*mesh.axes, indexing=\"ij\")\n",
    "    start = sum(\n",
    "        waves.perturbation(k, branch, grid, amplitude=1e-7) for k, branch in modes\n",
    "    )\n",
    "    result = solver.run(\n",
    "        solver.conservative_state(*waves.primitive_state(start)),\n",
    "        observe_interval=0.08,\n",
    "        observe=lambda state: [\n",
    "            waves.amplitude(k, branch, state.magnetic_field, axes=mesh.axes)\n",
    "            for k, branch in modes\n",
    "        ],\n",
    "    )\n",
    "    signals = result.history.values.T\n",
    "    return (\n",
    "        np.array(\n",
    "            [\n",
    "                oscillation_fit(result.history.times, signal).frequency\n",
    "                for signal in signals\n",
    "            ]\n",
    "        ),\n",
    "        result,\n",
    "    )\n",
    "\n",
    "\n",
    "methods = {\n",
    "    \"spectral\": FourierCollocation(),\n",
    "    \"central differences\": CenteredDifferences(),\n",
    "}\n",
    "grid_points = [16, 24, 32]\n",
    "runs = {\n",
    "    (name, n): measure_frequencies(spatial, n)\n",
    "    for name, spatial in methods.items()\n",
    "    for n in grid_points\n",
    "}\n",
    "measured, result = runs[\"spectral\", 32]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Frequencies of the spectral run on $32^3$ points against the library's linear theory and the\n",
    "literature formula."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "print(\n",
    "    \"wave vector   angle  branch          simulation   linear theory   literature   deviation\"\n",
    ")\n",
    "for (k, branch), angle, simulation, theory in zip(modes, angles, measured, exact):\n",
    "    literature = literature_frequencies(3.0, angle)[2 if branch == \"whistler\" else 1]\n",
    "    print(\n",
    "        f\"{str(k):12s} {angle:5.1f}°  {branch:14s} {simulation:10.6f}   {theory:10.6f}   {literature:10.6f}\"\n",
    "        f\"   {simulation / theory - 1:+.1e}\"\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The spectral derivative is exact for every resolved wave, so its error does not depend on the\n",
    "grid. Central differences approach the exact frequencies with second order."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "errors = {\n",
    "    name: [np.max(np.abs(runs[name, n][0] / exact - 1)) for n in grid_points]\n",
    "    for name in (\"central differences\", \"spectral\")\n",
    "}\n",
    "for name, values in errors.items():\n",
    "    print(\n",
    "        f\"{name:20s} largest frequency error on {grid_points} points: \"\n",
    "        + \", \".join(f\"{e:.1e}\" for e in values)\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The magnetic field in a plane across $\\mathbf B_0$, one recorded wave signal against\n",
    "$\\cos\\omega t$, the measured frequencies on the dispersion relation, and the grid study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "fig = plots.figure(1, 4, size=(17, 4.4))\n",
    "\n",
    "plots.heatmap(\n",
    "    result.axes[0],\n",
    "    result.axes[1],\n",
    "    result.magnetic_field[0][:, :, 0] / 1e-7,\n",
    "    colormap=\"diverging\",\n",
    "    label=\"b_x / 10^-7\",\n",
    "    xlabel=\"x\",\n",
    "    ylabel=\"y\",\n",
    "    title=\"Magnetic field b_x at z = 0\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "\n",
    "times, signal = result.history.times, result.history.values[:, 2]\n",
    "smooth = np.linspace(0, times[-1], 600)\n",
    "plots.line(\n",
    "    points={\"simulation\": (times, (signal / signal[0]).real)},\n",
    "    reference={\"cos(omega t)\": (smooth, np.cos(exact[2] * smooth))},\n",
    "    xlabel=\"time\",\n",
    "    ylabel=\"wave amplitude\",\n",
    "    title=\"Whistler wave k = (2, 2, 1)\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "\n",
    "theta = np.linspace(0, 90, 91)\n",
    "theory = np.array([literature_frequencies(3.0, angle) for angle in theta])\n",
    "plots.line(\n",
    "    theta,\n",
    "    {\"ion-cyclotron\": theory[:, 1], \"whistler\": theory[:, 2]},\n",
    "    points={\"simulation\": (angles, measured)},\n",
    "    xlabel=\"angle between k and B_0 [deg]\",\n",
    "    ylabel=\"frequency\",\n",
    "    title=\"Dispersion relation, |k| = 3\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "\n",
    "plots.convergence(\n",
    "    2 * np.pi / np.array(grid_points),\n",
    "    errors,\n",
    "    order=2,\n",
    "    xlabel=\"grid spacing\",\n",
    "    ylabel=\"largest frequency error\",\n",
    "    title=\"Grid study\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Set `hall_coefficient = 0` to recover the ideal Alfvén and magnetosonic waves, raise the\n",
    "amplitude to see nonlinear coupling between the waves, or give the solver a `resistivity`:\n",
    "every wave is then damped at the rate $\\eta k^2/2$, which `oscillation_fit` returns as\n",
    "`growth_rate`."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
