{
 "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": [
    "# Fabry-Perot etalon\n",
    "\n",
    "A plane-parallel plate of high-resistivity silicon ($n=3.42$, thickness $d=2$ mm) in air is the\n",
    "simplest Fabry-Perot interferometer, used as a frequency filter and a thickness standard in the\n",
    "millimetre-wave and terahertz range. Each face reflects about 30 % of the power; the waves that\n",
    "bounce between the faces add up in phase when the round trip is a whole number of wavelengths,\n",
    "and the plate is then fully transparent.\n",
    "\n",
    "The plate is infinite in $x$, so one period of width 0.3 mm is computed with Bloch periodic sides\n",
    "and Floquet ports above and below. The model solves the field component out of the plane: $E_z$\n",
    "for s polarization and $H_z$ for p polarization.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| `x_min`, `x_max` | Bloch periodic, $k_x=k_0\\sin\\theta$ |\n",
    "| `y_max` | Floquet port with the incident plane wave |\n",
    "| `y_min` | Floquet port, the transmitted wave leaves |\n",
    "\n",
    "**Reference** (M. Born and E. Wolf, *Principles of Optics*, 7th ed., §7.6.1; E. Hecht, *Optics*,\n",
    "5th ed., §9.6). With the reflectance $R$ of one face from the Fresnel equations and the phase of\n",
    "one round trip $\\delta=4\\pi n d\\cos\\theta_t\\,f/c$, the transmittance of the lossless plate is the\n",
    "Airy function\n",
    "\n",
    "$$T=\\frac{1}{1+F\\sin^2(\\delta/2)},\\qquad F=\\frac{4R}{(1-R)^2}.$$\n",
    "\n",
    "It is 1 at the resonances $f_m=m\\,c/(2nd\\cos\\theta_t)$, spaced by the free spectral range\n",
    "$c/(2nd\\cos\\theta_t)=21.9$ GHz at normal incidence, and $(1-R)^2/(1+R)^2$ midway between them."
   ]
  },
  {
   "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",
    "index = 3.42\n",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the cell and the silicon plate; `section` cuts both at half thickness. Quadratic\n",
    "triangles of 40 µm in the silicon resolve its shortest wavelength (0.55 mm at 160 GHz) with\n",
    "fourteen cells, 0.15 mm in the air; the periodic sides are divided into equal 40 µm pieces, so that\n",
    "their nodes match and fall on the faces of the plate, and the ports into 50 µm pieces, enough for\n",
    "the plane-wave orders the ports expand the field in."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "solids = {\n",
    "    name: load(f\"fabry_perot_etalon_transmission{name}.step\")\n",
    "    for name in (\"\", \"_silicon\")\n",
    "}\n",
    "cell = solids[\"\"].section((0, 0, 1), origin=(0, 0, 0.05e-3))\n",
    "plate = solids[\"_silicon\"].section((0, 0, 1), origin=(0, 0, 0.05e-3)).named(\"silicon\")\n",
    "sides = cell.boundaries\n",
    "thickness = plate.size[1]\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.15e-3,\n",
    "    embedded_regions=(plate,),\n",
    "    region_sizes={\"silicon\": 40e-6},\n",
    "    hard_sizes={\"x_min\": 40e-6, \"x_max\": 40e-6, \"y_min\": 50e-6, \"y_max\": 50e-6},\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, incident wave\": sides.y_max,\n",
    "        \"port, transmitted wave\": sides.y_min,\n",
    "    },\n",
    "    labels=False,\n",
    "    title=\"One period of the etalon (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",
    "A `FrequencyDomainMaxwell` model is set up for every frequency of the sweep, 60 to 160 GHz in\n",
    "steps of 2 GHz, at normal incidence and at 45° in both polarizations. The transmittance is the\n",
    "power of the order `(1, 0)` leaving through the lower port."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = RegionwiseElectromagneticMaterial(\n",
    "    {\"silicon\": IsotropicElectromagneticMaterial(relative_permittivity=index**2)},\n",
    "    default=IsotropicElectromagneticMaterial(),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "model = lambda polarization, frequency: 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",
    "simulate = lambda model, angle: Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Etalon\",\n",
    "        geometry=cell,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            BlochPeriodicBoundary(\n",
    "                physics=model,\n",
    "                pair=PeriodicPair(sides.x_min, sides.x_max),\n",
    "                wavevector=(\n",
    "                    2 * np.pi * model.frequency / light * np.sin(np.radians(angle)),\n",
    "                    0.0,\n",
    "                    0.0,\n",
    "                ),\n",
    "            ),\n",
    "            FloquetPort(physics=model, boundary=sides.y_max, incident_amplitude=1.0),\n",
    "            FloquetPort(physics=model, boundary=sides.y_min),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=mesh,\n",
    "    numerics=numerics,\n",
    ").solve_stationary()\n",
    "transmittance = lambda polarization, angle, frequency: diffraction_efficiencies(\n",
    "    simulate(m := model(polarization, frequency), angle), m\n",
    ")[(1, 0)]\n",
    "\n",
    "frequencies = np.arange(60e9, 161e9, 2e9)\n",
    "cases = {\n",
    "    \"normal incidence\": (\"Ez\", 0.0),\n",
    "    \"45 deg, s\": (\"Ez\", 45.0),\n",
    "    \"45 deg, p\": (\"Hz\", 45.0),\n",
    "}\n",
    "spectra = {\n",
    "    name: np.array([transmittance(polarization, angle, f) for f in frequencies])\n",
    "    for name, (polarization, angle) in cases.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The computed spectra against the Airy formula, and the resonance frequencies at normal incidence,\n",
    "located by maximizing the computed transmittance around each peak of the sweep."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def airy(polarization, angle, frequency):\n",
    "    c1, c2 = np.cos(np.radians(angle)), np.sqrt(\n",
    "        1 - (np.sin(np.radians(angle)) / index) ** 2\n",
    "    )\n",
    "    a, b = (c1, index * c2) if polarization == \"Ez\" else (index * c1, c2)\n",
    "    reflectance = ((a - b) / (a + b)) ** 2\n",
    "    return 1 / (\n",
    "        1\n",
    "        + 4\n",
    "        * reflectance\n",
    "        / (1 - reflectance) ** 2\n",
    "        * np.sin(2 * np.pi * index * thickness * c2 * frequency / light) ** 2\n",
    "    )\n",
    "\n",
    "\n",
    "exact = {\n",
    "    name: airy(polarization, angle, frequencies)\n",
    "    for name, (polarization, angle) in cases.items()\n",
    "}\n",
    "print(\n",
    "    \"case                max |T - T_Airy|   min T computed   min T Airy   max T computed\"\n",
    ")\n",
    "for name in cases:\n",
    "    print(\n",
    "        f\"{name:18s}  {np.abs(spectra[name] - exact[name]).max():16.2e}   {spectra[name].min():14.5f}   {exact[name].min():10.5f}   {spectra[name].max():14.6f}\"\n",
    "    )\n",
    "\n",
    "peaks = [\n",
    "    frequencies[i]\n",
    "    for i in range(1, len(frequencies) - 1)\n",
    "    if spectra[\"normal incidence\"][i]\n",
    "    >= max(spectra[\"normal incidence\"][i - 1], spectra[\"normal incidence\"][i + 1])\n",
    "]\n",
    "refined = [\n",
    "    minimize_scalar(\n",
    "        lambda f: -transmittance(\"Ez\", 0.0, f),\n",
    "        bounds=(f - 2e9, f + 2e9),\n",
    "        method=\"bounded\",\n",
    "        options={\"xatol\": 1e6},\n",
    "    )\n",
    "    for f in peaks\n",
    "]\n",
    "spacing = light / (2 * index * thickness)\n",
    "print(f\"\\nfree spectral range c/(2nd) = {spacing / 1e9:.3f} GHz\")\n",
    "print(\n",
    "    \"order m   resonance computed [GHz]   m c/(2nd) [GHz]   difference [MHz]   T at the resonance\"\n",
    ")\n",
    "for peak in refined:\n",
    "    order = round(peak.x / spacing)\n",
    "    print(\n",
    "        f\"{order:7d}   {peak.x / 1e9:24.4f}   {order * spacing / 1e9:15.4f}   {(peak.x - order * spacing) / 1e6:16.1f}   {-peak.fun:18.6f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: the transmittance spectra with the Airy formula dashed; at 45° the round trip is shorter,\n",
    "the resonances move up, and the p wave meets weaker reflections than the s wave, so its fringes\n",
    "are shallower. Right: the field strength across the etalon at a resonance and midway between two\n",
    "resonances; the plate lies between the dashed lines."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "resonance = refined[len(refined) // 2].x\n",
    "profiles = {\n",
    "    f\"{label} ({f / 1e9:.1f} GHz)\": simulate(m := model(\"Ez\", f), 0.0).field(\n",
    "        m.electric_field\n",
    "    )\n",
    "    for label, f in (\n",
    "        (\"resonance\", resonance),\n",
    "        (\"between resonances\", resonance + spacing / 2),\n",
    "    )\n",
    "}\n",
    "y = np.linspace(0.0, cell.size[1], 601)\n",
    "line = np.column_stack((np.full_like(y, cell.size[0] / 2), y))\n",
    "fig = plots.figure(1, 2, size=(16, 5.5))\n",
    "plots.line(\n",
    "    frequencies / 1e9,\n",
    "    spectra,\n",
    "    reference=exact,\n",
    "    ylimits=(0, 1.05),\n",
    "    xlabel=\"frequency [GHz]\",\n",
    "    ylabel=\"transmittance\",\n",
    "    title=\"Silicon etalon, d = 2 mm (dashed: Airy formula)\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * y,\n",
    "    {name: np.abs(field.evaluate(line)[:, 2]) for name, field in profiles.items()},\n",
    "    vlines={\n",
    "        \"front face\": 1e3 * (cell.size[1] + thickness) / 2,\n",
    "        \"back face\": 1e3 * (cell.size[1] - thickness) / 2,\n",
    "    },\n",
    "    xlabel=\"height y [mm] (wave enters at the top)\",\n",
    "    ylabel=\"|E_z| / incident amplitude\",\n",
    "    title=\"Standing waves at and between resonances\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Coat both faces with a quarter-wave layer of higher index in the geometry script: the\n",
    "reflectance of the faces rises, the fringes become sharp lines and the etalon a narrow-band\n",
    "filter. A slightly conducting plate (`conductivity` in the material) lowers the peaks below 1."
   ]
  }
 ]
}
