{
 "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": [
    "# Light scattered by a rough metal coating\n",
    "\n",
    "A glass substrate ($n=1.5$) carries a gold coating 50 nm thick ($\\varepsilon=-11.7+1.26\\,\\mathrm i$ at\n",
    "$\\lambda_0=633$ nm). Light falls on it from the air at normal incidence. On an optically flat coating\n",
    "the light is reflected, transmitted and absorbed as in a thin film; a rough top surface scatters part\n",
    "of it into oblique directions and raises the absorption.\n",
    "\n",
    "The rough surface is periodic over $W=4\\,\\mu$m, so the field obeys Bloch conditions and leaves\n",
    "through a finite number of diffraction orders $\\sin\\theta_m=m\\lambda_0/(nW)$. OneSimulation solves\n",
    "one period on its cross-section, for $E_z$ (s polarization, electric field along the grooves) and\n",
    "$H_z$ (p polarization); `FloquetPort` feeds the specular order and absorbs all orders, and\n",
    "`diffraction_efficiencies` returns the power of every order:\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| `y_max` (air) | Floquet port, plane wave fed at normal incidence |\n",
    "| `y_min` (glass) | Floquet port |\n",
    "| `x_min` ↔ `x_max` | Bloch periodic, $k_x=0$ |\n",
    "\n",
    "The cell, the glass and the two coatings come from `rough_surface_scattering_floquet.step` and the\n",
    "files `..._glass.step`, `..._flat.step` and `..._rough.step`, drawn in micrometres by\n",
    "`rough_surface_scattering_floquet_geometry.py` with the CAD objects of OneSimulation; the rough\n",
    "top surface is a periodic sum of eight cosines with random phases, 15 nm rms.\n",
    "\n",
    "**Reference.** The flat coating is a single absorbing film between air and glass; its reflectance\n",
    "and transmittance follow from the Airy formula of the film, computed here by the coherent thin-film\n",
    "solution `CoherentOpticalStack` (Born and Wolf, *Principles of Optics*, 7th ed., §13.4). For the\n",
    "rough coating there is no closed form: the computed orders and the power absorbed in the gold must\n",
    "conserve energy, $R+T+A=1$."
   ]
  },
  {
   "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",
    "    CoherentOpticalStack,\n",
    "    IsotropicElectromagneticMaterial,\n",
    "    OpticalLayer,\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",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`section` cuts the plates at mid-depth. Quadratic triangles of 40 nm in air and glass and 6 nm in\n",
    "the coating, which is thinner than the skin depth of gold (about 30 nm) only by a factor of two;\n",
    "`scaled` turns the micrometres of the drawing into metres. The periodic sides get matching nodes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plates = {\n",
    "    name: load(f\"rough_surface_scattering_floquet{suffix}.step\")\n",
    "    for name, suffix in (\n",
    "        (\"cell\", \"\"),\n",
    "        (\"glass\", \"_glass\"),\n",
    "        (\"flat\", \"_flat\"),\n",
    "        (\"rough\", \"_rough\"),\n",
    "    )\n",
    "}\n",
    "cut = lambda part: part.section((0, 0, 1), origin=(0, 0, 0.025))\n",
    "cell = cut(plates[\"cell\"])\n",
    "sides = cell.boundaries\n",
    "meshes = {\n",
    "    name: scaled(\n",
    "        TriangularMesher(\n",
    "            target_size=0.04,\n",
    "            embedded_regions=(\n",
    "                cut(plates[\"glass\"]).named(\"glass\"),\n",
    "                cut(plates[name]).named(\"gold\"),\n",
    "            ),\n",
    "            region_sizes={\"gold\": 0.006},\n",
    "            hard_sizes={\"x_min\": 0.006, \"x_max\": 0.006},\n",
    "            grading=0.3,\n",
    "        ).generate(cell),\n",
    "        \"um\",\n",
    "    )\n",
    "    for name in (\"flat\", \"rough\")\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(16, 5))\n",
    "plots.geometry(\n",
    "    [plates[\"glass\"].named(\"glass\"), plates[\"rough\"].named(\"rough gold coating\")],\n",
    "    camera=plots.Camera(elevation=60, azimuth=-80),\n",
    "    title=\"One period: glass and rough coating (STEP)\",\n",
    "    length_unit=\"um\",\n",
    "    drawing_unit=\"um\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"rough\"],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    length_unit=\"um\",\n",
    "    title=f\"Rough coating: {meshes['rough'].cell_count} quadratic triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "One solve per coating and polarization at $\\lambda_0=633$ nm; the orders on the air side give the\n",
    "reflectance, those on the glass side the transmittance."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "wavelength, gold, n_glass = 633e-9, -11.7 + 1.26j, 1.5\n",
    "material = RegionwiseElectromagneticMaterial(\n",
    "    {\n",
    "        \"gold\": IsotropicElectromagneticMaterial(relative_permittivity=gold),\n",
    "        \"glass\": IsotropicElectromagneticMaterial(relative_permittivity=n_glass**2),\n",
    "    },\n",
    "    default=IsotropicElectromagneticMaterial(),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "solve = lambda coating, polarization: (\n",
    "    lambda m: (\n",
    "        Simulation(\n",
    "            problem=Problem(\n",
    "                name=\"Coated glass\",\n",
    "                geometry=cell,\n",
    "                physics=(m,),\n",
    "                boundary_conditions=(\n",
    "                    BlochPeriodicBoundary(\n",
    "                        physics=m,\n",
    "                        pair=PeriodicPair(sides.x_min, sides.x_max),\n",
    "                        wavevector=(0.0, 0.0, 0.0),\n",
    "                    ),\n",
    "                    FloquetPort(\n",
    "                        physics=m, boundary=sides.y_max, incident_amplitude=1.0\n",
    "                    ),\n",
    "                    FloquetPort(physics=m, boundary=sides.y_min),\n",
    "                ),\n",
    "            ),\n",
    "            mesh=meshes[coating],\n",
    "            numerics=numerics,\n",
    "        ).solve_stationary(),\n",
    "        m,\n",
    "    )\n",
    ")(\n",
    "    FrequencyDomainMaxwell(\n",
    "        domain=cell.domain(),\n",
    "        frequency=light / wavelength,\n",
    "        material=material,\n",
    "        polarization=polarization,\n",
    "        phasor_convention=\"exp(-i*omega*t)\",\n",
    "        amplitude_convention=\"peak\",\n",
    "    )\n",
    ")\n",
    "solved = {\n",
    "    (coating, polarization): solve(coating, polarization)\n",
    "    for coating in (\"flat\", \"rough\")\n",
    "    for polarization in (\"Ez\", \"Hz\")\n",
    "}\n",
    "runs = {key: diffraction_efficiencies(*value) for key, value in solved.items()}\n",
    "impedance = np.sqrt(VACUUM_PERMEABILITY / VACUUM_PERMITTIVITY)\n",
    "incident = {\"Ez\": 4e-6 / (2 * impedance), \"Hz\": 4e-6 * impedance / 2}\n",
    "absorbed = {\n",
    "    key: result.field(m.absorbed_power_density).integrate().value / incident[key[1]]\n",
    "    for key, (result, m) in solved.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Reflectance $R$ (all orders in the air), transmittance $T$ (all orders in the glass), absorptance $A$\n",
    "from the power dissipated in the gold (per period, relative to the incident power $W|E_0|^2/2\\eta_0$\n",
    "or $W\\eta_0|H_0|^2/2$), and the energy balance $R+T+A-1$; the diffuse part is the power outside the\n",
    "specular orders."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "film = CoherentOpticalStack(\n",
    "    layers=(OpticalLayer(thickness=50e-9, index=np.sqrt(gold)),)\n",
    ")\n",
    "exact = {\n",
    "    \"Ez\": film(wavelength, 1.0, 1.0, n_glass, polarization=\"s\"),\n",
    "    \"Hz\": film(wavelength, 1.0, 1.0, n_glass, polarization=\"p\"),\n",
    "}\n",
    "print(\n",
    "    \"coating  polarization      R         T         A      R+T+A-1   diffuse R   diffuse T   orders   thin-film solution R / T / A\"\n",
    ")\n",
    "for (coating, polarization), orders in runs.items():\n",
    "    R = sum(v for (port, order), v in orders.items() if port == 0)\n",
    "    T = sum(v for (port, order), v in orders.items() if port == 1)\n",
    "    ref = exact[polarization]\n",
    "    print(\n",
    "        f\"{coating:7s}  {polarization:12s} {R:9.5f} {T:9.5f} {absorbed[(coating, polarization)]:9.5f} {R + T + absorbed[(coating, polarization)] - 1:+9.1e} {R - orders.get((0, 0), 0.0):11.2e} {T - orders.get((1, 0), 0.0):11.2e} {len(orders):8d}   \"\n",
    "        + (\n",
    "            f\"{ref.reflected:.5f} / {ref.transmitted:.5f} / {1 - ref.reflected - ref.transmitted:.5f}\"\n",
    "            if coating == \"flat\"\n",
    "            else \"\"\n",
    "        )\n",
    "    )\n",
    "for polarization in (\"Ez\", \"Hz\"):\n",
    "    flat = runs[(\"flat\", polarization)]\n",
    "    print(\n",
    "        f\"flat coating, {polarization}: |R - R_film| = {abs(sum(v for (p, _), v in flat.items() if p == 0) - exact[polarization].reflected):.1e}, \"\n",
    "        f\"|T - T_film| = {abs(sum(v for (p, _), v in flat.items() if p == 1) - exact[polarization].transmitted):.1e}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The power reflected into each diffraction order by the rough coating, against the angle of the\n",
    "order in the air, for both polarizations (the specular order is off the scale)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "angle = lambda order: np.degrees(np.arcsin(np.clip(order * wavelength / 4e-6, -1, 1)))\n",
    "fig = plots.figure(1, 2, size=(16, 5.5))\n",
    "for panel, polarization in enumerate((\"Ez\", \"Hz\")):\n",
    "    orders = {\n",
    "        o: v for (p, o), v in runs[(\"rough\", polarization)].items() if p == 0 and o != 0\n",
    "    }\n",
    "    plots.line(\n",
    "        points={\n",
    "            \"rough coating, reflected orders\": (\n",
    "                angle(np.array(list(orders))),\n",
    "                np.array(list(orders.values())),\n",
    "            )\n",
    "        },\n",
    "        scale=\"logy\",\n",
    "        ylimits=(1e-5, 1e-1),\n",
    "        xlabel=\"angle of the order in air [°]\",\n",
    "        ylabel=\"power in the order\",\n",
    "        title=f\"Diffuse reflection, {'s' if polarization == 'Ez' else 'p'} polarization\",\n",
    "        legend=\"upper right\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the roughness in `rough_surface_scattering_floquet_geometry.py` or shorten its correlation\n",
    "length: the diffuse part grows and, for p polarization, rough gold couples light into surface\n",
    "plasmons, which shows as a dip in the reflectance. A nonzero Bloch wavevector gives oblique\n",
    "incidence."
   ]
  }
 ]
}
