{
 "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": [
    "# Metal scatterer near an optical waveguide\n",
    "\n",
    "A slab waveguide - a core of index $n_1=2.0$ and thickness $d=0.4$ um in a cladding of $n_2=1.45$ -\n",
    "guides light of 1.3 to 1.8 um in its fundamental TE and TM modes. A gold rod 0.15 um above the\n",
    "core reaches into the evanescent tail of the mode. It takes power out of the guided mode in three\n",
    "ways: it reflects part of it back into the guide, it absorbs part (gold is lossy) and it scatters\n",
    "part into the cladding as radiation.\n",
    "\n",
    "Gold is the Drude-Lorentz model of Rakić et al. ($\\hbar\\omega_p=9.03$ eV, $f_0=0.760$,\n",
    "$\\hbar\\Gamma_0=0.053$ eV and five interband oscillators). The section solves $E_z$ (TE) and $H_z$\n",
    "(TM). Absorbing layers (`CartesianPML`) 0.8 um thick above and below take the radiation; the\n",
    "waveguide ports run through them, and their mode solver handles the complex material of the layers.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| `x_min` | waveguide port, four modes, the fundamental fed with 1 W/m |\n",
    "| `x_max` | waveguide port, four modes |\n",
    "| `y_min`, `y_max` (behind the absorbing layers) | perfect electric conductor |\n",
    "\n",
    "**Reference** (D. Marcuse, *Theory of Dielectric Optical Waveguides*, 2nd ed., §1.3; A. D. Rakić et\n",
    "al., *Appl. Opt.* 37, 5271 (1998); Poynting's theorem). With $\\kappa=\\sqrt{n_1^2k_0^2-\\beta^2}$ and\n",
    "$\\gamma=\\sqrt{\\beta^2-n_2^2k_0^2}$ the even modes of the slab satisfy\n",
    "\n",
    "$$\\kappa\\tan\\frac{\\kappa d}{2}=\\gamma\\ \\ \\text{(TE)},\\qquad\n",
    "  \\frac{\\kappa}{n_1^2}\\tan\\frac{\\kappa d}{2}=\\frac{\\gamma}{n_2^2}\\ \\ \\text{(TM)}.$$\n",
    "\n",
    "The power balance $R+T+A+P_{rad}=1$ uses four independent parts of the solution: the port\n",
    "amplitudes ($R=|S_{11}|^2$, $T=|S_{21}|^2$), the absorbed power density in the gold ($A$) and the\n",
    "Poynting flux $\\tfrac12\\mathrm{Re}(\\mathbf E\\times\\mathbf H^*)$ through two lines just inside the\n",
    "absorbing layers ($P_{rad}$).\n",
    "\n",
    "The STEP parts are drawn in micrometres, the unit that suits features of 0.1 um; `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",
    "    CartesianPML,\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 brentq\n",
    "\n",
    "theme.set()\n",
    "\n",
    "core, cladding, thickness = 2.0, 1.45, 0.4e-6\n",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\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 the cladding, the core and the rod; `section` cuts them at half thickness. Quadratic\n",
    "triangles of 80 nm in the cladding, 40 nm in the core and 6 nm in the rod, where the field decays\n",
    "within 25 nm of the surface; `scaled(..., \"um\")` turns the micrometres of the drawing into metres."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "parts = {\n",
    "    name: load(f\"waveguide_metal_scatterer{name}.step\").section(\n",
    "        (0, 0, 1), origin=(0, 0, 0.05)\n",
    "    )\n",
    "    for name in (\"\", \"_core\", \"_rod\")\n",
    "}\n",
    "section = parts[\"\"]\n",
    "sides = section.boundaries\n",
    "mesh = scaled(\n",
    "    TriangularMesher(\n",
    "        target_size=0.08,\n",
    "        embedded_regions=(parts[\"_core\"].named(\"core\"), parts[\"_rod\"].named(\"rod\")),\n",
    "        region_sizes={\"core\": 0.04, \"rod\": 0.006},\n",
    "    ).generate(section),\n",
    "    \"um\",\n",
    ")\n",
    "\n",
    "fig = plots.figure(1, 2, size=(16, 6.5))\n",
    "plots.geometry(\n",
    "    section,\n",
    "    selection={\n",
    "        \"ports\": sides.x_min | sides.x_max,\n",
    "        \"outer faces\": sides.y_min | sides.y_max,\n",
    "    },\n",
    "    labels=False,\n",
    "    title=\"Cladding, core and gold rod (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",
    "The damping of the absorbing layers grows quadratically over the outer 0.8 um above and below.\n",
    "Each port keeps four modes - the guided mode and the next three modes of the port line, ordered by\n",
    "their propagation constant; modes that live in the absorbing layers come last - so that the near\n",
    "field of the rod that reaches the ports also leaves the model."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "omega = lambda wavelength: 2 * np.pi * light / wavelength\n",
    "material = lambda wavelength: CartesianPML(\n",
    "    material=RegionwiseElectromagneticMaterial(\n",
    "        {\n",
    "            \"core\": IsotropicElectromagneticMaterial(relative_permittivity=core**2),\n",
    "            \"rod\": gold,\n",
    "        },\n",
    "        default=IsotropicElectromagneticMaterial(relative_permittivity=cladding**2),\n",
    "    ),\n",
    "    damping=lambda x, y, z: np.column_stack(\n",
    "        (\n",
    "            0 * x,\n",
    "            3\n",
    "            * omega(wavelength)\n",
    "            * np.clip((np.abs(y) - 1.7e-6) / 0.8e-6, 0, None) ** 2,\n",
    "            0 * x,\n",
    "        )\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "model = lambda wavelength, polarization: FrequencyDomainMaxwell(\n",
    "    domain=section.domain(),\n",
    "    frequency=light / wavelength,\n",
    "    material=material(wavelength),\n",
    "    polarization=polarization,\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "solve = lambda physics: Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"scatterer\",\n",
    "        geometry=section,\n",
    "        physics=(physics,),\n",
    "        boundary_conditions=(\n",
    "            SectionWaveguidePort(\n",
    "                physics=physics, boundary=sides.x_min, modes=4, incident_power=1.0\n",
    "            ),\n",
    "            SectionWaveguidePort(physics=physics, boundary=sides.x_max, modes=4),\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 = np.linspace(1.3e-6, 1.8e-6, 11)\n",
    "cases = {\n",
    "    (wavelength, polarization): model(wavelength, polarization)\n",
    "    for wavelength in wavelengths\n",
    "    for polarization in (\"Ez\", \"Hz\")\n",
    "}\n",
    "results = {key: solve(physics) for key, physics in cases.items()}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The guided mode of the port line against the exact slab modes, then the power balance. The\n",
    "Poynting flux leaves through the lines $y=\\pm1.6$ um; $\\mathbf H=\\mathbf B/\\mu_0$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "line = np.linspace(-2.9e-6, 2.9e-6, 1161)\n",
    "flux = {}\n",
    "for key, result in results.items():\n",
    "    leaving = 0.0\n",
    "    for height, sign in ((1.6e-6, 1.0), (-1.6e-6, -1.0)):\n",
    "        points = np.column_stack((line, height + 0 * line))\n",
    "        E = result.field(cases[key].electric_field).evaluate(points)\n",
    "        H = (\n",
    "            result.field(cases[key].magnetic_flux_density).evaluate(points)\n",
    "            / VACUUM_PERMEABILITY\n",
    "        )\n",
    "        leaving += sign * np.trapezoid(\n",
    "            0.5 * (E[:, 2] * np.conj(H[:, 0]) - E[:, 0] * np.conj(H[:, 2])).real, line\n",
    "        )\n",
    "    flux[key] = leaving\n",
    "scattering = {\n",
    "    key: scattering_parameters(result, cases[key]) for key, result in results.items()\n",
    "}\n",
    "absorbed = {\n",
    "    key: result.field(cases[key].absorbed_power_density).integrate().value\n",
    "    for key, result in results.items()\n",
    "}\n",
    "dispersion = lambda n, k0, te: (\n",
    "    np.sqrt(core**2 - n**2)\n",
    "    * k0\n",
    "    * np.tan(np.sqrt(core**2 - n**2) * k0 * thickness / 2)\n",
    "    / (1 if te else core**2)\n",
    "    - np.sqrt(n**2 - cladding**2) * k0 / (1 if te else cladding**2)\n",
    ")\n",
    "print(\n",
    "    \"lambda   pol   n_eff computed   n_eff exact     R        T        A        P_rad    R+T+A+P_rad\"\n",
    ")\n",
    "for (wavelength, polarization), result in results.items():\n",
    "    k0 = 2 * np.pi / wavelength\n",
    "    neff = port_modes(result, cases[(wavelength, polarization)])[0][\"effective_index\"][\n",
    "        0\n",
    "    ]\n",
    "    exact = brentq(\n",
    "        dispersion, cladding + 1e-9, core - 1e-9, args=(k0, polarization == \"Ez\")\n",
    "    )\n",
    "    s = scattering[(wavelength, polarization)]\n",
    "    R, T = abs(s[(0, 0)]) ** 2, abs(s[(1, 0)]) ** 2\n",
    "    print(\n",
    "        f\"{wavelength * 1e6:5.2f}   {'TE' if polarization == 'Ez' else 'TM'}    {neff.real:.6f}         {exact:.6f}      {R:.4f}   {T:.4f}   {absorbed[(wavelength, polarization)]:.4f}   \"\n",
    "        f\"{flux[(wavelength, polarization)]:.4f}   {R + T + absorbed[(wavelength, polarization)] + flux[(wavelength, polarization)]:.4f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Reflection, absorption and radiation against the wavelength for both polarizations, and the\n",
    "field around the rod at 1.55 um."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x, y = np.asarray(mesh.coordinates).T\n",
    "at = wavelengths[int(np.argmin(np.abs(wavelengths - 1.55e-6)))]\n",
    "values = np.abs(\n",
    "    results[(at, \"Ez\")]\n",
    "    .field(cases[(at, \"Ez\")].electric_field)\n",
    "    .evaluate(np.column_stack((x, y)))[:, 2]\n",
    ")\n",
    "fig = plots.figure(1, 2, size=(20, 6.5))\n",
    "plots.line(\n",
    "    wavelengths * 1e6,\n",
    "    {\n",
    "        f\"{name} {'TE' if p == 'Ez' else 'TM'}\": data\n",
    "        for p in (\"Ez\", \"Hz\")\n",
    "        for name, data in (\n",
    "            (\"R\", [abs(scattering[(w, p)][(0, 0)]) ** 2 for w in wavelengths]),\n",
    "            (\"A\", [absorbed[(w, p)] for w in wavelengths]),\n",
    "            (\"P_rad\", [flux[(w, p)] for w in wavelengths]),\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"vacuum wavelength [um]\",\n",
    "    ylabel=\"fraction of the guided power\",\n",
    "    title=\"Where the rod takes the power\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.heatmap(\n",
    "    x,\n",
    "    y,\n",
    "    values,\n",
    "    triangles=np.asarray(mesh.cells),\n",
    "    limits=(0, np.percentile(values, 99.5)),\n",
    "    label=\"|E_z| [V/m]\",\n",
    "    ylimits=(-1.7e-6, 1.7e-6),\n",
    "    aspect=\"auto\",\n",
    "    title=f\"TE mode passing the rod at {at * 1e6:.2f} um\",\n",
    "    length_unit=\"um\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Move the rod closer to the core in `waveguide_metal_scatterer_geometry.py`: the coupling to the\n",
    "evanescent tail grows exponentially. A rod of silica instead of gold only scatters, a row of rods\n",
    "along the guide forms a grating coupler that sends the light out at a chosen angle."
   ]
  }
 ]
}
