{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Capacitively coupled helium discharge: particle-in-cell benchmark case 1\n",
    "\n",
    "Two plane electrodes 6.7 cm apart enclose helium at 300 K and about 4 Pa. One electrode is driven\n",
    "with $V(t)=V_0\\sin(2\\pi f t)$, $V_0=450$ V, $f=13.56$ MHz, the other is grounded. Electrons gain\n",
    "energy in the oscillating sheaths in front of the electrodes, ionise the gas and sustain a plasma\n",
    "whose ions stream to the walls. At this low pressure the electron energy distribution is far from\n",
    "Maxwellian, so a fluid model cannot predict the discharge; the standard tool is the\n",
    "**particle-in-cell method with Monte Carlo collisions** (PIC-MCC).\n",
    "\n",
    "OneSimulation follows electrons and He$^+$ ions as macro-particles in one space and three velocity\n",
    "dimensions (1d3v). Each time step it deposits the charge on the grid, solves Poisson's equation\n",
    "\n",
    "$$\\frac{\\mathrm d^2\\phi}{\\mathrm dx^2}=-\\frac{e\\,(n_i-n_e)}{\\varepsilon_0},\\qquad\n",
    "  \\phi(0)=V(t),\\quad \\phi(L)=0,$$\n",
    "\n",
    "moves the particles in the field and lets them collide with the background gas by the null-collision\n",
    "method. The helium cross sections ship with the library:\n",
    "\n",
    "| species | processes |\n",
    "|---|---|\n",
    "| electrons | elastic scattering, two excitation levels (19.82 eV, 20.61 eV), ionisation (24.55 eV) |\n",
    "| He$^+$ ions | isotropic elastic scattering, backscattering (charge exchange) |\n",
    "| electrodes | absorb every particle, no secondary emission |\n",
    "\n",
    "**Reference** (M. M. Turner, A. Derzsi, Z. Donkó, D. Eremin, S. J. Kelly, T. Lafleur and\n",
    "T. Mussenbrock, *Simulation benchmarks for low-pressure plasmas: capacitive discharges*, Phys.\n",
    "Plasmas **20**, 013507, 2013). Five independent PIC codes were run on four cases; for case 1\n",
    "($N=9.64\\times10^{20}$ m$^{-3}$, $V_0=450$ V) the paper publishes the time-averaged ion density\n",
    "profile, the midplane ion density $n_i(L/2)=1.40\\times10^{14}$ m$^{-3}$, the midplane electron\n",
    "temperature $k_BT_e=\\tfrac23\\langle\\varepsilon\\rangle=9.36$ eV, the power absorbed by electrons and\n",
    "ions (34.3 and 90.6 W/m$^2$) and the ion current density at the electrode (0.219 A/m$^2$). The\n",
    "numerical parameters below are those prescribed by the benchmark."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.numerics import PICNumericalConfiguration\n",
    "from onesim.physics.plasma import (\n",
    "    BinomialCollisionCandidates,\n",
    "    CapacitiveDischargePIC,\n",
    "    PICMCCExecution,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Discharge and numerics\n",
    "\n",
    "`CapacitiveDischargePIC.helium` sets up the physical problem with the bundled helium data. The\n",
    "benchmark prescribes 128 cells, 400 time steps per RF period, 512 macro-particles per cell and\n",
    "species at the start, 1280 RF periods to reach the periodic state and an average over the last 32."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "frequency, gap = 13.56e6, 0.067\n",
    "discharge = CapacitiveDischargePIC.helium(\n",
    "    gap=gap,\n",
    "    frequency=frequency,\n",
    "    voltage=450.0,\n",
    "    gas_density=9.64e20,\n",
    "    initial_density=2.56e14,\n",
    ")\n",
    "numerics = PICNumericalConfiguration(\n",
    "    cells=128,\n",
    "    time_step=1 / (400 * frequency),\n",
    "    steps=1280 * 400,\n",
    "    averaging_steps=32 * 400,\n",
    "    particles_per_cell=512,\n",
    "    seed=20130107,\n",
    "    diagnostic_stride=32,\n",
    "    kernel=\"numba\",\n",
    ")\n",
    "execution = PICMCCExecution(\n",
    "    electron_candidate_sampler=BinomialCollisionCandidates(),\n",
    "    ion_candidate_sampler=BinomialCollisionCandidates(),\n",
    ")\n",
    "result = discharge.run(execution=execution, numerics=numerics)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the benchmark\n",
    "\n",
    "The published ion density profile of case 1 is given at 17 positions across the gap (in units of\n",
    "$10^{14}$ m$^{-3}$, read from the paper's figure). The simulated profile is interpolated to the\n",
    "same positions."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "published_position = np.array(\n",
    "    [\n",
    "        0.0,\n",
    "        0.0625,\n",
    "        0.125,\n",
    "        0.1876,\n",
    "        0.25,\n",
    "        0.3124,\n",
    "        0.3748,\n",
    "        0.4373,\n",
    "        0.5002,\n",
    "        0.5627,\n",
    "        0.6252,\n",
    "        0.6876,\n",
    "        0.75,\n",
    "        0.8124,\n",
    "        0.875,\n",
    "        0.9375,\n",
    "        0.9921,\n",
    "    ]\n",
    ")\n",
    "published_density = 1e14 * np.array(\n",
    "    [\n",
    "        0.3615,\n",
    "        0.4033,\n",
    "        0.4578,\n",
    "        0.5276,\n",
    "        0.6219,\n",
    "        0.7661,\n",
    "        1.011,\n",
    "        1.301,\n",
    "        1.4047,\n",
    "        1.3003,\n",
    "        1.011,\n",
    "        0.7668,\n",
    "        0.6226,\n",
    "        0.5282,\n",
    "        0.4578,\n",
    "        0.4027,\n",
    "        0.3648,\n",
    "    ]\n",
    ")\n",
    "simulated = np.interp(published_position, result.coordinates / gap, result.ion_density)\n",
    "published = {\n",
    "    \"midplane ion density [1e14 m^-3]\": (1.40, result.midplane_ion_density / 1e14),\n",
    "    \"midplane electron temperature [eV]\": (9.36, result.midplane_electron_temperature),\n",
    "    \"electron power density [W/m^2]\": (34.3, result.electron_power_density),\n",
    "    \"ion power density [W/m^2]\": (90.6, result.ion_power_density),\n",
    "    \"ion current density [A/m^2]\": (0.219, result.ion_current_density),\n",
    "}\n",
    "print(\"quantity                                published   simulation   deviation\")\n",
    "for name, (reference, value) in published.items():\n",
    "    print(\n",
    "        f\"{name:38s} {reference:10.3f} {value:12.3f} {100 * (value / reference - 1):+10.1f} %\"\n",
    "    )\n",
    "print(\n",
    "    f\"ion density profile: largest deviation {100 * np.abs(simulated - published_density).max() / published_density.max():.1f} % \"\n",
    "    f\"of the peak, rms deviation {100 * np.sqrt(np.mean((simulated - published_density) ** 2)) / published_density.max():.1f} %\"\n",
    ")\n",
    "diagnostics = result.diagnostics\n",
    "print(\n",
    "    f\"resolution: omega_p dt = {diagnostics['omega_p_dt']:.3f}, Debye length / cell = {diagnostics['debye_over_dx']:.2f}, \"\n",
    "    f\"{diagnostics['particles_per_debye_length']:.0f} particles per Debye length, \"\n",
    "    f\"{result.particle_counts['electron']} electrons and {result.particle_counts['ion']} ions at the end\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: the time-averaged electron and ion densities. In the bulk the plasma is quasi-neutral; in the\n",
    "sheaths next to the electrodes the electrons are missing on average, and only the ions remain.\n",
    "Right: the electron energy distribution in the midplane. Compared with a Maxwellian of the same mean\n",
    "energy it holds more slow electrons and a stronger tail far above the excitation threshold: at this\n",
    "low pressure the bulk electrons stay cold while those heated by the oscillating sheaths reach high\n",
    "energies, the typical two-temperature shape of a capacitive discharge."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "temperature = result.midplane_electron_temperature\n",
    "maxwellian = (\n",
    "    2\n",
    "    * np.sqrt(result.energy_bins / np.pi)\n",
    "    * temperature**-1.5\n",
    "    * np.exp(-result.energy_bins / temperature)\n",
    ")\n",
    "fig = plots.figure(1, 2, size=(13, 4.8))\n",
    "plots.line(\n",
    "    100 * result.coordinates,\n",
    "    {\"ions\": result.ion_density, \"electrons\": result.electron_density},\n",
    "    points={\"ions\": (100 * gap * published_position, published_density)},\n",
    "    xlabel=\"position between the electrodes [cm]\",\n",
    "    ylabel=\"time-averaged density [m^-3]\",\n",
    "    title=\"Densities (markers: published ion density)\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    result.energy_bins,\n",
    "    {\"simulation\": result.energy_distribution},\n",
    "    reference={\"Maxwellian, same mean energy\": maxwellian},\n",
    "    vlines={\"first excitation\": 19.82},\n",
    "    scale=\"logy\",\n",
    "    ylimits=(1e-5, 0.2),\n",
    "    xlabel=\"electron energy [eV]\",\n",
    "    ylabel=\"energy distribution [1/eV]\",\n",
    "    title=\"Electron energy distribution\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "The paper defines three more cases at higher pressure (up to 120 Pa) and lower voltage; they need\n",
    "finer cells and smaller time steps and run between 30 and 300 times longer. Set\n",
    "`kernel=\"numpy\"` to run the same model without the compiled kernel, or vary the driving voltage to\n",
    "follow how the midplane density grows with the absorbed power."
   ]
  }
 ]
}
