{
 "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 plasmons of a thin silver film in glass\n",
    "\n",
    "On a single metal-dielectric interface a surface plasmon polariton is bound with the propagation\n",
    "constant $\\beta=k_0\\sqrt{\\varepsilon_m\\varepsilon_d/(\\varepsilon_m+\\varepsilon_d)}$. A film of\n",
    "thickness $t$ has two interfaces; when $t$ is comparable with the decay length in the metal\n",
    "($\\approx 25$ nm) the two plasmons couple into a mode of even and a mode of odd magnetic field\n",
    "$H_z(y)$. One of them keeps most of its field in the glass: it is the **long-range** plasmon, which\n",
    "travels hundreds of micrometres in the near infrared. The other concentrates its field in the\n",
    "metal: the **short-range** plasmon, with a larger index and much stronger damping.\n",
    "\n",
    "Silver is described by the Drude-Lorentz model of Rakić et al. (free electrons with plasma energy\n",
    "$\\hbar\\omega_p=9.01$ eV, oscillator strength $f_0=0.845$, damping $\\hbar\\Gamma_0=0.048$ eV, and\n",
    "five interband oscillators), the glass by $\\varepsilon_d=2.25$:\n",
    "\n",
    "$$\\varepsilon_m(\\omega)=1-\\frac{f_0\\omega_p^2}{\\omega(\\omega+\\mathrm i\\Gamma_0)}\n",
    "  +\\sum_{j=1}^5\\frac{f_j\\omega_p^2}{\\omega_j^2-\\omega^2-\\mathrm i\\omega\\Gamma_j}.$$\n",
    "\n",
    "The plasmons are TM waves; the section solves the out-of-plane magnetic field $H_z$ with\n",
    "`FrequencyDomainMaxwell`. A `SectionWaveguidePort` computes the modes of its port line with the\n",
    "material along it - glass, silver, glass - and absorbs them; `port_modes` returns their complex\n",
    "propagation constants $\\beta$, and the propagation length is $L_p=1/(2\\,\\mathrm{Im}\\,\\beta)$.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| `x_min` | waveguide port, two modes, one of them fed with 1 W/m |\n",
    "| `x_max` | waveguide port, two modes |\n",
    "| `y_min`, `y_max` (3 um from the film) | perfect electric conductor |\n",
    "\n",
    "**Reference** (E. N. Economou, *Phys. Rev.* 182, 539 (1969); S. A. Maier, *Plasmonics:\n",
    "Fundamentals and Applications*, Springer 2007, §2.3; A. D. Rakić et al., *Appl. Opt.* 37, 5271\n",
    "(1998)). With $\\kappa_i=\\sqrt{\\beta^2-\\varepsilon_ik_0^2}$ the bound TM modes of the film satisfy\n",
    "\n",
    "$$\\frac{\\kappa_m}{\\varepsilon_m}\\tanh\\frac{\\kappa_mt}{2}+\\frac{\\kappa_d}{\\varepsilon_d}=0\\quad\n",
    "  \\text{(even }H_z),\\qquad\n",
    "  \\frac{\\kappa_m}{\\varepsilon_m}\\coth\\frac{\\kappa_mt}{2}+\\frac{\\kappa_d}{\\varepsilon_d}=0\\quad\n",
    "  \\text{(odd }H_z),$$\n",
    "\n",
    "solved here for complex $\\beta$ at each photon energy with the same permittivity.\n",
    "\n",
    "The STEP parts are drawn in micrometres, the unit that suits a film of 40 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",
    "    DrudeLorentzElectromagneticMaterial,\n",
    "    IsotropicElectromagneticMaterial,\n",
    "    LorentzOscillator,\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",
    "from scipy.optimize import newton\n",
    "\n",
    "theme.set()\n",
    "\n",
    "glass, thickness = 2.25, 40e-9\n",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\n",
    "plasma, oscillators = 9.01, [\n",
    "    (0.065, 3.886, 0.816),\n",
    "    (0.124, 0.452, 4.481),\n",
    "    (0.011, 0.065, 8.185),\n",
    "    (0.840, 0.916, 9.083),\n",
    "    (5.646, 2.419, 20.29),\n",
    "]\n",
    "silver = DrudeLorentzElectromagneticMaterial(\n",
    "    plasma_frequency=electronvolts_to_angular_frequency(np.sqrt(0.845) * plasma),\n",
    "    collision_rate=electronvolts_to_angular_frequency(0.048),\n",
    "    oscillators=tuple(\n",
    "        LorentzOscillator(\n",
    "            strength=f * plasma**2 / w**2,\n",
    "            resonance_frequency=electronvolts_to_angular_frequency(w),\n",
    "            damping=electronvolts_to_angular_frequency(g),\n",
    "        )\n",
    "        for f, g, w in oscillators\n",
    "    ),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the glass strip, the film and a thin band around the film; `section` cuts them at\n",
    "half thickness. Quadratic triangles of 8 nm in the film, 12 nm in the band and 60 nm in the rest\n",
    "of the glass follow the field of both plasmons, which decays within 20 to 700 nm from the film;\n",
    "`scaled(..., \"um\")` turns the micrometres of the drawing into metres."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "parts = {\n",
    "    name: load(f\"thin_film_surface_plasmon_dispersion{name}.step\")\n",
    "    for name in (\"\", \"_band\", \"_film\")\n",
    "}\n",
    "strip = parts[\"\"].section((0, 0, 1), origin=(0, 0, 0.05))\n",
    "band = parts[\"_band\"].section((0, 0, 1), origin=(0, 0, 0.05)).named(\"band\")\n",
    "film = parts[\"_film\"].section((0, 0, 1), origin=(0, 0, 0.05)).named(\"film\")\n",
    "sides = strip.boundaries\n",
    "mesh = scaled(\n",
    "    TriangularMesher(\n",
    "        target_size=0.06,\n",
    "        embedded_regions=(band, film),\n",
    "        region_sizes={\"band\": 0.012, \"film\": 0.008},\n",
    "    ).generate(strip),\n",
    "    \"um\",\n",
    ")\n",
    "\n",
    "fig = plots.figure(1, 2, size=(10, 8))\n",
    "plots.geometry(\n",
    "    strip,\n",
    "    selection={\"ports\": sides.x_min | sides.x_max, \"walls\": sides.y_min | sides.y_max},\n",
    "    labels=False,\n",
    "    title=\"Glass strip with the silver film (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 solves $H_z$ (polarization `Hz`) with the\n",
    "silver in the film and glass elsewhere. Each port keeps two modes - the two plasmons, whose\n",
    "indices exceed that of the glass - and the first port feeds one of them."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = RegionwiseElectromagneticMaterial(\n",
    "    {\"film\": silver},\n",
    "    default=IsotropicElectromagneticMaterial(relative_permittivity=glass),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "model = lambda energy: FrequencyDomainMaxwell(\n",
    "    domain=strip.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, mode=0: Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"silver film\",\n",
    "        geometry=strip,\n",
    "        physics=(physics,),\n",
    "        boundary_conditions=(\n",
    "            SectionWaveguidePort(\n",
    "                physics=physics,\n",
    "                boundary=sides.x_min,\n",
    "                modes=2,\n",
    "                incident_mode=mode,\n",
    "                incident_power=1.0,\n",
    "            ),\n",
    "            SectionWaveguidePort(physics=physics, boundary=sides.x_max, modes=2),\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.2, 3.2, 21)\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\"]\n",
    "        for result, physics in zip(results, models)\n",
    "    ]\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The exact constants come from the two dispersion relations, solved by Newton's method from the\n",
    "single-interface plasmon. $k_0$ and $\\beta$ are in rad/m, propagation lengths printed in um."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "relation = lambda beta, k0, metal, even: (\n",
    "    np.sqrt(beta**2 - metal * k0**2 + 0j)\n",
    "    / metal\n",
    "    * np.tanh(np.sqrt(beta**2 - metal * k0**2 + 0j) * thickness / 2)\n",
    "    ** (1 if even else -1)\n",
    "    + np.sqrt(beta**2 - glass * k0**2 + 0j) / glass\n",
    ")\n",
    "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 = np.array(\n",
    "    [\n",
    "        [\n",
    "            newton(\n",
    "                relation,\n",
    "                k0 * np.sqrt(metal * glass / (metal + glass)),\n",
    "                args=(k0, metal, even),\n",
    "            )\n",
    "            for even in (True, False)\n",
    "        ]\n",
    "        for k0, metal in zip(wavenumbers, metals)\n",
    "    ]\n",
    ")\n",
    "order = np.argsort(-exact.real, axis=1)\n",
    "exact = np.take_along_axis(exact, order, axis=1)\n",
    "length = {\n",
    "    \"long-range\": 1e6 / (2 * computed[:, 1].imag),\n",
    "    \"short-range\": 1e6 / (2 * computed[:, 0].imag),\n",
    "}\n",
    "print(\n",
    "    \"energy   eps_silver        n_eff long-range         n_eff short-range        L_p long-range [um]   L_p short-range [um]\"\n",
    ")\n",
    "print(\n",
    "    \"[eV]                       computed     exact       computed     exact        computed   exact      computed  exact\"\n",
    ")\n",
    "for i in range(0, len(energies), 2):\n",
    "    n, m = computed[i] / wavenumbers[i], exact[i] / wavenumbers[i]\n",
    "    print(\n",
    "        f\"{energies[i]:5.2f}   {metals[i].real:7.2f}{metals[i].imag:+6.2f}i   {n[1].real:.5f}  {m[1].real:.5f}     {n[0].real:.5f}  {m[0].real:.5f}     \"\n",
    "        f\"{length['long-range'][i]:8.2f}  {1e6 / (2 * exact[i, 1].imag):8.2f}    {length['short-range'][i]:7.3f}  {1e6 / (2 * exact[i, 0].imag):7.3f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"\\nlargest deviation of n_eff: long-range {np.max(np.abs((computed[:, 1] - exact[:, 1]) / wavenumbers)):.1e}, \"\n",
    "    f\"short-range {np.max(np.abs((computed[:, 0] - exact[:, 0]) / wavenumbers)):.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"largest relative deviation of L_p: long-range {np.max(np.abs(computed[:, 1].imag / exact[:, 1].imag - 1)):.1e}, \"\n",
    "    f\"short-range {np.max(np.abs(computed[:, 0].imag / exact[:, 0].imag - 1)):.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The driven strip is an independent check of the damping: the first mode of the ports, the\n",
    "short-range plasmon with the larger index, is fed at one port; the power received at the other,\n",
    "1 um away, is $e^{-2\\,\\mathrm{Im}\\,\\beta\\,L}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "through = np.array(\n",
    "    [\n",
    "        abs(scattering_parameters(result, physics)[(1, 0)]) ** 2\n",
    "        for result, physics in zip(results, models)\n",
    "    ]\n",
    ")\n",
    "expected = np.exp(-2 * exact[:, 0].imag * np.ptp(mesh.coordinates[:, 0]))\n",
    "print(\"\\nenergy [eV]   |S21|^2 computed   exp(-2 Im(beta) L)\")\n",
    "for i in range(0, len(energies), 4):\n",
    "    print(f\"{energies[i]:8.2f}      {through[i]:.6f}           {expected[i]:.6f}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The dispersion of both plasmons against the light line of the glass, their propagation lengths\n",
    "on a logarithmic scale, and the magnetic field across the film of both modes at 2 eV, fed one\n",
    "after the other."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "profile = np.linspace(-0.6e-6, 0.6e-6, 601)\n",
    "at = int(np.argmin(np.abs(energies - 2.0)))\n",
    "fields = {\n",
    "    name: np.abs(\n",
    "        solve(models[at], mode)\n",
    "        .field(models[at].magnetic_flux_density)\n",
    "        .evaluate(np.column_stack((0.5e-6 + 0 * profile, profile)))[:, 2]\n",
    "    )\n",
    "    for mode, name in enumerate((\"short-range\", \"long-range\"))\n",
    "}\n",
    "fig = plots.figure(1, 3, size=(24, 6.5))\n",
    "plots.line(\n",
    "    y={\n",
    "        \"long-range\": (1e-6 * computed[:, 1].real, energies),\n",
    "        \"short-range\": (1e-6 * computed[:, 0].real, energies),\n",
    "        \"light line of the glass\": (1e-6 * np.sqrt(glass) * wavenumbers, energies),\n",
    "    },\n",
    "    reference={\n",
    "        \"long-range\": (1e-6 * exact[:, 1].real, energies),\n",
    "        \"short-range\": (1e-6 * exact[:, 0].real, energies),\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",
    "    length,\n",
    "    reference={\n",
    "        \"long-range\": 1e6 / (2 * exact[:, 1].imag),\n",
    "        \"short-range\": 1e6 / (2 * exact[:, 0].imag),\n",
    "    },\n",
    "    scale=\"logy\",\n",
    "    xlabel=\"photon energy [eV]\",\n",
    "    ylabel=\"propagation length [um]\",\n",
    "    title=\"Propagation length (dashed: exact)\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    1e9 * profile,\n",
    "    {name: values / values.max() for name, values in fields.items()},\n",
    "    xlabel=\"y [nm]\",\n",
    "    ylabel=\"|H_z| / max\",\n",
    "    title=\"Field across the film (|y| < 20 nm) at 2 eV\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the film thinner in `thin_film_surface_plasmon_dispersion_geometry.py`: the long-range\n",
    "plasmon spreads further into the glass and its propagation length grows, while the short-range\n",
    "plasmon slows down and is damped more strongly. Glass of different index on the two sides\n",
    "breaks the symmetry and cuts the long-range plasmon off below a critical thickness."
   ]
  }
 ]
}
