{
 "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": [
    "# Plasmonic waveguide filter\n",
    "\n",
    "Two metal surfaces closer than the wavelength guide a **gap plasmon**: the surface plasmons of both\n",
    "walls couple into one TM mode whose magnetic field $H_z$ is even across the gap. It exists down to\n",
    "gaps of a few nanometres and is the waveguide of plasmonic circuits. A side branch of the same\n",
    "width - a stub closed by the metal at its end - is a resonator: when its depth is about a quarter\n",
    "of the plasmon wavelength, the wave reflected in the stub cancels the transmitted one and the\n",
    "filter stops that band.\n",
    "\n",
    "Silver is a Drude metal with $\\varepsilon_\\infty=3.7$, $\\omega_p=1.3825\\times10^{16}$ rad/s and\n",
    "$\\gamma=2.736\\times10^{13}$ rad/s, the gap is air, 50 nm wide, the stub 250 nm deep. The section\n",
    "solves $H_z$ (polarization `Hz`). The `SectionWaveguidePort` computes the gap plasmon on its port\n",
    "line from the material along it - silver, air, silver - and absorbs it.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| `x_min` | waveguide port, gap plasmon fed with 1 W/m |\n",
    "| `x_max` | waveguide port |\n",
    "| `y_min`, `y_max` (0.35 um into the silver) | 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; X.-S. Lin and X.-G. Huang, *Opt. Lett.* 33,\n",
    "2874 (2008)). With $\\kappa_i=\\sqrt{\\beta^2-\\varepsilon_ik_0^2}$ the gap plasmon of a gap $w$ satisfies\n",
    "\n",
    "$$\\frac{\\kappa_d}{\\varepsilon_d}\\tanh\\frac{\\kappa_dw}{2}+\\frac{\\kappa_m}{\\varepsilon_m}=0 .$$\n",
    "\n",
    "A stub of depth $L$ stops the guide near $\\mathrm{Re}\\,\\beta\\,L\\approx\\pi/2$; the field that leaks\n",
    "around the corners and into the closing metal makes the stub look a little longer, so the\n",
    "quarter-wave estimate is approximate.\n",
    "\n",
    "The STEP parts are drawn in micrometres, the unit that suits a channel of 50 nm; `scaled` brings\n",
    "the 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",
    ")\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",
    "gap, depth = 50e-9, 250e-9\n",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\n",
    "silver = DrudeElectromagneticMaterial(\n",
    "    plasma_frequency=1.3825e16, collision_rate=2.736e13, high_frequency_permittivity=3.7\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the silver block with the channel and the stub; `section` cuts them at half\n",
    "thickness. Quadratic triangles of 6 nm in channel and stub and 40 nm in the silver, graded towards\n",
    "the air, where the field decays within 25 nm; `scaled(..., \"um\")` turns the micrometres of the\n",
    "drawing into metres."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "parts = {\n",
    "    name: load(f\"plasmonic_waveguide_stub_filter{name}.step\").section(\n",
    "        (0, 0, 1), origin=(0, 0, 0.05)\n",
    "    )\n",
    "    for name in (\"\", \"_channel\", \"_stub\")\n",
    "}\n",
    "block = parts[\"\"]\n",
    "sides = block.boundaries\n",
    "mesh = scaled(\n",
    "    TriangularMesher(\n",
    "        target_size=0.04,\n",
    "        embedded_regions=(\n",
    "            parts[\"_channel\"].named(\"channel\"),\n",
    "            parts[\"_stub\"].named(\"stub\"),\n",
    "        ),\n",
    "        region_sizes={\"channel\": 0.006, \"stub\": 0.006},\n",
    "    ).generate(block),\n",
    "    \"um\",\n",
    ")\n",
    "\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.geometry(\n",
    "    block,\n",
    "    selection={\n",
    "        \"ports\": sides.x_min | sides.x_max,\n",
    "        \"outer silver faces\": sides.y_min | sides.y_max,\n",
    "    },\n",
    "    labels=False,\n",
    "    title=\"Silver block with channel and stub (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",
    "Air in channel and stub, silver elsewhere; one model per vacuum wavelength from 1.0 to 2.2 um."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = RegionwiseElectromagneticMaterial(\n",
    "    {\n",
    "        \"channel\": IsotropicElectromagneticMaterial(),\n",
    "        \"stub\": IsotropicElectromagneticMaterial(),\n",
    "    },\n",
    "    default=silver,\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "model = lambda wavelength: FrequencyDomainMaxwell(\n",
    "    domain=block.domain(),\n",
    "    frequency=light / wavelength,\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=\"stub filter\",\n",
    "        geometry=block,\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",
    "wavelengths = 1e-6 * np.concatenate(\n",
    "    (np.linspace(1.0, 1.3, 7), np.linspace(1.33, 1.75, 22), np.linspace(1.8, 2.2, 5))\n",
    ")\n",
    "models = [model(wavelength) for wavelength in wavelengths]\n",
    "results = [solve(physics) for physics in models]\n",
    "scattering = [\n",
    "    scattering_parameters(result, physics) for result, physics in zip(results, models)\n",
    "]\n",
    "transmitted = np.array([abs(s[(1, 0)]) ** 2 for s in scattering])\n",
    "reflected = np.array([abs(s[(0, 0)]) ** 2 for s in scattering])\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",
    "The gap plasmon from the port line against the exact dispersion relation (solved by Newton's\n",
    "method from the single-interface plasmon), and the stop band against the quarter-wave condition."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "wavenumbers = 2 * np.pi / wavelengths\n",
    "metals = np.array(\n",
    "    [silver.relative_permittivity_at(physics.frequency) for physics in models]\n",
    ")\n",
    "relation = (\n",
    "    lambda beta, k0, metal: np.sqrt(beta**2 - k0**2 + 0j)\n",
    "    * np.tanh(np.sqrt(beta**2 - k0**2 + 0j) * gap / 2)\n",
    "    + np.sqrt(beta**2 - metal * k0**2 + 0j) / metal\n",
    ")\n",
    "exact = np.array(\n",
    "    [\n",
    "        newton(relation, 1.3 * k0 * np.sqrt(metal / (metal + 1)), args=(k0, metal))\n",
    "        for k0, metal in zip(wavenumbers, metals)\n",
    "    ]\n",
    ")\n",
    "print(\n",
    "    \"lambda [um]   eps_silver          n_eff computed        n_eff exact          |S21|^2   |S11|^2\"\n",
    ")\n",
    "for i in range(0, len(wavelengths), 3):\n",
    "    print(\n",
    "        f\"{1e6 * wavelengths[i]:9.3f}   {metals[i].real:8.2f}{metals[i].imag:+6.2f}i   {computed[i].real / wavenumbers[i]:.5f}{computed[i].imag / wavenumbers[i]:+.5f}i   \"\n",
    "        f\"{exact[i].real / wavenumbers[i]:.5f}{exact[i].imag / wavenumbers[i]:+.5f}i   {transmitted[i]:.4f}    {reflected[i]:.4f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"\\nlargest deviation of the effective index: {np.max(np.abs(computed - exact) / wavenumbers):.1e}\"\n",
    ")\n",
    "notch = wavelengths[np.argmin(transmitted)]\n",
    "quarter = np.interp(np.pi / 2, (exact.real * depth)[::-1], wavelengths[::-1])\n",
    "print(\n",
    "    f\"stop band: least transmission {transmitted.min():.4f} at {1e6 * notch:.3f} um; quarter-wave estimate Re(beta) L = pi/2 at {1e6 * quarter:.3f} um\"\n",
    ")\n",
    "print(\n",
    "    f\"wavelengths with |S21|^2 < 0.1: {1e6 * wavelengths[transmitted < 0.1].min():.3f} to {1e6 * wavelengths[transmitted < 0.1].max():.3f} um\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Transmission and reflection of the filter, the dispersion of the gap plasmon, and the magnetic\n",
    "field at the stop band and outside it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x, y = np.asarray(mesh.coordinates).T\n",
    "fields = {\n",
    "    f\"{1e6 * wavelengths[i]:.2f} um\": np.abs(\n",
    "        results[i]\n",
    "        .field(models[i].magnetic_flux_density)\n",
    "        .evaluate(np.column_stack((x, y)))[:, 2]\n",
    "    )\n",
    "    for i in (int(np.argmin(transmitted)), 0)\n",
    "}\n",
    "fig = plots.figure(2, 2, size=(18, 11))\n",
    "plots.line(\n",
    "    1e6 * wavelengths,\n",
    "    {\"|S21|^2 (transmitted)\": transmitted, \"|S11|^2 (reflected)\": reflected},\n",
    "    vlines={\"quarter-wave stub\": 1e6 * quarter},\n",
    "    ylimits=(0, 1),\n",
    "    xlabel=\"vacuum wavelength [um]\",\n",
    "    ylabel=\"fraction of the incident power\",\n",
    "    title=\"Stub filter\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    1e6 * wavelengths,\n",
    "    {\"Re(n_eff) computed\": computed.real / wavenumbers},\n",
    "    reference={\"Re(n_eff) computed\": exact.real / wavenumbers},\n",
    "    xlabel=\"vacuum wavelength [um]\",\n",
    "    ylabel=\"effective index\",\n",
    "    title=\"Gap plasmon of the 50 nm channel (dashed: exact)\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "for panel, (name, values) in zip((fig[2], fig[3]), fields.items()):\n",
    "    plots.heatmap(\n",
    "        x,\n",
    "        y,\n",
    "        values / values.max(),\n",
    "        triangles=np.asarray(mesh.cells),\n",
    "        limits=(0, 1),\n",
    "        label=\"|H_z| / max\",\n",
    "        ylimits=(-0.15e-6, 0.35e-6),\n",
    "        title=f\"|H_z| at {name}\",\n",
    "        length_unit=\"um\",\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the stub depth in `plasmonic_waveguide_stub_filter_geometry.py`: the stop band moves in\n",
    "proportion to it. Two stubs a quarter plasmon wavelength apart deepen and widen the band, a stub\n",
    "filled with a dielectric shifts it to longer wavelengths."
   ]
  }
 ]
}
