{
 "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": [
    "# Photonic crystal: band gap and bent waveguide\n",
    "\n",
    "Alumina rods ($\\varepsilon_r=8.9$) of radius $r=0.2a$ stand on a square lattice of period\n",
    "$a=10$ mm. For waves with the electric field along the rods (TM, $E_z$ out of the section) the\n",
    "periodic structure has a complete band gap: no wave of a frequency in the gap can travel through\n",
    "the crystal in any direction. A line of missing rods is then a waveguide whose walls are perfect\n",
    "mirrors, and it can bend sharply without losing the wave.\n",
    "\n",
    "Three models on sections of the STEP parts:\n",
    "\n",
    "* **Bands.** On the unit cell the field is Bloch periodic,\n",
    "  $u(\\mathbf x+\\mathbf a)=u(\\mathbf x)\\,e^{\\mathrm i\\mathbf k\\cdot\\mathbf a}$, and for every\n",
    "  wavevector $\\mathbf k$ along the edge $\\Gamma\\!-\\!X\\!-\\!M\\!-\\!\\Gamma$ of the irreducible Brillouin\n",
    "  zone the resonances of the cell are the frequencies of the bands.\n",
    "* **Transmission.** One period of a slab seven rows thick, with Bloch periodic sides and Floquet\n",
    "  ports above and below, transmits a plane wave travelling along $\\Gamma X$.\n",
    "* **Bent waveguide.** In an 11 x 11 crystal a row and a column of rods are missing; a line\n",
    "  current sits in the horizontal arm, and perfectly matched layers absorb what leaves the crystal.\n",
    "\n",
    "| model | boundaries |\n",
    "|---|---|\n",
    "| unit cell | `x_min`/`x_max` and `y_min`/`y_max` Bloch periodic with $\\mathbf k$ |\n",
    "| slab | `x_min`/`x_max` periodic, `y_max` Floquet port with the incident wave, `y_min` Floquet port |\n",
    "| crystal | perfect conductor behind a PML of 15 mm |\n",
    "\n",
    "**Reference.** J. D. Joannopoulos, S. G. Johnson, J. N. Winn and R. D. Meade, *Photonic\n",
    "Crystals: Molding the Flow of Light*, 2nd ed., Princeton 2008, chapter 5: this lattice of\n",
    "dielectric columns ($\\varepsilon=8.9$, $r=0.2a$) has a complete TM gap between the first and the\n",
    "second band, from $\\omega a/2\\pi c\\approx0.32$ to $0.44$ (31 % of the midgap frequency), and no\n",
    "TE gap. Along $\\Gamma X$ alone the stop band of the slab must open between the first and the\n",
    "second band at $X$."
   ]
  },
  {
   "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",
    "    CartesianPML,\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",
    "    PerfectElectricConductor,\n",
    "    diffraction_efficiencies,\n",
    "    harmonic_resonances,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()\n",
    "\n",
    "a = 0.01\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 three air regions and their rods; `section` cuts the air at half thickness and\n",
    "`sections` returns the separate discs of the rods. The meshes follow the rods; the sides of the unit cell and of the slab period are divided alike so\n",
    "that the nodes of periodic sides match."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "solids = {\n",
    "    name: load(f\"photonic_crystal_band_gap{name}.step\")\n",
    "    for name in (\"\", \"_rods\", \"_cell\", \"_cell_rod\", \"_column\", \"_column_rods\")\n",
    "}\n",
    "section = lambda name: solids[name].section((0, 0, 1), origin=(0, 0, 0.5e-3))\n",
    "cell, column, crystal = section(\"_cell\"), section(\"_column\"), section(\"\")\n",
    "rods = {\n",
    "    name: tuple(\n",
    "        piece.named(\"rods\")\n",
    "        for piece in solids[name].sections((0, 0, 1), origin=(0, 0, 0.5e-3))\n",
    "    )\n",
    "    for name in (\"_cell_rod\", \"_column_rods\", \"_rods\")\n",
    "}\n",
    "meshes = {\n",
    "    \"cell\": TriangularMesher(\n",
    "        target_size=0.5e-3,\n",
    "        embedded_regions=rods[\"_cell_rod\"],\n",
    "        region_sizes={\"rods\": 0.4e-3},\n",
    "        curvature_angle=0.5,\n",
    "        hard_sizes={side: 0.5e-3 for side in (\"x_min\", \"x_max\", \"y_min\", \"y_max\")},\n",
    "    ).generate(cell),\n",
    "    \"slab\": TriangularMesher(\n",
    "        target_size=1.5e-3,\n",
    "        embedded_regions=rods[\"_column_rods\"],\n",
    "        region_sizes={\"rods\": 0.8e-3},\n",
    "        curvature_angle=0.5,\n",
    "        hard_sizes={\"x_min\": 1.5e-3, \"x_max\": 1.5e-3},\n",
    "    ).generate(column),\n",
    "    \"crystal\": TriangularMesher(\n",
    "        target_size=3e-3,\n",
    "        embedded_regions=rods[\"_rods\"],\n",
    "        region_sizes={\"rods\": 1.1e-3},\n",
    "        curvature_angle=0.5,\n",
    "        minimum_size=0.6e-3,\n",
    "        grading=0.5,\n",
    "    ).generate(crystal),\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(15, 7))\n",
    "plots.geometry(\n",
    "    [solids[\"\"].named(\"air\"), solids[\"_rods\"].named(\"alumina rods\")],\n",
    "    camera=plots.Camera(elevation=70, azimuth=-80),\n",
    "    title=\"Crystal with a bent line defect (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"crystal\"],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"{meshes['crystal'].cell_count} quadratic triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Band structure\n",
    "\n",
    "16 wavevectors along $\\Gamma\\!-\\!X\\!-\\!M\\!-\\!\\Gamma$; at each the four lowest resonances of the\n",
    "cell for both polarizations. The path stops 3 % short of $\\Gamma$, where the first band\n",
    "starts at zero frequency."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = RegionwiseElectromagneticMaterial(\n",
    "    {\"rods\": IsotropicElectromagneticMaterial(relative_permittivity=8.9)},\n",
    "    default=IsotropicElectromagneticMaterial(),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "model = lambda region, polarization, frequency, medium=material, **options: FrequencyDomainMaxwell(\n",
    "    domain=region.domain(),\n",
    "    frequency=frequency,\n",
    "    material=medium,\n",
    "    polarization=polarization,\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    "    **options,\n",
    ")\n",
    "corners = np.array([[0.03, 0.0], [1.0, 0.0], [1.0, 1.0], [0.03, 0.03]]) * np.pi / a\n",
    "path = np.concatenate(\n",
    "    [np.linspace(corners[i], corners[i + 1], 6)[:-1] for i in range(3)] + [corners[-1:]]\n",
    ")\n",
    "cell_sides = cell.boundaries\n",
    "cell_problem = lambda m, k: Problem(\n",
    "    name=\"Unit cell\",\n",
    "    geometry=cell,\n",
    "    physics=(m,),\n",
    "    boundary_conditions=tuple(\n",
    "        BlochPeriodicBoundary(\n",
    "            physics=m,\n",
    "            pair=PeriodicPair(cell_sides[f\"{axis}_min\"], cell_sides[f\"{axis}_max\"]),\n",
    "            wavevector=(*k, 0.0),\n",
    "        )\n",
    "        for axis in \"xy\"\n",
    "    ),\n",
    ")\n",
    "resonances = lambda m, k: harmonic_resonances(\n",
    "    Simulation(\n",
    "        problem=cell_problem(m, k), mesh=meshes[\"cell\"], numerics=numerics\n",
    "    ).solve_stationary(),\n",
    "    m,\n",
    "    count=6,\n",
    "    near=1e8,\n",
    ")\n",
    "bands = {\n",
    "    polarization: np.array(\n",
    "        [\n",
    "            [f.real * a / light for f in resonances(m, k) if f.real * a / light > 1e-3][\n",
    "                :4\n",
    "            ]\n",
    "            for k in path\n",
    "            for m in [model(cell, polarization, 10e9)]\n",
    "        ]\n",
    "    )\n",
    "    for polarization in (\"Ez\", \"Hz\")\n",
    "}\n",
    "gap = (bands[\"Ez\"][:, 0].max(), bands[\"Ez\"][:, 1].min())\n",
    "print(\n",
    "    f\"TM: band 1 up to {gap[0]:.4f}, band 2 from {gap[1]:.4f} (omega a / 2 pi c): complete gap {gap[0]:.3f} - {gap[1]:.3f}, \"\n",
    "    f\"{2 * (gap[1] - gap[0]) / (gap[1] + gap[0]):.1%} of midgap (reference about 0.32 - 0.44, 31 %)\"\n",
    ")\n",
    "print(\n",
    "    f\"TE: band 1 up to {bands['Hz'][:, 0].max():.4f}, band 2 from {bands['Hz'][:, 1].min():.4f}: \"\n",
    "    f\"{'no complete gap' if bands['Hz'][:, 1].min() < bands['Hz'][:, 0].max() else 'gap'}\"\n",
    ")\n",
    "print(\n",
    "    f\"at X: TM bands 1 and 2 at {bands['Ez'][5, 0]:.4f} and {bands['Ez'][5, 1]:.4f}, TE at {bands['Hz'][5, 0]:.4f} and {bands['Hz'][5, 1]:.4f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Transmission through seven rows\n",
    "\n",
    "The slab period is swept for the TM wave in normalized frequency from 0.15 to 0.59 in steps of\n",
    "0.02, with the wave at normal incidence ($\\Gamma X$)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "normalized = np.arange(0.15, 0.6001, 0.02)\n",
    "slab_sides = column.boundaries\n",
    "slab_problem = lambda m: Problem(\n",
    "    name=\"Seven rows\",\n",
    "    geometry=column,\n",
    "    physics=(m,),\n",
    "    boundary_conditions=(\n",
    "        BlochPeriodicBoundary(\n",
    "            physics=m,\n",
    "            pair=PeriodicPair(slab_sides.x_min, slab_sides.x_max),\n",
    "            wavevector=(0.0, 0.0, 0.0),\n",
    "        ),\n",
    "        FloquetPort(physics=m, boundary=slab_sides.y_max, incident_amplitude=1.0),\n",
    "        FloquetPort(physics=m, boundary=slab_sides.y_min),\n",
    "    ),\n",
    ")\n",
    "transmitted = lambda m: diffraction_efficiencies(\n",
    "    Simulation(\n",
    "        problem=slab_problem(m), mesh=meshes[\"slab\"], numerics=numerics\n",
    "    ).solve_stationary(),\n",
    "    m,\n",
    ")[(1, 0)]\n",
    "transmission = np.array(\n",
    "    [transmitted(model(column, \"Ez\", nu * light / a)) for nu in normalized]\n",
    ")\n",
    "blocked = normalized[transmission < 1e-2]\n",
    "print(\n",
    "    f\"TM: transmission below 1 % from {blocked.min():.2f} to {blocked.max():.2f} (sweep step 0.02); stop band at X from the bands \"\n",
    "    f\"{bands['Ez'][5, 0]:.3f} - {bands['Ez'][5, 1]:.3f}; smallest transmission {transmission.min():.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Bent waveguide\n",
    "\n",
    "A Gaussian line current in the horizontal arm, at a frequency inside the TM gap (0.38). The damping of the PML grows quadratically over the outer 15 mm. The intensity at the\n",
    "end of the vertical arm is compared with that at the same distance from the centre on the right,\n",
    "where the crystal is intact."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "damping = lambda omega: (\n",
    "    lambda x, y, z: np.column_stack(\n",
    "        (\n",
    "            3 * omega * np.clip((np.abs(x) - 6.5 * a) / (1.5 * a), 0, None) ** 2,\n",
    "            3 * omega * np.clip((np.abs(y) - 6.5 * a) / (1.5 * a), 0, None) ** 2,\n",
    "            0 * x,\n",
    "        )\n",
    "    )\n",
    ")\n",
    "source = lambda x, y, z: np.column_stack(\n",
    "    (0 * x, 0 * x, np.exp(-((x + 3 * a) ** 2 + y**2) / (2 * (0.1 * a) ** 2)))\n",
    ").astype(complex)\n",
    "crystal_problem = lambda m: Problem(\n",
    "    name=\"Bent waveguide\",\n",
    "    geometry=crystal,\n",
    "    physics=(m,),\n",
    "    boundary_conditions=(\n",
    "        PerfectElectricConductor(physics=m, boundary=crystal.boundaries.all),\n",
    "    ),\n",
    ")\n",
    "source_field = (\n",
    "    lambda m: Simulation(\n",
    "        problem=crystal_problem(m), mesh=meshes[\"crystal\"], numerics=numerics\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(m.electric_field)\n",
    ")\n",
    "fields = {\n",
    "    nu: source_field(\n",
    "        model(\n",
    "            crystal,\n",
    "            \"Ez\",\n",
    "            nu * light / a,\n",
    "            medium=CartesianPML(\n",
    "                material=material, damping=damping(2 * np.pi * nu * light / a)\n",
    "            ),\n",
    "            impressed_current=source,\n",
    "        )\n",
    "    )\n",
    "    for nu in (0.38,)\n",
    "}\n",
    "probe = lambda field, centre: np.mean(\n",
    "    np.abs(\n",
    "        field.evaluate(\n",
    "            np.asarray(centre)\n",
    "            + 0.4 * a * np.random.default_rng(1).uniform(-1, 1, (50, 2))\n",
    "        )[:, 2]\n",
    "    )\n",
    "    ** 2\n",
    ")\n",
    "for nu, field in fields.items():\n",
    "    print(\n",
    "        f\"omega a / 2 pi c = {nu}: intensity at the end of the bent arm / on the right of the crystal = \"\n",
    "        f\"{10 * np.log10(probe(field, (0.0, 6.0 * a)) / probe(field, (6.0 * a, 0.0))):+.1f} dB\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The band diagram with the complete TM gap, the transmission of the seven rows on a logarithmic\n",
    "scale with the band edges at $X$ marked, and the field of the source inside the gap."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(24, 7))\n",
    "plots.line(\n",
    "    np.arange(len(path)),\n",
    "    {f\"TM band {n + 1}\": bands[\"Ez\"][:, n] for n in range(4)}\n",
    "    | {f\"TE band {n + 1}\": bands[\"Hz\"][:, n] for n in range(2)},\n",
    "    hlines={\"top of TM band 1\": gap[0], \"bottom of TM band 2\": gap[1]},\n",
    "    vlines={\"X\": 5, \"M\": 10},\n",
    "    xlabel=\"wavevector along Gamma - X - M - Gamma\",\n",
    "    ylabel=\"omega a / 2 pi c\",\n",
    "    title=\"Band structure of the rod lattice\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    normalized,\n",
    "    {\"TM (E_z)\": transmission},\n",
    "    scale=\"logy\",\n",
    "    ylimits=(1e-6, 2),\n",
    "    vlines={\"TM band 1 at X\": bands[\"Ez\"][5, 0], \"TM band 2 at X\": bands[\"Ez\"][5, 1]},\n",
    "    xlabel=\"omega a / 2 pi c\",\n",
    "    ylabel=\"transmittance\",\n",
    "    title=\"Seven rows, normal incidence\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "for panel, (nu, field) in zip((fig[2],), fields.items()):\n",
    "    x, y = np.asarray(meshes[\"crystal\"].coordinates).T\n",
    "    values = np.abs(field.evaluate(np.column_stack((x, y)))[:, 2])\n",
    "    plots.heatmap(\n",
    "        x / a,\n",
    "        y / a,\n",
    "        values,\n",
    "        triangles=np.asarray(meshes[\"crystal\"].cells),\n",
    "        limits=(0, np.percentile(values, 99)),\n",
    "        label=\"|E_z| [V/m]\",\n",
    "        xlabel=\"x / a\",\n",
    "        ylabel=\"y / a\",\n",
    "        title=f\"Line source, omega a / 2 pi c = {nu}\",\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Remove a single rod inside the intact crystal: the defect holds a localized mode whose\n",
    "frequency lies in the gap and can be found with `harmonic_resonances` on the crystal with metal\n",
    "walls. Change the rod radius in `photonic_crystal_band_gap_geometry.py` to see how the gap opens\n",
    "and closes."
   ]
  }
 ]
}
