{
 "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": [
    "# Surface plasmon polariton on a silver-air interface\n",
    "\n",
    "A metal with a negative permittivity $\\varepsilon_m$ next to a dielectric $\\varepsilon_d$ carries a\n",
    "TM surface wave, bound to the interface on both sides. Its magnetic field is along the interface\n",
    "and decays exponentially into both media; its propagation constant follows from the continuity of\n",
    "$H_z$ and of $\\varepsilon^{-1}\\partial H_z/\\partial y$:\n",
    "\n",
    "$$\\beta=k_0\\sqrt{\\frac{\\varepsilon_m\\varepsilon_d}{\\varepsilon_m+\\varepsilon_d}},\\qquad\n",
    "  L_p=\\frac1{2\\,\\mathrm{Im}\\,\\beta}.$$\n",
    "\n",
    "With the Drude model of silver, $\\varepsilon_m=\\varepsilon_\\infty-\\omega_p^2/(\\omega^2+\\mathrm i\\gamma\\omega)$\n",
    "with $\\varepsilon_\\infty=3.7$, $\\omega_p=1.37\\times10^{16}$ rad/s (9.0 eV) and\n",
    "$\\gamma=3.2\\times10^{13}$ rad/s, the plasmon starts on the light line at low frequency and bends\n",
    "over towards the surface plasmon frequency $\\omega_{sp}=\\omega_p/\\sqrt{\\varepsilon_\\infty+\\varepsilon_d}$\n",
    "(4.15 eV), where it slows down and its damping grows.\n",
    "\n",
    "The section solves the out-of-plane magnetic field $H_z$ of `FrequencyDomainMaxwell`. A\n",
    "`SectionWaveguidePort` computes the modes of its port line with the material along it - silver\n",
    "below, air above - and `port_modes` returns the complex propagation constant of the plasmon.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| `x_min` | waveguide port, plasmon fed with 1 W/m |\n",
    "| `x_max` | waveguide port |\n",
    "| `y_min` (0.4 um deep in the silver), `y_max` (3.5 um into the air) | perfect electric conductor |\n",
    "\n",
    "**Reference** (H. Raether, *Surface Plasmons on Smooth and Rough Surfaces and on Gratings*,\n",
    "Springer 1988, §2.1; S. A. Maier, *Plasmonics: Fundamentals and Applications*, Springer 2007,\n",
    "§2.2). The dispersion relation above, with the same Drude permittivity.\n",
    "\n",
    "The STEP parts are drawn in micrometres, the unit that suits a skin of 20 nm; `scaled` brings the\n",
    "mesh to metres, so the model is solved in SI units and the plots show micrometres again."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import VACUUM_PERMEABILITY, VACUUM_PERMITTIVITY\n",
    "from onesim.materials.electromagnetic import (\n",
    "    DrudeElectromagneticMaterial,\n",
    "    IsotropicElectromagneticMaterial,\n",
    "    RegionwiseElectromagneticMaterial,\n",
    "    electronvolts_to_angular_frequency,\n",
    ")\n",
    "from onesim.meshing import TriangularMesher, scaled\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import ComplexSparseDirect\n",
    "from onesim.physics.electromagnetics import (\n",
    "    FrequencyDomainMaxwell,\n",
    "    PerfectElectricConductor,\n",
    "    SectionWaveguidePort,\n",
    "    port_modes,\n",
    "    scattering_parameters,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()\n",
    "\n",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\n",
    "silver = DrudeElectromagneticMaterial(\n",
    "    plasma_frequency=1.37e16, collision_rate=3.2e13, high_frequency_permittivity=3.7\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the section, the deep silver, its top 80 nm (the skin) and 80 nm of air above it;\n",
    "`section` cuts them at half thickness. Quadratic triangles of 10 nm in skin and band and 80 nm\n",
    "elsewhere resolve the plasmon, which decays within 20 nm in the silver and within 50 nm to 0.7 um\n",
    "in the air. `scaled(..., \"um\")` turns the micrometres of the drawing into metres."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "parts = {\n",
    "    name: load(f\"metal_air_surface_plasmon_propagation{name}.step\").section(\n",
    "        (0, 0, 1), origin=(0, 0, 0.05)\n",
    "    )\n",
    "    for name in (\"\", \"_silver\", \"_skin\", \"_band\")\n",
    "}\n",
    "section = parts[\"\"]\n",
    "sides = section.boundaries\n",
    "mesh = scaled(\n",
    "    TriangularMesher(\n",
    "        target_size=0.08,\n",
    "        embedded_regions=tuple(\n",
    "            parts[f\"_{name}\"].named(name) for name in (\"silver\", \"skin\", \"band\")\n",
    "        ),\n",
    "        region_sizes={\"skin\": 0.01, \"band\": 0.01},\n",
    "    ).generate(section),\n",
    "    \"um\",\n",
    ")\n",
    "\n",
    "fig = plots.figure(1, 2, size=(12, 7))\n",
    "plots.geometry(\n",
    "    section,\n",
    "    selection={\"ports\": sides.x_min | sides.x_max, \"walls\": sides.y_min | sides.y_max},\n",
    "    labels=False,\n",
    "    title=\"Silver under air (STEP)\",\n",
    "    length_unit=\"um\",\n",
    "    drawing_unit=\"um\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"{mesh.cell_count} quadratic triangles\",\n",
    "    length_unit=\"um\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "One `FrequencyDomainMaxwell` model per photon energy, polarization `Hz`, silver in its region and\n",
    "air elsewhere. Each port keeps one mode - the plasmon - and the first port feeds it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = RegionwiseElectromagneticMaterial(\n",
    "    {\"silver\": silver, \"skin\": silver}, default=IsotropicElectromagneticMaterial()\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "model = lambda energy: FrequencyDomainMaxwell(\n",
    "    domain=section.domain(),\n",
    "    frequency=electronvolts_to_angular_frequency(energy) / (2 * np.pi),\n",
    "    material=material,\n",
    "    polarization=\"Hz\",\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "solve = lambda physics: Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"silver-air plasmon\",\n",
    "        geometry=section,\n",
    "        physics=(physics,),\n",
    "        boundary_conditions=(\n",
    "            SectionWaveguidePort(\n",
    "                physics=physics, boundary=sides.x_min, modes=1, incident_power=1.0\n",
    "            ),\n",
    "            SectionWaveguidePort(physics=physics, boundary=sides.x_max, modes=1),\n",
    "            PerfectElectricConductor(\n",
    "                physics=physics, boundary=sides.y_min | sides.y_max\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=mesh,\n",
    "    numerics=numerics,\n",
    ").solve_stationary()\n",
    "\n",
    "energies = np.linspace(1.5, 3.9, 13)\n",
    "models = [model(energy) for energy in energies]\n",
    "results = [solve(physics) for physics in models]\n",
    "computed = np.array(\n",
    "    [\n",
    "        port_modes(result, physics)[0][\"propagation_constant\"][0]\n",
    "        for result, physics in zip(results, models)\n",
    "    ]\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "$k_0$ and $\\beta$ are in rad/m; the received power over the 2 um between the ports checks the\n",
    "damping independently of the mode solver."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "wavenumbers = 2 * np.pi * np.array([physics.frequency for physics in models]) / light\n",
    "metals = np.array(\n",
    "    [silver.relative_permittivity_at(physics.frequency) for physics in models]\n",
    ")\n",
    "exact = wavenumbers * np.sqrt(metals / (metals + 1))\n",
    "through = np.array(\n",
    "    [\n",
    "        abs(scattering_parameters(result, physics)[(1, 0)]) ** 2\n",
    "        for result, physics in zip(results, models)\n",
    "    ]\n",
    ")\n",
    "print(\n",
    "    \"energy   eps_silver         n_eff = beta/k0              L_p [um]              |S21|^2 over 2 um\"\n",
    ")\n",
    "print(\n",
    "    \"[eV]                        computed      exact          computed   exact      computed   exp(-2 Im(beta) L)\"\n",
    ")\n",
    "for i, energy in enumerate(energies):\n",
    "    print(\n",
    "        f\"{energy:5.2f}   {metals[i].real:7.2f}{metals[i].imag:+6.3f}i   {computed[i].real / wavenumbers[i]:.6f}   {exact[i].real / wavenumbers[i]:.6f}     \"\n",
    "        f\"{1e6 / (2 * computed[i].imag):8.2f}  {1e6 / (2 * exact[i].imag):8.2f}    {through[i]:.5f}    {np.exp(-2 * exact[i].imag * np.ptp(mesh.coordinates[:, 0])):.5f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"\\nlargest deviation of n_eff: {np.max(np.abs(computed - exact) / wavenumbers):.1e}; \"\n",
    "    f\"largest relative deviation of L_p: {np.max(np.abs(computed.imag / exact.imag - 1)):.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"surface plasmon frequency omega_p / sqrt(eps_inf + 1) = {1.37e16 / np.sqrt(4.7) / electronvolts_to_angular_frequency(1.0):.2f} eV\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The dispersion of the plasmon against the light line, its propagation length, and the\n",
    "instantaneous magnetic field of the plasmon fed at 3 eV near the surface."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "at = int(np.argmin(np.abs(energies - 3.0)))\n",
    "x, y = np.asarray(mesh.coordinates).T\n",
    "field = (\n",
    "    results[at]\n",
    "    .field(models[at].magnetic_flux_density)\n",
    "    .evaluate(np.column_stack((x, y)))[:, 2]\n",
    ")\n",
    "fig = plots.figure(1, 3, size=(24, 6.5))\n",
    "plots.line(\n",
    "    y={\n",
    "        \"plasmon\": (1e-6 * computed.real, energies),\n",
    "        \"light line\": (1e-6 * wavenumbers, energies),\n",
    "    },\n",
    "    reference={\"plasmon\": (1e-6 * exact.real, energies)},\n",
    "    hlines={\n",
    "        \"surface plasmon frequency\": 1.37e16\n",
    "        / np.sqrt(4.7)\n",
    "        / electronvolts_to_angular_frequency(1.0)\n",
    "    },\n",
    "    xlabel=\"Re(beta) [rad/um]\",\n",
    "    ylabel=\"photon energy [eV]\",\n",
    "    title=\"Dispersion (dashed: exact)\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    energies,\n",
    "    {\"propagation length\": 1e6 / (2 * computed.imag)},\n",
    "    reference={\"propagation length\": 1e6 / (2 * exact.imag)},\n",
    "    scale=\"logy\",\n",
    "    xlabel=\"photon energy [eV]\",\n",
    "    ylabel=\"L_p [um]\",\n",
    "    title=\"Propagation length (dashed: exact)\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.heatmap(\n",
    "    x,\n",
    "    y,\n",
    "    (field / np.abs(field).max()).real,\n",
    "    triangles=np.asarray(mesh.cells),\n",
    "    colormap=\"diverging\",\n",
    "    centre=0.0,\n",
    "    limits=(-1, 1),\n",
    "    label=\"Re(H_z) / max |H_z|\",\n",
    "    aspect=\"auto\",\n",
    "    ylimits=(-0.15e-6, 0.35e-6),\n",
    "    length_unit=\"um\",\n",
    "    title=f\"Plasmon at {energies[at]:.1f} eV\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Replace the air by glass ($\\varepsilon_d=2.25$): the surface plasmon frequency drops to\n",
    "3.4 eV and the plasmon is confined more tightly. A second interface below a thin film couples two\n",
    "plasmons into a long-range and a short-range mode."
   ]
  }
 ]
}
