{
 "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 wire grating\n",
    "\n",
    "Silver wires of 40 nm radius, 400 nm apart and 20 nm above a glass substrate ($n=1.5$), form a\n",
    "grating for light of 550 nm. Besides the specular reflection and the refraction into the glass,\n",
    "the period lets the first diffraction order $m=-1$ propagate in the glass at every angle and in\n",
    "the air beyond $\\sin\\theta>\\lambda/p-1$ (22 degrees). In s polarization (electric field along the\n",
    "wires) the silver acts as a wire medium that reflects and diffracts strongly; in p polarization\n",
    "(magnetic field along the wires) the wires are polarized across and, far below their plasmon\n",
    "resonance in the ultraviolet, let most of the light through.\n",
    "\n",
    "Silver is a Drude metal, $\\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 and $\\gamma=3.2\\times10^{13}$ rad/s.\n",
    "The section solves $E_z$ (s) or $H_z$ (p); Bloch-periodic sides carry\n",
    "$k_x=k_0\\sin\\theta$, Floquet ports above and below feed the plane wave and take every order out.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| `x_min`, `x_max` | Bloch periodic, $k_x=k_0\\sin\\theta$ |\n",
    "| `y_max` (air) | Floquet port, incident wave |\n",
    "| `y_min` (glass) | Floquet port |\n",
    "\n",
    "**Reference** (M. Born and E. Wolf, *Principles of Optics*, 7th ed., §8.6; Poynting's theorem). The\n",
    "grating equation $k_{x,m}=k_0\\sin\\theta+2\\pi m/p$ fixes the directions of the orders; their\n",
    "efficiencies have no closed form, so their accuracy is checked by a mesh study (the mesh halved\n",
    "everywhere, the wire mesh halved again). What the wires do not reflect or transmit they absorb, so\n",
    "\n",
    "$$\\sum_m R_m+\\sum_m T_m+A=1,\\qquad A=\\frac1{P_{inc}}\\int_{\\rm wire}\\tfrac12\\omega\\,\\varepsilon_0\\,\\mathrm{Im}\\,\\varepsilon_m|E|^2\\,\\mathrm dA,$$\n",
    "\n",
    "with $R_m$, $T_m$ from the port amplitudes and $A$ from the absorbed power density of the Drude\n",
    "metal. The Galerkin solution keeps this balance to rounding on any mesh, so it confirms that ports\n",
    "and dissipation are consistent rather than measuring the discretization error.\n",
    "\n",
    "The STEP parts are drawn in micrometres, the unit that suits wires of a few tens of nanometres;\n",
    "`scaled` brings the meshes to metres, so the model is solved in SI units and the plots show\n",
    "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 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",
    "    diffraction_efficiencies,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()\n",
    "\n",
    "wavelength, period = 550e-9, 0.4e-6\n",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\n",
    "impedance = np.sqrt(VACUUM_PERMEABILITY / VACUUM_PERMITTIVITY)\n",
    "frequency, k0 = light / wavelength, 2 * np.pi / wavelength\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 cell, the glass and the wire; `section` cuts them at half thickness. The\n",
    "periodic sides are meshed alike; quadratic triangles of 20 nm, and 4 nm in the wire, where the\n",
    "field decays within 25 nm of the surface; `scaled(..., \"um\")` turns the micrometres of the drawing\n",
    "into metres."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "parts = {\n",
    "    name: load(f\"plasmonic_wire_grating{name}.step\").section(\n",
    "        (0, 0, 1), origin=(0, 0, 0.05)\n",
    "    )\n",
    "    for name in (\"\", \"_glass\", \"_wire\")\n",
    "}\n",
    "cell = parts[\"\"]\n",
    "sides = cell.boundaries\n",
    "mesh = scaled(\n",
    "    TriangularMesher(\n",
    "        target_size=0.02,\n",
    "        embedded_regions=(parts[\"_glass\"].named(\"glass\"), parts[\"_wire\"].named(\"wire\")),\n",
    "        region_sizes={\"wire\": 0.004},\n",
    "        periodic_pairs=(PeriodicPair(sides.x_min, sides.x_max),),\n",
    "    ).generate(cell),\n",
    "    \"um\",\n",
    ")\n",
    "\n",
    "fig = plots.figure(1, 2, size=(10, 8))\n",
    "plots.geometry(\n",
    "    cell,\n",
    "    selection={\n",
    "        \"periodic sides\": sides.x_min | sides.x_max,\n",
    "        \"port in air\": sides.y_max,\n",
    "        \"port in glass\": sides.y_min,\n",
    "    },\n",
    "    labels=False,\n",
    "    title=\"One period (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} 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",
    "For every angle the Bloch wavevector is set and `diffraction_efficiencies` returns the power of\n",
    "every propagating order at both ports relative to the incident power: `(0, m)` reflected, `(1, m)`\n",
    "transmitted. The absorbed power is integrated over the cell (only the silver dissipates)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = RegionwiseElectromagneticMaterial(\n",
    "    {\n",
    "        \"glass\": IsotropicElectromagneticMaterial(relative_permittivity=2.25),\n",
    "        \"wire\": silver,\n",
    "    },\n",
    "    default=IsotropicElectromagneticMaterial(),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "models = {\n",
    "    polarization: FrequencyDomainMaxwell(\n",
    "        domain=cell.domain(),\n",
    "        frequency=frequency,\n",
    "        material=material,\n",
    "        polarization=polarization,\n",
    "        phasor_convention=\"exp(-i*omega*t)\",\n",
    "        amplitude_convention=\"peak\",\n",
    "    )\n",
    "    for polarization in (\"Ez\", \"Hz\")\n",
    "}\n",
    "solve = lambda polarization, angle, grid=mesh: Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"wire grating\",\n",
    "        geometry=cell,\n",
    "        physics=(models[polarization],),\n",
    "        boundary_conditions=(\n",
    "            BlochPeriodicBoundary(\n",
    "                physics=models[polarization],\n",
    "                pair=PeriodicPair(sides.x_min, sides.x_max),\n",
    "                wavevector=(k0 * np.sin(np.radians(angle)), 0.0, 0.0),\n",
    "            ),\n",
    "            FloquetPort(\n",
    "                physics=models[polarization],\n",
    "                boundary=sides.y_max,\n",
    "                incident_amplitude=1.0,\n",
    "            ),\n",
    "            FloquetPort(physics=models[polarization], boundary=sides.y_min),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=grid,\n",
    "    numerics=numerics,\n",
    ").solve_stationary()\n",
    "\n",
    "angles = np.arange(0.0, 80.1, 2.5)\n",
    "results = {\n",
    "    (polarization, angle): solve(polarization, angle)\n",
    "    for polarization in (\"Ez\", \"Hz\")\n",
    "    for angle in angles\n",
    "}\n",
    "efficiencies = {\n",
    "    key: diffraction_efficiencies(result, models[key[0]])\n",
    "    for key, result in results.items()\n",
    "}\n",
    "incident = {\"Ez\": 0.5 / impedance * period, \"Hz\": 0.5 * impedance * period}\n",
    "absorbed = {\n",
    "    key: result.field(models[key[0]].absorbed_power_density).integrate().value\n",
    "    / (incident[key[0]] * np.cos(np.radians(key[1])))\n",
    "    for key, result in results.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The orders present, their efficiencies at a few angles, and the power balance over all angles."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "names = {\"Ez\": \"s (E_z)\", \"Hz\": \"p (H_z)\"}\n",
    "print(\n",
    "    f\"silver at {1e9 * wavelength:.0f} nm: eps = {silver.relative_permittivity_at(frequency):.2f}\"\n",
    ")\n",
    "for polarization in (\"Ez\", \"Hz\"):\n",
    "    print(\n",
    "        f\"\\n{names[polarization]}   angle   R_0      R_-1     T_0      T_-1     T_+1     A        sum\"\n",
    "    )\n",
    "    for angle in (0.0, 20.0, 40.0, 60.0, 80.0):\n",
    "        e = efficiencies[(polarization, angle)]\n",
    "        print(\n",
    "            f\"           {angle:5.1f}   {e.get((0, 0), 0):.4f}   {e.get((0, -1), 0):.4f}   {e.get((1, 0), 0):.4f}   {e.get((1, -1), 0):.4f}   \"\n",
    "            f\"{e.get((1, 1), 0):.4f}   {absorbed[(polarization, angle)]:.4f}   {sum(e.values()) + absorbed[(polarization, angle)]:.6f}\"\n",
    "        )\n",
    "balance = {\n",
    "    polarization: max(\n",
    "        abs(\n",
    "            sum(efficiencies[(polarization, a)].values())\n",
    "            + absorbed[(polarization, a)]\n",
    "            - 1\n",
    "        )\n",
    "        for a in angles\n",
    "    )\n",
    "    for polarization in (\"Ez\", \"Hz\")\n",
    "}\n",
    "symmetry = {\n",
    "    polarization: abs(\n",
    "        efficiencies[(polarization, 0.0)].get((1, -1), 0)\n",
    "        - efficiencies[(polarization, 0.0)].get((1, 1), 0)\n",
    "    )\n",
    "    for polarization in (\"Ez\", \"Hz\")\n",
    "}\n",
    "print(\n",
    "    f\"\\nlargest |sum R + sum T + A - 1| over all angles: s {balance['Ez']:.1e}, p {balance['Hz']:.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"normal incidence |T_-1 - T_+1| (mirror symmetry): s {symmetry['Ez']:.1e}, p {symmetry['Hz']:.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"first reflected order appears beyond arcsin(lambda/p - 1) = {np.degrees(np.arcsin(wavelength / period - 1)):.1f} deg\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The mesh study: triangles of 10 nm and 2 nm in the wire, at three angles."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = scaled(\n",
    "    TriangularMesher(\n",
    "        target_size=0.01,\n",
    "        embedded_regions=(parts[\"_glass\"].named(\"glass\"), parts[\"_wire\"].named(\"wire\")),\n",
    "        region_sizes={\"wire\": 0.002},\n",
    "        periodic_pairs=(PeriodicPair(sides.x_min, sides.x_max),),\n",
    "    ).generate(cell),\n",
    "    \"um\",\n",
    ")\n",
    "refined = {\n",
    "    (polarization, angle): diffraction_efficiencies(\n",
    "        solve(polarization, angle, fine), models[polarization]\n",
    "    )\n",
    "    for polarization in (\"Ez\", \"Hz\")\n",
    "    for angle in (0.0, 40.0, 70.0)\n",
    "}\n",
    "print(\n",
    "    f\"\\nmesh study ({mesh.cell_count} -> {fine.cell_count} triangles): largest change of any efficiency\"\n",
    ")\n",
    "for (polarization, angle), values in refined.items():\n",
    "    print(\n",
    "        f\"  {names[polarization]} at {angle:4.1f} deg: {max(abs(values[k] - efficiencies[(polarization, angle)].get(k, 0.0)) for k in values):.1e}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Specular and first-order reflection, transmission and absorption against the angle of incidence,\n",
    "and the magnetic field around the wires in p polarization at 40 degrees."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x, y = np.asarray(mesh.coordinates).T\n",
    "field = np.abs(\n",
    "    results[(\"Hz\", 40.0)]\n",
    "    .field(models[\"Hz\"].magnetic_flux_density)\n",
    "    .evaluate(np.column_stack((x, y)))[:, 2]\n",
    ") / (VACUUM_PERMEABILITY * 1.0)\n",
    "fig = plots.figure(1, 3, size=(24, 6.5))\n",
    "for panel, polarization in zip(fig, (\"Ez\", \"Hz\")):\n",
    "    plots.line(\n",
    "        angles,\n",
    "        {\n",
    "            \"R_0\": [efficiencies[(polarization, a)].get((0, 0), 0) for a in angles],\n",
    "            \"R_-1\": [efficiencies[(polarization, a)].get((0, -1), 0) for a in angles],\n",
    "            \"T_0\": [efficiencies[(polarization, a)].get((1, 0), 0) for a in angles],\n",
    "            \"T_-1\": [efficiencies[(polarization, a)].get((1, -1), 0) for a in angles],\n",
    "            \"A\": [absorbed[(polarization, a)] for a in angles],\n",
    "        },\n",
    "        vlines={\"R_-1 opens\": np.degrees(np.arcsin(wavelength / period - 1))},\n",
    "        xlimits=(0, 80),\n",
    "        ylimits=(0, 1),\n",
    "        xlabel=\"angle of incidence [deg]\",\n",
    "        ylabel=\"fraction of the incident power\",\n",
    "        title=f\"{names[polarization]} polarization\",\n",
    "        legend=\"upper right\",\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.heatmap(\n",
    "    x,\n",
    "    y,\n",
    "    field,\n",
    "    triangles=np.asarray(mesh.cells),\n",
    "    limits=(0, np.percentile(field, 99.5)),\n",
    "    label=\"|H_z| / |H_inc|\",\n",
    "    ylimits=(-0.3e-6, 0.4e-6),\n",
    "    title=\"p polarization at 40 deg\",\n",
    "    length_unit=\"um\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the wire radius or the period in `plasmonic_wire_grating_geometry.py`, or sweep the\n",
    "wavelength instead of the angle: the absorption peak of the p polarization follows the localized\n",
    "plasmon of the wire, near $\\varepsilon_m=-\\varepsilon_{\\rm surrounding}$."
   ]
  }
 ]
}
