{
 "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": [
    "# Band gaps of a one-dimensional photonic crystal\n",
    "\n",
    "A stack of alternating layers with permittivities $\\varepsilon_1$ and $\\varepsilon_2$, each half a\n",
    "period $a$ thick, is periodic along $x$ and uniform along $y$. Waves travelling along $x$ obey\n",
    "Bloch's theorem, $E_z(x+a)=e^{\\mathrm ik_xa}E_z(x)$, and their frequencies form bands $\\omega_n(k_x)$.\n",
    "Wherever the layers differ, gaps open at the edge of the Brillouin zone, $k_x=\\pi/a$: frequencies in\n",
    "the gap cannot propagate, and the stack is a perfect mirror there. Three cases (Joannopoulos et al.,\n",
    "*Photonic Crystals: Molding the Flow of Light*, 2nd ed., 2008, ch. 4, fig. 2):\n",
    "\n",
    "| case | $\\varepsilon_1$ | $\\varepsilon_2$ |\n",
    "|---|---|---|\n",
    "| uniform | 13 | 13 |\n",
    "| weak contrast | 13 | 12 |\n",
    "| strong contrast | 13 | 1 |\n",
    "\n",
    "OneSimulation solves the time-harmonic Maxwell equation for $E_z$ on the cross-section of one\n",
    "period and finds its eigenfrequencies with `electromagnetic_modes`:\n",
    "\n",
    "| sides | condition |\n",
    "|---|---|\n",
    "| `x_min` ↔ `x_max` | Bloch periodic with $k_x$ |\n",
    "| `y_min` ↔ `y_max` | periodic ($k_y=0$) |\n",
    "\n",
    "The unit cell comes from `one_dimensional_photonic_crystal_bands.step`, the first layer from\n",
    "`one_dimensional_photonic_crystal_bands_layer.step`; the script\n",
    "`one_dimensional_photonic_crystal_bands_geometry.py` builds both with the CAD objects of\n",
    "OneSimulation.\n",
    "\n",
    "**Reference.** The transfer matrix of one period gives the exact dispersion relation of the\n",
    "multilayer (Yeh, *Optical Waves in Layered Media*, 1988, ch. 6), with $k_i=n_i\\omega/c$ and\n",
    "$d_1=d_2=a/2$:\n",
    "\n",
    "$$\\cos k_xa=\\cos k_1d_1\\cos k_2d_2-\\frac12\\Big(\\frac{n_1}{n_2}+\\frac{n_2}{n_1}\\Big)\\sin k_1d_1\\sin k_2d_2 .$$\n",
    "\n",
    "Where the right-hand side exceeds 1 in magnitude, there is a gap."
   ]
  },
  {
   "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",
    "    FrequencyDomainMaxwell,\n",
    "    electromagnetic_modes,\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-thickness. Quadratic triangles of $a/40$ follow the layer\n",
    "interface; the periodic sides get the same nodes on both sides."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plate, layer_plate = load(\"one_dimensional_photonic_crystal_bands.step\"), load(\n",
    "    \"one_dimensional_photonic_crystal_bands_layer.step\"\n",
    ")\n",
    "cell = plate.section((0, 0, 1), origin=(0, 0, plate.size[2] / 2))\n",
    "layer = layer_plate.section((0, 0, 1), origin=(0, 0, plate.size[2] / 2)).named(\"layer\")\n",
    "a = cell.size[0]\n",
    "sides = cell.boundaries\n",
    "mesh = TriangularMesher(\n",
    "    target_size=a / 40,\n",
    "    embedded_regions=(layer,),\n",
    "    hard_sizes={side: a / 40 for side in (\"x_min\", \"x_max\", \"y_min\", \"y_max\")},\n",
    ").generate(cell)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 4.5))\n",
    "plots.geometry(\n",
    "    [plate.named(\"unit cell\"), layer_plate.named(\"layer 1\")],\n",
    "    camera=plots.Camera(elevation=55, azimuth=-70),\n",
    "    title=\"One period of the stack (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Cross-section: {mesh.cell_count} quadratic triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Bands\n",
    "\n",
    "For every case and eleven Bloch wavenumbers from the centre to the edge of the zone, the four\n",
    "lowest eigenfrequencies; the static solution at $k_x=0$ is left out."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "cases = {\n",
    "    \"uniform\": (13.0, 13.0),\n",
    "    \"weak contrast\": (13.0, 12.0),\n",
    "    \"strong contrast\": (13.0, 1.0),\n",
    "}\n",
    "material = lambda e1, e2: RegionwiseElectromagneticMaterial(\n",
    "    {\"layer\": IsotropicElectromagneticMaterial(relative_permittivity=e1)},\n",
    "    default=IsotropicElectromagneticMaterial(relative_permittivity=e2),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "wavenumbers = np.linspace(0.0, np.pi / a, 11)\n",
    "bands = {}\n",
    "for name, (e1, e2) in cases.items():\n",
    "    rows = []\n",
    "    for k in wavenumbers:\n",
    "        m = FrequencyDomainMaxwell(\n",
    "            domain=cell.domain(),\n",
    "            frequency=0.2 * light / a,\n",
    "            material=material(e1, e2),\n",
    "            polarization=\"Ez\",\n",
    "            phasor_convention=\"exp(-i*omega*t)\",\n",
    "            amplitude_convention=\"peak\",\n",
    "        )\n",
    "        result = Simulation(\n",
    "            problem=Problem(\n",
    "                name=\"Unit cell\",\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=(k, 0.0, 0.0),\n",
    "                    ),\n",
    "                    BlochPeriodicBoundary(\n",
    "                        physics=m,\n",
    "                        pair=PeriodicPair(sides.y_min, sides.y_max),\n",
    "                        wavevector=(k, 0.0, 0.0),\n",
    "                    ),\n",
    "                ),\n",
    "            ),\n",
    "            mesh=mesh,\n",
    "            numerics=numerics,\n",
    "        ).solve_stationary()\n",
    "        found = (\n",
    "            np.sort(\n",
    "                electromagnetic_modes(\n",
    "                    result, m, mode_count=6, target_frequency=0.25 * light / a\n",
    "                ).frequencies.real\n",
    "            )\n",
    "            * a\n",
    "            / light\n",
    "        )\n",
    "        rows.append(found[found > 1e-3][:4])\n",
    "    bands[name] = np.array(rows)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the exact dispersion relation\n",
    "\n",
    "For every computed pair $(k_x,\\omega)$ the mismatch in the dispersion relation, divided by its\n",
    "slope in $\\omega$, is the distance to the exact band (one Newton step); where two exact bands touch\n",
    "the slope vanishes and the point is left out. The gaps follow from where the right-hand side\n",
    "leaves $[-1, 1]$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "rhs = lambda nu, e1, e2: (\n",
    "    np.cos(np.pi * nu * np.sqrt(e1)) * np.cos(np.pi * nu * np.sqrt(e2))\n",
    "    - 0.5\n",
    "    * (np.sqrt(e1 / e2) + np.sqrt(e2 / e1))\n",
    "    * np.sin(np.pi * nu * np.sqrt(e1))\n",
    "    * np.sin(np.pi * nu * np.sqrt(e2))\n",
    ")\n",
    "grid = np.linspace(1e-4, 0.45, 45001)\n",
    "mismatch = lambda nu, k, e1, e2: rhs(nu, e1, e2) - np.cos(k * a)\n",
    "slope = (\n",
    "    lambda nu, k, e1, e2: (\n",
    "        mismatch(nu + 1e-7, k, e1, e2) - mismatch(nu - 1e-7, k, e1, e2)\n",
    "    )\n",
    "    / 2e-7\n",
    ")\n",
    "first_gap = lambda e1, e2: (\n",
    "    lambda idx: grid[\n",
    "        idx[: np.argmax(np.diff(idx) > 1) + 1] if np.any(np.diff(idx) > 1) else idx\n",
    "    ]\n",
    ")(np.flatnonzero(np.abs(rhs(grid, e1, e2)) > 1))\n",
    "print(\n",
    "    \"case              largest relative frequency error   first gap (FEM)       first gap (exact)     gap / midgap (FEM)\"\n",
    ")\n",
    "for name, (e1, e2) in cases.items():\n",
    "    k = wavenumbers[:, None] * np.ones_like(bands[name])\n",
    "    steep = np.abs(slope(bands[name], k, e1, e2)) > 1e-2\n",
    "    error = np.max(\n",
    "        np.abs(mismatch(bands[name], k, e1, e2) / slope(bands[name], k, e1, e2))[steep]\n",
    "        / bands[name][steep]\n",
    "    )\n",
    "    exact = first_gap(e1, e2)\n",
    "    computed = (bands[name][-1, 0], bands[name][-1, 1])\n",
    "    print(\n",
    "        f\"{name:16s} {error:30.1e}   {computed[0]:.4f} - {computed[1]:.4f}       \"\n",
    "        + (\n",
    "            f\"{exact.min():.4f} - {exact.max():.4f}\"\n",
    "            if exact.size\n",
    "            else \"none           \"\n",
    "        )\n",
    "        + f\"       {2 * (computed[1] - computed[0]) / (computed[1] + computed[0]):9.2%}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The bands of the three cases (markers) on the exact dispersion relation (lines), in the\n",
    "normalized frequency $\\omega a/2\\pi c$; the gaps lie between the bands at the zone edge."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "curves = {\n",
    "    name: (\n",
    "        lambda e1, e2: (\n",
    "            np.arccos(np.clip(rhs(grid, e1, e2), -1, 1)) / np.pi,\n",
    "            np.where(np.abs(rhs(grid, e1, e2)) <= 1, grid, np.nan),\n",
    "        )\n",
    "    )(*cases[name])\n",
    "    for name in cases\n",
    "}\n",
    "fig = plots.figure(1, 3, size=(20, 6))\n",
    "for panel, name in enumerate(cases):\n",
    "    plots.line(\n",
    "        points={\n",
    "            \"FEM bands\": (np.repeat(wavenumbers * a / np.pi, 4), bands[name].ravel())\n",
    "        },\n",
    "        reference={\"exact dispersion relation\": curves[name]},\n",
    "        ylimits=(0, 0.45),\n",
    "        xlabel=\"k_x a / pi\",\n",
    "        ylabel=\"omega a / 2 pi c\",\n",
    "        title=f\"{name}: epsilon {cases[name][0]:.0f} / {cases[name][1]:.0f}\",\n",
    "        legend=\"upper left\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Give the layers different thicknesses in `one_dimensional_photonic_crystal_bands_geometry.py`: the\n",
    "quarter-wave stack $n_1d_1=n_2d_2$ has the widest gap for a given contrast. A nonzero $k_y$ in the\n",
    "second Bloch condition gives the bands of oblique propagation, and `polarization=\"Hz\"` those of\n",
    "the other polarization."
   ]
  }
 ]
}
