{
 "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 excitation in the Otto and Kretschmann configurations\n",
    "\n",
    "A surface plasmon on a gold-air interface has a larger wavenumber than light in air,\n",
    "$\\mathrm{Re}\\,\\beta>k_0$, so a plane wave from the air cannot excite it. In glass of index\n",
    "$n_p=1.515$ the tangential wavenumber $k_x=n_pk_0\\sin\\theta$ can reach $\\beta$ beyond the critical\n",
    "angle; the totally reflected wave is then evanescent on the other side and couples into the\n",
    "plasmon by tunnelling:\n",
    "\n",
    "* **Kretschmann**: a gold film of 50 nm on the prism; the plasmon on its far side (gold-air) is\n",
    "  excited through the metal,\n",
    "* **Otto**: an air gap of 450 nm between the prism and a gold block; the plasmon on the gold\n",
    "  surface is excited across the gap.\n",
    "\n",
    "At the coupling angle $n_p\\sin\\theta\\approx\\mathrm{Re}\\sqrt{\\varepsilon_m/(\\varepsilon_m+1)}$ the\n",
    "reflected p-polarized (TM) power drops sharply; s-polarized (TE) light has no surface plasmon and\n",
    "stays totally reflected. Gold is the Drude-Lorentz model of Rakić et al. ($\\hbar\\omega_p=9.03$ eV,\n",
    "$f_0=0.760$, $\\hbar\\Gamma_0=0.053$ eV and five interband oscillators), $\\varepsilon_m=-9.81+1.96\\mathrm i$\n",
    "at 633 nm.\n",
    "\n",
    "The layers are infinite, so one period of 0.15 um (much less than half a wavelength in glass)\n",
    "suffices: Bloch-periodic sides carry $k_x$ and only the specular order propagates. The section\n",
    "solves $H_z$ for p and $E_z$ for s polarization.\n",
    "\n",
    "| boundary | Kretschmann | Otto |\n",
    "|---|---|---|\n",
    "| `x_min`, `x_max` | Bloch periodic, $k_x=n_pk_0\\sin\\theta$ | Bloch periodic |\n",
    "| `y_max` (glass) | Floquet port, incident wave | Floquet port, incident wave |\n",
    "| `y_min` | Floquet port in air | perfect conductor 0.3 um deep in the gold |\n",
    "\n",
    "**Reference** (E. Kretschmann and H. Raether, *Z. Naturforsch.* 23a, 2135 (1968); A. Otto,\n",
    "*Z. Phys.* 216, 398 (1968); M. Born and E. Wolf, *Principles of Optics*, 7th ed., §1.6.4;\n",
    "A. D. Rakić et al., *Appl. Opt.* 37, 5271 (1998)). For three media with\n",
    "$k_{z,i}=\\sqrt{\\varepsilon_ik_0^2-k_x^2}$ and the middle layer of thickness $d$,\n",
    "\n",
    "$$R=\\left|\\frac{r_{12}+r_{23}e^{2\\mathrm ik_{z,2}d}}{1+r_{12}r_{23}e^{2\\mathrm ik_{z,2}d}}\\right|^2,\\qquad\n",
    "  r_{ij}^{(p)}=\\frac{\\varepsilon_jk_{z,i}-\\varepsilon_ik_{z,j}}{\\varepsilon_jk_{z,i}+\\varepsilon_ik_{z,j}},\\quad\n",
    "  r_{ij}^{(s)}=\\frac{k_{z,i}-k_{z,j}}{k_{z,i}+k_{z,j}}.$$\n",
    "\n",
    "The STEP parts are drawn in micrometres, the unit that suits a film of 50 nm; `scaled` brings the\n",
    "meshes 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 PeriodicPair, 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",
    "    BlochPeriodicBoundary,\n",
    "    FloquetPort,\n",
    "    FrequencyDomainMaxwell,\n",
    "    PerfectElectricConductor,\n",
    "    diffraction_efficiencies,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()\n",
    "\n",
    "wavelength, prism = 633e-9, 1.515\n",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\n",
    "frequency, k0 = light / wavelength, 2 * np.pi / wavelength\n",
    "plasma, oscillators = 9.03, [\n",
    "    (0.024, 0.241, 0.415),\n",
    "    (0.010, 0.345, 0.830),\n",
    "    (0.071, 0.870, 2.969),\n",
    "    (0.601, 2.494, 4.304),\n",
    "    (4.384, 2.214, 13.32),\n",
    "]\n",
    "gold = DrudeLorentzElectromagneticMaterial(\n",
    "    plasma_frequency=electronvolts_to_angular_frequency(np.sqrt(0.760) * plasma),\n",
    "    collision_rate=electronvolts_to_angular_frequency(0.053),\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 both cells with their glass and gold; `section` cuts them at half thickness. The\n",
    "periodic sides are meshed alike (`periodic_pairs`); quadratic triangles of 20 nm, and 8 nm in the\n",
    "gold, where the field decays within 25 nm; `scaled(..., \"um\")` turns the micrometres of the drawing\n",
    "into metres."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "configurations = (\"kretschmann\", \"otto\")\n",
    "cells, meshes = {}, {}\n",
    "for name in configurations:\n",
    "    parts = {\n",
    "        part: load(f\"surface_plasmon_prism_coupling_{name}{part}.step\").section(\n",
    "            (0, 0, 1), origin=(0, 0, 0.05)\n",
    "        )\n",
    "        for part in (\"\", \"_glass\", \"_gold\")\n",
    "    }\n",
    "    cells[name] = parts[\"\"]\n",
    "    meshes[name] = scaled(\n",
    "        TriangularMesher(\n",
    "            target_size=0.02,\n",
    "            embedded_regions=(\n",
    "                parts[\"_glass\"].named(\"glass\"),\n",
    "                parts[\"_gold\"].named(\"gold\"),\n",
    "            ),\n",
    "            region_sizes={\"gold\": 0.008},\n",
    "            periodic_pairs=(\n",
    "                PeriodicPair(parts[\"\"].boundaries.x_min, parts[\"\"].boundaries.x_max),\n",
    "            ),\n",
    "        ).generate(parts[\"\"]),\n",
    "        \"um\",\n",
    "    )\n",
    "\n",
    "fig = plots.figure(1, 4, size=(16, 9))\n",
    "for index, name in enumerate(configurations):\n",
    "    sides = cells[name].boundaries\n",
    "    plots.geometry(\n",
    "        cells[name],\n",
    "        selection={\n",
    "            \"periodic sides\": sides.x_min | sides.x_max,\n",
    "            \"port in the glass\": sides.y_max,\n",
    "            \"port in air\" if name == \"kretschmann\" else \"conductor\": sides.y_min,\n",
    "        },\n",
    "        labels=False,\n",
    "        title=f\"{name.capitalize()} cell (STEP)\",\n",
    "        length_unit=\"um\",\n",
    "        drawing_unit=\"um\",\n",
    "        ax=fig[2 * index],\n",
    "    )\n",
    "    plots.mesh(\n",
    "        meshes[name],\n",
    "        groups=(\"all\",),\n",
    "        legend=False,\n",
    "        title=f\"{meshes[name].cell_count} triangles\",\n",
    "        length_unit=\"um\",\n",
    "        ax=fig[2 * index + 1],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "For every angle the Bloch wavevector of the side pair is $n_pk_0\\sin\\theta$ and the port in the\n",
    "glass feeds the plane wave; `diffraction_efficiencies` returns the reflected power at that port\n",
    "relative to the incident power."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = RegionwiseElectromagneticMaterial(\n",
    "    {\n",
    "        \"glass\": IsotropicElectromagneticMaterial(relative_permittivity=prism**2),\n",
    "        \"gold\": gold,\n",
    "    },\n",
    "    default=IsotropicElectromagneticMaterial(),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "models = {\n",
    "    (name, polarization): FrequencyDomainMaxwell(\n",
    "        domain=cells[name].domain(),\n",
    "        frequency=frequency,\n",
    "        material=material,\n",
    "        polarization=polarization,\n",
    "        phasor_convention=\"exp(-i*omega*t)\",\n",
    "        amplitude_convention=\"peak\",\n",
    "    )\n",
    "    for name in configurations\n",
    "    for polarization in (\"Hz\", \"Ez\")\n",
    "}\n",
    "reflect = lambda name, polarization, angle: diffraction_efficiencies(\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=name,\n",
    "            geometry=cells[name],\n",
    "            physics=(models[(name, polarization)],),\n",
    "            boundary_conditions=(\n",
    "                BlochPeriodicBoundary(\n",
    "                    physics=models[(name, polarization)],\n",
    "                    pair=PeriodicPair(\n",
    "                        cells[name].boundaries.x_min, cells[name].boundaries.x_max\n",
    "                    ),\n",
    "                    wavevector=(prism * k0 * np.sin(np.radians(angle)), 0.0, 0.0),\n",
    "                ),\n",
    "                FloquetPort(\n",
    "                    physics=models[(name, polarization)],\n",
    "                    boundary=cells[name].boundaries.y_max,\n",
    "                    incident_amplitude=1.0,\n",
    "                ),\n",
    "                (\n",
    "                    FloquetPort(\n",
    "                        physics=models[(name, polarization)],\n",
    "                        boundary=cells[name].boundaries.y_min,\n",
    "                    )\n",
    "                    if name == \"kretschmann\"\n",
    "                    else PerfectElectricConductor(\n",
    "                        physics=models[(name, polarization)],\n",
    "                        boundary=cells[name].boundaries.y_min,\n",
    "                    )\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=meshes[name],\n",
    "        numerics=numerics,\n",
    "    ).solve_stationary(),\n",
    "    models[(name, polarization)],\n",
    ")[(0, 0)]\n",
    "\n",
    "angles = np.concatenate(\n",
    "    (\n",
    "        np.arange(36.0, 41.0, 1.0),\n",
    "        np.arange(41.0, 48.01, 0.25),\n",
    "        np.arange(49.0, 70.1, 1.5),\n",
    "    )\n",
    ")\n",
    "computed = {\n",
    "    (name, polarization): np.array(\n",
    "        [reflect(name, polarization, angle) for angle in angles]\n",
    "    )\n",
    "    for name in configurations\n",
    "    for polarization in (\"Hz\", \"Ez\")\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The exact reflectance of the three media, with the gold permittivity of the same model."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def multilayer(angle, layers, thickness, polarization):\n",
    "    kx = prism * k0 * np.sin(np.radians(angle))\n",
    "    kz = [np.sqrt(e * k0**2 - kx**2 + 0j) for e in layers]\n",
    "    r = [\n",
    "        (\n",
    "            (\n",
    "                (layers[j] * kz[i] - layers[i] * kz[j])\n",
    "                / (layers[j] * kz[i] + layers[i] * kz[j])\n",
    "            )\n",
    "            if polarization == \"Hz\"\n",
    "            else (kz[i] - kz[j]) / (kz[i] + kz[j])\n",
    "        )\n",
    "        for i, j in ((0, 1), (1, 2))\n",
    "    ]\n",
    "    return (\n",
    "        abs(\n",
    "            (r[0] + r[1] * np.exp(2j * kz[1] * thickness))\n",
    "            / (1 + r[0] * r[1] * np.exp(2j * kz[1] * thickness))\n",
    "        )\n",
    "        ** 2\n",
    "    )\n",
    "\n",
    "\n",
    "metal = gold.relative_permittivity_at(frequency)\n",
    "stacks = {\n",
    "    \"kretschmann\": ([prism**2, metal, 1.0], 50e-9),\n",
    "    \"otto\": ([prism**2, 1.0, metal], 450e-9),\n",
    "}\n",
    "exact = {\n",
    "    (name, polarization): np.array(\n",
    "        [multilayer(angle, *stacks[name], polarization) for angle in angles]\n",
    "    )\n",
    "    for name, polarization in computed\n",
    "}\n",
    "coupling = np.degrees(np.arcsin(np.sqrt(metal / (metal + 1)).real / prism))\n",
    "print(\n",
    "    f\"gold at 633 nm: eps = {metal.real:.3f}{metal.imag:+.3f}i; critical angle {np.degrees(np.arcsin(1 / prism)):.2f} deg, \"\n",
    "    f\"plasmon matching n_p sin(theta) = Re(n_spp) at {coupling:.2f} deg\"\n",
    ")\n",
    "print(\n",
    "    \"\\nconfiguration   polarization   max |R - R_exact|   dip: angle  R      exact: angle  R\"\n",
    ")\n",
    "for (name, polarization), values in computed.items():\n",
    "    i, j = np.argmin(values), np.argmin(exact[(name, polarization)])\n",
    "    print(\n",
    "        f\"{name:14s}  {'p (H_z)' if polarization == 'Hz' else 's (E_z)':12s}   {np.max(np.abs(values - exact[(name, polarization)])):17.1e}   \"\n",
    "        f\"{angles[i]:8.2f}  {values[i]:.4f}   {angles[j]:8.2f}  {exact[(name, polarization)][j]:.4f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Reflectance against the angle of incidence for both couplers and both polarizations, with the\n",
    "exact multilayer curves dashed."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "for panel, name in zip(fig, configurations):\n",
    "    plots.line(\n",
    "        angles,\n",
    "        {\"p (TM)\": computed[(name, \"Hz\")], \"s (TE)\": computed[(name, \"Ez\")]},\n",
    "        reference={\"p (TM)\": exact[(name, \"Hz\")], \"s (TE)\": exact[(name, \"Ez\")]},\n",
    "        vlines={\n",
    "            \"critical angle\": np.degrees(np.arcsin(1 / prism)),\n",
    "            \"plasmon matching\": coupling,\n",
    "        },\n",
    "        ylimits=(0, 1.05),\n",
    "        xlabel=\"angle of incidence in the glass [deg]\",\n",
    "        ylabel=\"reflectance\",\n",
    "        title=f\"{name.capitalize()} configuration (dashed: exact)\",\n",
    "        legend=\"lower right\",\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the film thickness or the gap in `surface_plasmon_prism_coupling_geometry.py`: the dip is\n",
    "deepest when the radiative loss of the plasmon into the prism equals its absorption in the gold\n",
    "(critical coupling), near 45 nm and 450 nm here. A thin dielectric layer on the gold shifts the\n",
    "coupling angle - the principle of surface plasmon resonance sensors."
   ]
  }
 ]
}
