{
 "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": [
    "# Dielectric slab waveguide\n",
    "\n",
    "A slab of thickness $d=4$ mm and index $n_1=1.5$ in air ($n_2=1$) guides a wave whose field\n",
    "decays exponentially outside the slab. A guided mode $u(y)\\,e^{\\mathrm i\\beta x}$ has a\n",
    "propagation constant between the wavenumbers of air and of the slab, $k_0<\\beta<n_1k_0$; its\n",
    "effective index is $n_\\text{eff}=\\beta/k_0$. TE modes have the electric field $E_z$ out of the\n",
    "section, TM modes the magnetic field $H_z$.\n",
    "\n",
    "Two models on the section:\n",
    "\n",
    "* **Mode analysis.** A segment 0.5 mm long with Bloch periodic ends carries the field\n",
    "  $u(x+L)=u(x)e^{\\mathrm i\\beta L}$; metal walls 12 mm from the axis close it, far outside the\n",
    "  guided fields. For each $\\beta$ the resonance frequencies of this segment below the light line\n",
    "  of air are the frequencies of the guided modes.\n",
    "* **Propagation.** A line current on the axis of a 100 mm long piece excites the TE$_0$ mode\n",
    "  at 60 GHz; perfectly matched layers around the piece absorb what leaves it.\n",
    "\n",
    "| boundary | mode analysis | propagation |\n",
    "|---|---|---|\n",
    "| `x_min`, `x_max` | Bloch periodic, phase $\\beta L$ | perfect conductor behind a PML of 12 mm |\n",
    "| `y_min`, `y_max` | perfect electric conductor | perfect conductor behind a PML of 5 mm |\n",
    "\n",
    "**Reference** (D. Marcuse, *Theory of Dielectric Optical Waveguides*, 2nd ed., §1.3; K. Okamoto,\n",
    "*Fundamentals of Optical Waveguides*, 2nd ed., §2.1). With $\\kappa=\\sqrt{n_1^2k_0^2-\\beta^2}$ and\n",
    "$\\gamma=\\sqrt{\\beta^2-n_2^2k_0^2}$ the modes of order $m$ satisfy\n",
    "\n",
    "$$\\kappa d=m\\pi+2\\arctan\\Big(p\\,\\frac{\\gamma}{\\kappa}\\Big),\\qquad p=1\\ \\text{(TE)},\\qquad\n",
    "  p=\\frac{n_1^2}{n_2^2}\\ \\text{(TM)} .$$"
   ]
  },
  {
   "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",
    "    FrequencyDomainMaxwell,\n",
    "    PerfectElectricConductor,\n",
    "    harmonic_resonances,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.optimize import brentq\n",
    "\n",
    "theme.set()\n",
    "\n",
    "core_index = 1.5\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 long piece with its slab and the periodic segment with its slab; `section`\n",
    "cuts them at half thickness. Quadratic triangles of 0.25 mm (segment) or 0.4 mm (long piece) in the\n",
    "slab and 0.5 mm or 1.2 mm in the air; the ends of the segment are divided alike so that their nodes\n",
    "match."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "solids = {\n",
    "    name: load(f\"dielectric_slab_waveguide_modes{name}.step\")\n",
    "    for name in (\"\", \"_core\", \"_cell\", \"_cell_core\")\n",
    "}\n",
    "section = lambda name: solids[name].section((0, 0, 1), origin=(0, 0, 0.5e-3))\n",
    "piece, cell = section(\"\"), section(\"_cell\")\n",
    "core, cell_core = section(\"_core\").named(\"core\"), section(\"_cell_core\").named(\"core\")\n",
    "thickness = core.size[1]\n",
    "ends = {\"x_min\": 0.125e-3, \"x_max\": 0.125e-3}\n",
    "cell_mesh = TriangularMesher(\n",
    "    target_size=0.5e-3,\n",
    "    embedded_regions=(cell_core,),\n",
    "    region_sizes={\"core\": 0.25e-3},\n",
    "    hard_sizes=ends,\n",
    ").generate(cell)\n",
    "mesh = TriangularMesher(\n",
    "    target_size=1.2e-3, embedded_regions=(core,), region_sizes={\"core\": 0.4e-3}\n",
    ").generate(piece)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(16, 4.5))\n",
    "plots.geometry(\n",
    "    piece,\n",
    "    selection={\"metal behind the absorbing layers\": piece.boundaries.all},\n",
    "    labels=False,\n",
    "    title=\"Air around the long piece of the slab (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": [
    "## Mode analysis\n",
    "\n",
    "For each propagation constant the segment is assembled with the Bloch phase of its ends and\n",
    "`harmonic_resonances` returns its lowest resonances; those below the light line of air,\n",
    "$f<c\\beta/2\\pi$, are guided modes. The segment is so short that the periodic images $\\beta-2\\pi/L$ of the modes lie\n",
    "far above the frequencies studied."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = RegionwiseElectromagneticMaterial(\n",
    "    {\"core\": IsotropicElectromagneticMaterial(relative_permittivity=core_index**2)},\n",
    "    default=IsotropicElectromagneticMaterial(),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "models = {\n",
    "    polarization: FrequencyDomainMaxwell(\n",
    "        domain=cell.domain(),\n",
    "        frequency=50e9,\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",
    "segment = lambda polarization, beta: harmonic_resonances(\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Slab segment\",\n",
    "            geometry=cell,\n",
    "            physics=(models[polarization],),\n",
    "            boundary_conditions=(\n",
    "                BlochPeriodicBoundary(\n",
    "                    physics=models[polarization],\n",
    "                    pair=PeriodicPair(cell.boundaries.x_min, cell.boundaries.x_max),\n",
    "                    wavevector=(beta, 0.0, 0.0),\n",
    "                ),\n",
    "                PerfectElectricConductor(\n",
    "                    physics=models[polarization],\n",
    "                    boundary=cell.boundaries.y_min | cell.boundaries.y_max,\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=cell_mesh,\n",
    "        numerics=numerics,\n",
    "    ).solve_stationary(),\n",
    "    models[polarization],\n",
    "    count=8,\n",
    "    near=1e9,\n",
    ")\n",
    "betas = np.linspace(600.0, 3000.0, 9)\n",
    "guided = {\n",
    "    (polarization, beta): [\n",
    "        f.real\n",
    "        for f in segment(polarization, beta)\n",
    "        if f.real < light * beta / (2 * np.pi)\n",
    "    ]\n",
    "    for polarization in (\"Ez\", \"Hz\")\n",
    "    for beta in betas\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The exact dispersion relation is solved for the frequency at each $\\beta$ and compared mode by\n",
    "mode."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "exact_k0 = lambda beta, order, p: brentq(\n",
    "    lambda k: np.sqrt(core_index**2 * k**2 - beta**2) * thickness\n",
    "    - order * np.pi\n",
    "    - 2\n",
    "    * np.arctan(p * np.sqrt(beta**2 - k**2) / np.sqrt(core_index**2 * k**2 - beta**2)),\n",
    "    beta / core_index * (1 + 1e-12),\n",
    "    beta * (1 - 1e-12),\n",
    ")\n",
    "ratio = {\"Ez\": 1.0, \"Hz\": core_index**2}\n",
    "names = {\"Ez\": \"TE\", \"Hz\": \"TM\"}\n",
    "exact = {\n",
    "    (polarization, beta): [\n",
    "        light * exact_k0(beta, m, ratio[polarization]) / (2 * np.pi)\n",
    "        for m in range(4)\n",
    "        if beta * thickness * np.sqrt(core_index**2 - 1) > m * np.pi\n",
    "    ]\n",
    "    for polarization, beta in guided\n",
    "}\n",
    "print(\n",
    "    \"beta [rad/m]   mode   f computed [GHz]   f exact [GHz]   n_eff computed   n_eff exact   rel. difference\"\n",
    ")\n",
    "for (polarization, beta), found in guided.items():\n",
    "    for m, (computed, reference) in enumerate(zip(found, exact[(polarization, beta)])):\n",
    "        print(\n",
    "            f\"{beta:12.0f}   {names[polarization]}{m}    {computed / 1e9:16.4f}   {reference / 1e9:13.4f}   \"\n",
    "            f\"{light * beta / (2 * np.pi * computed):14.5f}   {light * beta / (2 * np.pi * reference):11.5f}   {abs(computed / reference - 1):15.1e}\"\n",
    "        )\n",
    "print(\n",
    "    f\"largest relative frequency error over all modes: \"\n",
    "    f\"{max(abs(c / r - 1) for key in guided for c, r in zip(guided[key], exact[key])):.1e}; \"\n",
    "    f\"modes found {sum(len(v) for v in guided.values())}, modes predicted {sum(len(v) for v in exact.values())}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "All modes agree with the dispersion relation to a few parts in $10^4$, the higher ones near their\n",
    "cutoff to about $10^{-3}$, where their fields reach out to the metal walls of the segment. The\n",
    "walls also hold a mode or two right below the light line that the open slab no longer guides; they\n",
    "are the modes found beyond the prediction.\n",
    "\n",
    "## Propagation of the fundamental mode\n",
    "\n",
    "A narrow Gaussian line current $J_z$ on the axis, 25 mm from the left end (13 mm from the layer), radiates into the\n",
    "slab and into the air. The damping of the PML grows quadratically into the layers. Along the\n",
    "axis, beyond 20 mm from the source, the field is the TE$_0$ mode plus a decaying radiated part;\n",
    "the slope of its phase is the propagation constant."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "frequency = 60e9\n",
    "omega = 2 * np.pi * frequency\n",
    "length, height = piece.size[0], piece.size[1]\n",
    "damping = lambda x, y, z: np.column_stack(\n",
    "    (\n",
    "        3\n",
    "        * omega\n",
    "        * np.clip((np.abs(x - length / 2) - (length / 2 - 0.012)) / 0.012, 0, None)\n",
    "        ** 2,\n",
    "        3 * omega * np.clip((np.abs(y) - (height / 2 - 0.005)) / 0.005, 0, None) ** 2,\n",
    "        0 * x,\n",
    "    )\n",
    ")\n",
    "source = lambda x, y, z: np.column_stack(\n",
    "    (0 * x, 0 * x, np.exp(-((x - 0.025) ** 2 + y**2) / (2 * 0.4e-3**2)))\n",
    ").astype(complex)\n",
    "model = FrequencyDomainMaxwell(\n",
    "    domain=piece.domain(),\n",
    "    frequency=frequency,\n",
    "    material=CartesianPML(material=material, damping=damping),\n",
    "    polarization=\"Ez\",\n",
    "    impressed_current=source,\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "field = (\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Slab waveguide\",\n",
    "            geometry=piece,\n",
    "            physics=(model,),\n",
    "            boundary_conditions=(\n",
    "                PerfectElectricConductor(physics=model, boundary=piece.boundaries.all),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=numerics,\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(model.electric_field)\n",
    ")\n",
    "axis = np.linspace(0.045, 0.085, 161)\n",
    "values = field.evaluate(np.column_stack((axis, 0 * axis)))[:, 2]\n",
    "beta = np.polyfit(axis, np.unwrap(np.angle(values)), 1)[0]\n",
    "k0 = omega / light\n",
    "exact_beta = brentq(\n",
    "    lambda b: exact_k0(b, 0, 1.0) - k0, k0 * (1 + 1e-9), core_index * k0 * (1 - 1e-9)\n",
    ")\n",
    "print(\n",
    "    f\"\\nTE0 at {frequency / 1e9:.0f} GHz: n_eff from the phase along the axis {beta / k0:.5f}, exact {exact_beta / k0:.5f} \"\n",
    "    f\"(difference {abs(beta / exact_beta - 1):.1e}); the amplitude along the axis varies by {np.ptp(np.abs(values)) / np.abs(values).mean():.1%}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: the dispersion diagram, frequency against propagation constant, with the exact curves\n",
    "dashed between the light lines of air and of the slab. Right: the field of the line source at\n",
    "60 GHz; the guided mode runs along the slab, the radiated waves are absorbed in the layers."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = np.linspace(400.0, 3000.0, 200)\n",
    "curves = {\n",
    "    f\"{names[p]}{m}\": (\n",
    "        fine[fine * thickness * np.sqrt(core_index**2 - 1) > m * np.pi],\n",
    "        [\n",
    "            light * exact_k0(b, m, ratio[p]) / (2 * np.pi) / 1e9\n",
    "            for b in fine\n",
    "            if b * thickness * np.sqrt(core_index**2 - 1) > m * np.pi\n",
    "        ],\n",
    "    )\n",
    "    for p in (\"Ez\", \"Hz\")\n",
    "    for m in range(3)\n",
    "}\n",
    "found = {\n",
    "    f\"{names[p]}{m}\": (\n",
    "        np.array([b for b in betas if len(guided[(p, b)]) > m]),\n",
    "        np.array([guided[(p, b)][m] / 1e9 for b in betas if len(guided[(p, b)]) > m]),\n",
    "    )\n",
    "    for p in (\"Ez\", \"Hz\")\n",
    "    for m in range(3)\n",
    "}\n",
    "x, y = np.asarray(mesh.coordinates).T\n",
    "fig = plots.figure(1, 2, size=(17, 5.5))\n",
    "plots.line(\n",
    "    points=found,\n",
    "    reference=curves\n",
    "    | {\n",
    "        \"light line, air\": (fine, light * fine / (2 * np.pi) / 1e9),\n",
    "        \"light line, slab\": (fine, light * fine / (2 * np.pi * core_index) / 1e9),\n",
    "    },\n",
    "    xlabel=\"propagation constant beta [rad/m]\",\n",
    "    ylabel=\"frequency [GHz]\",\n",
    "    title=\"Dispersion of the slab modes (dashed: exact)\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.heatmap(\n",
    "    1e3 * x,\n",
    "    1e3 * y,\n",
    "    field.evaluate(np.column_stack((x, y)))[:, 2].real,\n",
    "    triangles=np.asarray(mesh.cells),\n",
    "    colormap=\"diverging\",\n",
    "    centre=0.0,\n",
    "    limits=(-np.abs(values).max(), np.abs(values).max()),\n",
    "    label=\"Re E_z [V/m]\",\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"y [mm]\",\n",
    "    title=\"Line source in the slab, 60 GHz\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the slab thinner or the frequency lower until only the fundamental modes are left (single\n",
    "mode below $V=k_0\\tfrac d2\\sqrt{n_1^2-n_2^2}<\\pi/2$), or move the source off the axis to excite\n",
    "the odd TE$_1$ mode as well and see the beating of the two modes along the slab."
   ]
  }
 ]
}
