{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plasma oscillation in a particle-in-cell simulation\n",
    "\n",
    "A uniform electron plasma of density $n_0$ sits in a neutralising background of immobile ions.\n",
    "If the electrons are displaced by a small sinusoidal amount, the space charge pulls them back\n",
    "and the plasma oscillates. The simulation follows the electrons as macro-particles on a periodic\n",
    "grid, so the oscillation comes from the self-consistent electric field.\n",
    "\n",
    "**Reference.** A cold plasma oscillates at the plasma frequency; a warm one with the thermal\n",
    "speed $v_{th}=\\sqrt{k_BT_e/m_e}$ follows the Bohm-Gross relation:\n",
    "\n",
    "$$\\omega_p=\\sqrt{\\frac{n_0 e^2}{\\varepsilon_0 m_e}},\\qquad\n",
    "  \\omega^2=\\omega_p^2+3k^2v_{th}^2=\\omega_p^2\\big(1+3\\,k^2\\lambda_D^2\\big) .$$"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from onesim.physics.plasma import PeriodicParticleInCell, PICSpecies\n",
    "from onesim.results import oscillation_fit\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.constants import e, epsilon_0, m_e\n",
    "from scipy.special import erfinv\n",
    "\n",
    "theme.set()\n",
    "\n",
    "density, length, cells, particles = 1.0e16, 5.0e-3, 64, 64 * 400\n",
    "plasma_frequency = np.sqrt(density * e**2 / (epsilon_0 * m_e))\n",
    "k = 2 * np.pi / length\n",
    "thermal_speed = lambda temperature: np.sqrt(e * temperature / m_e)\n",
    "bohm_gross = lambda temperature: np.sqrt(\n",
    "    plasma_frequency**2 + 3 * k**2 * thermal_speed(temperature) ** 2\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulation\n",
    "\n",
    "The electrons start as a travelling wave of displacement $0.01\\,L\\,\\sin kx$, with a Maxwellian\n",
    "velocity spread for the warm cases. Every five time steps the Fourier amplitude of the electric\n",
    "field at the wavenumber $k$ is recorded; it rotates at the oscillation frequency."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "plasma = PeriodicParticleInCell(\n",
    "    lengths=(length,), cells=(cells,), background_charge_density=e * density\n",
    ")\n",
    "grid = np.arange(cells) * length / cells\n",
    "start = (np.arange(particles) + 0.5) * length / particles\n",
    "time_step = 1 / (50 * plasma_frequency)\n",
    "\n",
    "\n",
    "def simulate(temperature):\n",
    "    \"\"\"Field amplitude and total energy over six oscillation periods for an electron temperature in eV.\"\"\"\n",
    "    velocities = np.zeros((particles, 3))\n",
    "    velocities[:, 0] = -0.01 * length * bohm_gross(temperature) * np.cos(k * start)\n",
    "    maxwellian = (\n",
    "        np.sqrt(2)\n",
    "        * thermal_speed(temperature)\n",
    "        * erfinv(2 * (np.arange(particles) + 0.5) / particles - 1)\n",
    "    )\n",
    "    velocities[:, 0] += np.random.default_rng(7).permutation(maxwellian)\n",
    "    electrons = PICSpecies(\n",
    "        positions=(start + 0.01 * length * np.sin(k * start))[:, None],\n",
    "        velocities=velocities,\n",
    "        mass=m_e,\n",
    "        charge=-e,\n",
    "        weights=density * length / particles,\n",
    "    )\n",
    "    times, amplitude, energy = [], [], []\n",
    "    for sample in range(int(6 * 2 * np.pi / bohm_gross(temperature) / (5 * time_step))):\n",
    "        result = plasma.solve(species=(electrons,), time_step=time_step, steps=5)\n",
    "        electrons = result.species[0]\n",
    "        times.append(5 * time_step * (sample + 1))\n",
    "        amplitude.append(np.sum(result.electric_field[:, 0] * np.exp(-1j * k * grid)))\n",
    "        energy.append(result.kinetic_energy[-1] + result.field_energy[-1])\n",
    "    return np.array(times), np.array(amplitude), np.array(energy)\n",
    "\n",
    "\n",
    "runs = {temperature: simulate(temperature) for temperature in (0.0, 1.0, 3.0)}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "`oscillation_fit` reads the frequency off the rotating field amplitude."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "measured = {\n",
    "    temperature: abs(oscillation_fit(times, amplitude).frequency)\n",
    "    for temperature, (times, amplitude, _) in runs.items()\n",
    "}\n",
    "print(\n",
    "    \"T_e [eV]   measured ω/ω_p   Bohm-Gross   deviation   largest change of the total energy\"\n",
    ")\n",
    "for temperature, (times, amplitude, energy) in runs.items():\n",
    "    print(\n",
    "        f\"{temperature:8.0f} {measured[temperature] / plasma_frequency:16.4f} {bohm_gross(temperature) / plasma_frequency:12.4f}\"\n",
    "        f\" {100 * (measured[temperature] / bohm_gross(temperature) - 1):+10.2f} % {np.abs(energy / energy[0] - 1).max():14.1e}\"\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The field amplitude over the first periods against a cosine at the Bohm-Gross frequency, and\n",
    "the measured frequencies on the dispersion relation."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "debye = lambda temperature: np.sqrt(epsilon_0 * e * temperature / (density * e**2))\n",
    "labels = {temperature: f\"T_e = {temperature:.0f} eV\" for temperature in runs}\n",
    "fine = np.linspace(0, 2.5 * 2 * np.pi / plasma_frequency, 600)\n",
    "kd = np.linspace(0, 0.2, 100)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 4.8))\n",
    "plots.line(\n",
    "    points={\n",
    "        labels[T]: (1e9 * times, (amplitude / amplitude[0]).real)\n",
    "        for T, (times, amplitude, _) in runs.items()\n",
    "    },\n",
    "    reference={\n",
    "        labels[T]: (1e9 * fine, np.cos(bohm_gross(T) * (fine - times[0])))\n",
    "        for T, (times, _, _) in runs.items()\n",
    "    },\n",
    "    xlimits=(0, 1e9 * fine[-1]),\n",
    "    xlabel=\"time [ns]\",\n",
    "    ylabel=\"field amplitude / initial amplitude\",\n",
    "    title=\"Simulation (markers) and Bohm-Gross frequency (dashed)\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    kd,\n",
    "    {\"Bohm-Gross\": np.sqrt(1 + 3 * kd**2)},\n",
    "    points={\n",
    "        \"simulation\": (\n",
    "            [k * debye(T) for T in runs],\n",
    "            [measured[T] / plasma_frequency for T in runs],\n",
    "        )\n",
    "    },\n",
    "    hlines={\"cold plasma\": 1.0},\n",
    "    xlabel=\"k λ_D\",\n",
    "    ylabel=\"ω / ω_p\",\n",
    "    title=\"Dispersion relation\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the temperature until $k\\lambda_D$ exceeds 0.3 and Landau damping makes the oscillation\n",
    "decay; `oscillation_fit` returns the damping as `growth_rate`. Two counter-streaming electron\n",
    "beams turn the oscillation into the two-stream instability."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
