{
 "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": [
    "# Fresnel equations at oblique incidence\n",
    "\n",
    "A plane wave of 1 GHz travels through a medium of index $n_1$ and meets the plane surface of a\n",
    "medium of index $n_2$ at the angle $\\theta_1$. It splits into a reflected wave and a refracted\n",
    "wave at the angle $\\theta_2$ of Snell's law, $n_1\\sin\\theta_1=n_2\\sin\\theta_2$. How the power\n",
    "divides depends on the polarization:\n",
    "\n",
    "* **s (TE)**: the electric field is perpendicular to the plane of incidence, out of the model\n",
    "  plane - the model solves for $E_z$,\n",
    "* **p (TM)**: the magnetic field is perpendicular to the plane of incidence - the model solves for\n",
    "  $H_z$.\n",
    "\n",
    "The interface is infinite, so one period of width $p=90$ mm ($0.3\\lambda$) suffices: the field\n",
    "at the right side of the cell is the field at the left side times the Bloch phase\n",
    "$e^{\\mathrm ik_xp}$ with $k_x=n_1k_0\\sin\\theta_1$. The top and bottom of the cell are Floquet\n",
    "ports that let every plane-wave order leave without reflection and feed the incident wave. With\n",
    "$p<\\lambda/(2n_2)$ only the specular order propagates, for every angle.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| `x_min`, `x_max` | Bloch periodic, $k_x=n_1k_0\\sin\\theta_1$ |\n",
    "| `y_max` (air) | Floquet port, incident wave when light comes from the air |\n",
    "| `y_min` (glass) | Floquet port, incident wave when light comes from the glass |\n",
    "\n",
    "**Reference** (M. Born and E. Wolf, *Principles of Optics*, 7th ed., §1.5.2; E. Hecht, *Optics*,\n",
    "5th ed., §4.6). With $c_1=\\cos\\theta_1$ and $c_2=\\cos\\theta_2$ the amplitude reflection\n",
    "coefficients are\n",
    "\n",
    "$$r_s=\\frac{n_1c_1-n_2c_2}{n_1c_1+n_2c_2},\\qquad r_p=\\frac{n_2c_1-n_1c_2}{n_2c_1+n_1c_2},\n",
    "  \\qquad R=|r|^2,\\qquad T=1-R .$$\n",
    "\n",
    "The p-reflection vanishes at the Brewster angle $\\tan\\theta_B=n_2/n_1$ (56.31° from air into\n",
    "glass of $n=1.5$); from the glass side all light is reflected beyond the critical angle\n",
    "$\\sin\\theta_c=n_2/n_1$ (41.81°)."
   ]
  },
  {
   "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",
    "    IsotropicElectromagneticMaterial,\n",
    "    RegionwiseElectromagneticMaterial,\n",
    ")\n",
    "from onesim.meshing import PeriodicPair, TriangularMesher\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",
    "from scipy.optimize import minimize_scalar\n",
    "\n",
    "theme.set()\n",
    "\n",
    "frequency, glass_index = 1.0e9, 1.5\n",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\n",
    "k0, wavelength = 2 * np.pi * frequency / light, light / frequency"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the cell and the glass in its lower half; `section` cuts both at half thickness.\n",
    "The mesh follows the interface (`embedded_regions`) and has quadratic triangles of\n",
    "$\\lambda/16$ in air, which is $\\lambda/(16n)$ in the glass."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "solids = {\n",
    "    name: load(f\"fresnel_oblique_incidence{name}.step\") for name in (\"\", \"_glass\")\n",
    "}\n",
    "cell = solids[\"\"].section((0, 0, 1), origin=(0, 0, 0.005))\n",
    "glass = solids[\"_glass\"].section((0, 0, 1), origin=(0, 0, 0.005)).named(\"glass\")\n",
    "sides = cell.boundaries\n",
    "mesh = TriangularMesher(\n",
    "    target_size=wavelength / 16, embedded_regions=(glass,)\n",
    ").generate(cell)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(9, 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 of the interface (STEP)\",\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",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The same `FrequencyDomainMaxwell` model solves $E_z$ (s) or $H_z$ (p) on the section. For\n",
    "every angle the Bloch wavevector of the side pair is set from the medium the light comes from,\n",
    "and `diffraction_efficiencies` returns the power of every propagating order at both ports\n",
    "relative to the incident power: `(0, 0)` is the reflected wave when the light comes from the\n",
    "air, `(1, 0)` the transmitted one."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = RegionwiseElectromagneticMaterial(\n",
    "    {\"glass\": IsotropicElectromagneticMaterial(relative_permittivity=glass_index**2)},\n",
    "    default=IsotropicElectromagneticMaterial(),\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",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "solve = lambda polarization, angle, from_air: diffraction_efficiencies(\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Fresnel cell\",\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=(\n",
    "                        (1.0 if from_air else glass_index)\n",
    "                        * k0\n",
    "                        * np.sin(np.radians(angle)),\n",
    "                        0.0,\n",
    "                        0.0,\n",
    "                    ),\n",
    "                ),\n",
    "                FloquetPort(\n",
    "                    physics=models[polarization],\n",
    "                    boundary=sides.y_max,\n",
    "                    incident_amplitude=1.0 if from_air else 0.0,\n",
    "                ),\n",
    "                FloquetPort(\n",
    "                    physics=models[polarization],\n",
    "                    boundary=sides.y_min,\n",
    "                    incident_amplitude=0.0 if from_air else 1.0,\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=numerics,\n",
    "    ).solve_stationary(),\n",
    "    models[polarization],\n",
    ")\n",
    "\n",
    "angles = np.arange(0.0, 89.5, 1.5)\n",
    "sweeps = {\n",
    "    (polarization, side): [\n",
    "        solve(polarization, angle, side == \"air\") for angle in angles\n",
    "    ]\n",
    "    for polarization in (\"Ez\", \"Hz\")\n",
    "    for side in (\"air\", \"glass\")\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The reflectance is the power in the specular order at the port of incidence, the\n",
    "transmittance the power at the opposite port (zero beyond the critical angle, where the\n",
    "transmitted order is evanescent)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def fresnel(polarization, n1, n2, angle):\n",
    "    c1, c2 = np.cos(np.radians(angle)), np.sqrt(\n",
    "        1 - (n1 / n2 * np.sin(np.radians(angle))) ** 2 + 0j\n",
    "    )\n",
    "    a, b = (n1 * c1, n2 * c2) if polarization == \"Ez\" else (n2 * c1, n1 * c2)\n",
    "    return np.abs((a - b) / (a + b)) ** 2\n",
    "\n",
    "\n",
    "ports = {\"air\": (0, 1), \"glass\": (1, 0)}\n",
    "indices = {\"air\": (1.0, glass_index), \"glass\": (glass_index, 1.0)}\n",
    "reflectance = {\n",
    "    key: np.array([e[(ports[key[1]][0], 0)] for e in sweep])\n",
    "    for key, sweep in sweeps.items()\n",
    "}\n",
    "transmittance = {\n",
    "    key: np.array([e.get((ports[key[1]][1], 0), 0.0) for e in sweep])\n",
    "    for key, sweep in sweeps.items()\n",
    "}\n",
    "exact = {key: fresnel(key[0], *indices[key[1]], angles) for key in sweeps}\n",
    "names = {\"Ez\": \"s (E_z)\", \"Hz\": \"p (H_z)\"}\n",
    "print(\n",
    "    \"incidence from   polarization   max |R - R_Fresnel|   max |T - (1 - R_Fresnel)|   max |R + T - 1|\"\n",
    ")\n",
    "for key in sweeps:\n",
    "    print(\n",
    "        f\"{key[1]:15s}  {names[key[0]]:12s}   {np.abs(reflectance[key] - exact[key]).max():19.2e}   \"\n",
    "        f\"{np.abs(transmittance[key] - (1 - exact[key])).max():25.2e}   {np.abs(reflectance[key] + transmittance[key] - 1).max():15.1e}\"\n",
    "    )\n",
    "print(\"\\nangle   R_s computed  R_s Fresnel   R_p computed  R_p Fresnel   (from air)\")\n",
    "for angle in (0.0, 30.0, 45.0, 60.0, 75.0, 88.5):\n",
    "    i = int(np.argmin(np.abs(angles - angle)))\n",
    "    print(\n",
    "        f\"{angles[i]:5.1f}   {reflectance[('Ez', 'air')][i]:12.6f}  {exact[('Ez', 'air')][i]:11.6f}   \"\n",
    "        f\"{reflectance[('Hz', 'air')][i]:12.6f}  {exact[('Hz', 'air')][i]:11.6f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Brewster angle is searched with the simulation itself: the angle at which the computed\n",
    "p-reflectance is smallest. The critical angle shows as the first angle with total reflection."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "brewster = minimize_scalar(\n",
    "    lambda angle: solve(\"Hz\", angle, True)[(0, 0)],\n",
    "    bounds=(50.0, 62.0),\n",
    "    method=\"bounded\",\n",
    "    options={\"xatol\": 1e-3},\n",
    ")\n",
    "critical = angles[np.argmax(reflectance[(\"Ez\", \"glass\")] > 1 - 1e-6)]\n",
    "print(\n",
    "    f\"\\nBrewster angle: computed {brewster.x:.3f} deg (R_p = {brewster.fun:.1e}), \"\n",
    "    f\"exact arctan(n) = {np.degrees(np.arctan(glass_index)):.3f} deg\"\n",
    ")\n",
    "print(\n",
    "    f\"total reflection from the glass side from {critical:.1f} deg on in the sweep; \"\n",
    "    f\"critical angle arcsin(1/n) = {np.degrees(np.arcsin(1 / glass_index)):.2f} deg\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Reflectance and transmittance against the angle of incidence, from the air side and from the\n",
    "glass side, with the Fresnel equations dashed."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(15, 5.5))\n",
    "for panel, side in zip((fig[0], fig[1]), (\"air\", \"glass\")):\n",
    "    plots.line(\n",
    "        angles,\n",
    "        {f\"R {names[p]}\": reflectance[(p, side)] for p in (\"Ez\", \"Hz\")}\n",
    "        | {f\"T {names[p]}\": transmittance[(p, side)] for p in (\"Ez\", \"Hz\")},\n",
    "        reference={f\"R {names[p]}\": exact[(p, side)] for p in (\"Ez\", \"Hz\")}\n",
    "        | {f\"T {names[p]}\": 1 - exact[(p, side)] for p in (\"Ez\", \"Hz\")},\n",
    "        vlines={\"Brewster\": np.degrees(np.arctan(indices[side][1] / indices[side][0]))}\n",
    "        | (\n",
    "            {\"critical\": np.degrees(np.arcsin(1 / glass_index))}\n",
    "            if side == \"glass\"\n",
    "            else {}\n",
    "        ),\n",
    "        xlimits=(0, 90),\n",
    "        ylimits=(0, 1.02),\n",
    "        xlabel=\"angle of incidence [deg]\",\n",
    "        ylabel=\"fraction of the incident power\",\n",
    "        title=f\"Light from the {side} side (dashed: Fresnel)\",\n",
    "        legend=\"center left\",\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Give the glass a thin coating as a third region in `fresnel_oblique_incidence_geometry.py`: the\n",
    "same cell then shows the interference of a thin film. A cell wider than $\\lambda/(2n)$ lets\n",
    "further diffraction orders appear once a grating is etched into the surface."
   ]
  }
 ]
}
