{
 "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": [
    "# Reflection of a circularly polarized plane wave at glass\n",
    "\n",
    "A plane wave in air meets the flat surface of glass with refractive index $n$ at normal\n",
    "incidence. Part of it is reflected, the rest is transmitted. For a circularly polarized wave\n",
    "both field components are reflected with the same coefficient, but because the reflected wave\n",
    "travels the other way, its sense of rotation with respect to the propagation direction is\n",
    "reversed: right-handed light comes back left-handed.\n",
    "\n",
    "The 3D model is a column of air, periodic in $x$ and $y$, so that it represents an unbounded\n",
    "plane wave. It comes from the CAD file `circular_wave_glass_reflection.step` (faces `x_min` ...\n",
    "`z_max`), written by `circular_wave_glass_reflection_geometry.py` with the CAD objects of\n",
    "OneSimulation. Two impedance boundaries close it:\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| $x$ and $y$ sides | periodic pairs |\n",
    "| $z=0$ | impedance boundary of air, $Y_0=\\sqrt{\\varepsilon_0/\\mu_0}$, with the incident field $\\mathbf E_0=(\\hat{\\mathbf x}+\\mathrm i\\hat{\\mathbf y})/\\sqrt2$ |\n",
    "| $z=\\ell$ | impedance boundary of glass, $Y=nY_0$, $n=1.5$: the glass half-space behind the interface |\n",
    "\n",
    "The impedance condition $\\mathbf n\\times\\mathbf H=Y\\,\\mathbf n\\times(\\mathbf n\\times\\mathbf E)$\n",
    "is exact for a plane wave entering a half-space of admittance $Y$, so the glass need not be\n",
    "meshed. Nédélec elements of order 2 solve\n",
    "$\\nabla\\times(\\mu_r^{-1}\\nabla\\times\\mathbf E)-k_0^2\\varepsilon_r\\mathbf E=0$ at 3 GHz.\n",
    "\n",
    "**Reference** (M. Born and E. Wolf, *Principles of Optics*, 7th ed., §1.5; E. Hecht, *Optics*,\n",
    "5th ed., §4.6 and §8.1). The Fresnel coefficients at normal incidence and the field in front of\n",
    "the interface (with $z'=z-\\ell$) are\n",
    "\n",
    "$$r=\\frac{1-n}{1+n},\\qquad t=\\frac{2}{1+n},\\qquad R=r^2,\\qquad T=n\\,t^2=1-R,\\qquad\n",
    "  \\mathbf E(z)=\\mathbf E_0\\big(e^{\\mathrm ik_0z}+r\\,e^{\\mathrm ik_0\\ell}e^{-\\mathrm ik_0z'}\\big).$$\n",
    "\n",
    "For $n=1.5$: $r=-0.2$, $R=4\\,\\%$, $T=96\\,\\%$."
   ]
  },
  {
   "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 IsotropicElectromagneticMaterial\n",
    "from onesim.meshing import PeriodicPair, StructuredHexahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Nedelec\n",
    "from onesim.numerics.linear import ComplexSparseDirect\n",
    "from onesim.physics.electromagnetics import FrequencyDomainMaxwell, ImpedanceBoundary\n",
    "from onesim.results.comparisons import convergence\n",
    "from onesim.simulation import PeriodicBoundary, Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "Hexahedra with one cell across the periodic column; three meshes along the 200 mm, two\n",
    "wavelengths at 3 GHz."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "column = load(\"circular_wave_glass_reflection.step\")\n",
    "faces = column.boundaries\n",
    "width, depth, length = column.size\n",
    "meshes = {\n",
    "    cells: StructuredHexahedralMesher(cells=(1, 1, cells)).generate(column)\n",
    "    for cells in (10, 20, 40)\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 5.5))\n",
    "plots.geometry(\n",
    "    column,\n",
    "    selection={\"incidence plane\": faces.z_min, \"air-glass interface\": faces.z_max},\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=20, azimuth=-60),\n",
    "    title=\"Air column\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[40],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=plots.Camera(elevation=20, azimuth=-60),\n",
    "    title=f\"Finest mesh: {meshes[40].cell_count} hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The same problem is solved with the circular incident field on every mesh, and on the finest\n",
    "mesh once more with each linear polarization alone."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "frequency, n = 3.0e9, 1.5\n",
    "admittance = np.sqrt(VACUUM_PERMITTIVITY / VACUUM_PERMEABILITY)\n",
    "k0 = 2 * np.pi * frequency * np.sqrt(VACUUM_PERMITTIVITY * VACUUM_PERMEABILITY)\n",
    "model = FrequencyDomainMaxwell(\n",
    "    domain=column.volume,\n",
    "    frequency=frequency,\n",
    "    material=IsotropicElectromagneticMaterial(),\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=2)), linear_solver=ComplexSparseDirect()\n",
    ")\n",
    "incident = {\n",
    "    \"circular\": (1 / np.sqrt(2), 1j / np.sqrt(2), 0.0),\n",
    "    \"x\": (1 / np.sqrt(2), 0.0, 0.0),\n",
    "    \"y\": (0.0, 1 / np.sqrt(2), 0.0),\n",
    "}\n",
    "solve = lambda polarization, mesh: Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Plane wave at glass\",\n",
    "        geometry=column,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            *(\n",
    "                PeriodicBoundary(\n",
    "                    physics=model,\n",
    "                    pair=PeriodicPair(faces[side + \"_min\"], faces[side + \"_max\"]),\n",
    "                )\n",
    "                for side in \"xy\"\n",
    "            ),\n",
    "            ImpedanceBoundary(\n",
    "                physics=model,\n",
    "                boundary=faces.z_min,\n",
    "                admittance=admittance,\n",
    "                incident_electric_field=incident[polarization],\n",
    "            ),\n",
    "            ImpedanceBoundary(\n",
    "                physics=model, boundary=faces.z_max, admittance=n * admittance\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=mesh,\n",
    "    numerics=numerics,\n",
    ").solve_stationary()\n",
    "circular = {cells: solve(\"circular\", mesh) for cells, mesh in meshes.items()}\n",
    "linear = {polarization: solve(polarization, meshes[40]) for polarization in (\"x\", \"y\")}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with Fresnel\n",
    "\n",
    "On a line along the column the field is fitted by a forward and a backward wave,\n",
    "$\\mathbf E=\\mathbf A\\,e^{\\mathrm ik_0z}+\\mathbf B\\,e^{-\\mathrm ik_0z'}$; the reflection coefficient is\n",
    "$B/(A\\,e^{\\mathrm ik_0\\ell})$ for each component. The transmitted power follows from the field on the\n",
    "interface, $T=n\\,|\\mathbf E(\\ell)|^2/|\\mathbf E_0|^2$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "z = np.linspace(0, length, 81)\n",
    "line = np.column_stack((np.full_like(z, 0.4 * width), np.full_like(z, 0.6 * depth), z))\n",
    "waves = np.column_stack((np.exp(1j * k0 * z), np.exp(-1j * k0 * (z - length))))\n",
    "r, t = (1 - n) / (1 + n), 2 / (1 + n)\n",
    "fields = {\n",
    "    cells: result.field(model.electric_field).evaluate(line)\n",
    "    for cells, result in circular.items()\n",
    "}\n",
    "split = {\n",
    "    cells: np.linalg.lstsq(waves, field[:, :2], rcond=None)[0]\n",
    "    for cells, field in fields.items()\n",
    "}\n",
    "reflection = {\n",
    "    cells: B / (A * np.exp(1j * k0 * length)) for cells, (A, B) in split.items()\n",
    "}\n",
    "print(\n",
    "    \"hexahedra   r (E_x)              r (E_y)              R          T          R + T\"\n",
    ")\n",
    "for cells, coefficient in reflection.items():\n",
    "    transmitted = n * np.sum(np.abs(fields[cells][-1, :2]) ** 2)\n",
    "    print(\n",
    "        f\"{meshes[cells].cell_count:9d}   {coefficient[0].real:+.5f}{coefficient[0].imag:+.5f}i   {coefficient[1].real:+.5f}{coefficient[1].imag:+.5f}i \"\n",
    "        f\"{np.mean(np.abs(coefficient) ** 2):9.5f} {transmitted:10.5f} {np.mean(np.abs(coefficient) ** 2) + transmitted:10.5f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"Fresnel     r = {r:+.5f}             r = {r:+.5f}            {r**2:9.5f} {n * t**2:10.5f} {1.0:10.5f}\"\n",
    ")\n",
    "study = convergence(\n",
    "    [abs(coefficient[0] - r) for coefficient in reflection.values()],\n",
    "    [length / cells for cells in reflection],\n",
    ")\n",
    "print(f\"error of r falls with the cell size at order {study.order:.2f}\")\n",
    "\n",
    "A, B = split[40]\n",
    "print(\n",
    "    f\"rotation in time: incident {'x -> y' if (A[0].conj() * A[1]).imag > 0 else 'y -> x'}, \"\n",
    "    f\"reflected {'x -> y' if (B[0].conj() * B[1]).imag > 0 else 'y -> x'}; \"\n",
    "    f\"relative to its direction of travel the reflected wave turns the other way\"\n",
    ")\n",
    "superposed = linear[\"x\"].field(model.electric_field).evaluate(line) + 1j * linear[\n",
    "    \"y\"\n",
    "].field(model.electric_field).evaluate(line)\n",
    "print(\n",
    "    f\"circular solution against x + i y superposition of the linear solutions: largest difference \"\n",
    "    f\"{np.abs(superposed - fields[40]).max():.1e} V/m\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The standing-wave pattern of the field strength in front of the glass, and the direction of the\n",
    "incident and of the reflected field vector along the column at one instant: both turn by 360°\n",
    "per wavelength, but in opposite senses, so the reflected wave has the opposite handedness."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = np.linspace(0, length, 600)\n",
    "exact = np.abs(\n",
    "    np.exp(1j * k0 * fine)\n",
    "    + r * np.exp(1j * k0 * length) * np.exp(-1j * k0 * (fine - length))\n",
    ") / np.sqrt(2)\n",
    "screw = lambda amplitude, sign: np.degrees(\n",
    "    np.unwrap(\n",
    "        np.arctan2(\n",
    "            (amplitude[1] * np.exp(sign * 1j * k0 * (z - length))).real,\n",
    "            (amplitude[0] * np.exp(sign * 1j * k0 * (z - length))).real,\n",
    "        )\n",
    "    )\n",
    ")\n",
    "fig = plots.figure(1, 2, size=(13, 5))\n",
    "plots.line(\n",
    "    points={\n",
    "        \"E_x\": (1e3 * z, np.abs(fields[40][:, 0])),\n",
    "        \"E_y\": (1e3 * z, np.abs(fields[40][:, 1])),\n",
    "    },\n",
    "    reference={\"Fresnel\": (1e3 * fine, exact)},\n",
    "    ylimits=(0.5, 0.9),\n",
    "    xlabel=\"position z [mm]\",\n",
    "    ylabel=\"|E| [V/m]\",\n",
    "    title=\"Standing wave in front of the glass (interface at 200 mm)\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * z,\n",
    "    {\n",
    "        \"incident wave\": screw(A * np.exp(1j * k0 * length), 1),\n",
    "        \"reflected wave\": screw(B, -1),\n",
    "    },\n",
    "    xlabel=\"position z [mm]\",\n",
    "    ylabel=\"direction of E at t = 0 [°]\",\n",
    "    title=\"Opposite screw sense of the two waves\",\n",
    "    legend=\"upper center\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Give the glass a complex index through the admittance, $Y=(n+\\mathrm i\\kappa)Y_0$, to model an\n",
    "absorbing substrate, or replace the glass boundary by a perfect conductor: the wave is then\n",
    "reflected completely with $r=-1$, and the column holds a pure standing wave."
   ]
  }
 ]
}
