{
 "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": [
    "# Hyperbolic waves in a layered metamaterial\n",
    "\n",
    "Layers much thinner than the wavelength act on light like one anisotropic medium. For a fill\n",
    "fraction $f$ of metal ($\\varepsilon_m$) in a dielectric ($\\varepsilon_d$) the effective\n",
    "permittivity along and across the layers is\n",
    "\n",
    "$$\\varepsilon_\\parallel=f\\varepsilon_m+(1-f)\\varepsilon_d,\\qquad\n",
    "  \\varepsilon_\\perp=\\frac{\\varepsilon_m\\varepsilon_d}{f\\varepsilon_d+(1-f)\\varepsilon_m}.$$\n",
    "\n",
    "With silver at 800 nm ($\\varepsilon_m\\approx-30+0.5\\mathrm i$, Drude model) and a dielectric of\n",
    "$\\varepsilon_d=4$ at $f=1/2$, $\\varepsilon_\\parallel<0<\\varepsilon_\\perp$: TM waves obey\n",
    "$k_x^2/\\varepsilon_\\perp+k_y^2/\\varepsilon_\\parallel=k_0^2$, a hyperbola instead of an ellipse. Waves\n",
    "of arbitrarily large wavenumber propagate, and a point-like source launches its energy along the\n",
    "asymptotes of the hyperbola: two narrow beams (resonance cones) at\n",
    "$\\tan\\theta=\\sqrt{-\\varepsilon_\\parallel/\\varepsilon_\\perp}$ from the normal of the layers.\n",
    "\n",
    "Both studies solve the in-plane electric field (polarization `Exy`, Nédélec elements, TM light).\n",
    "\n",
    "| study | boundary | condition |\n",
    "|---|---|---|\n",
    "| one period | `x_min`, `x_max` | Bloch-periodic, $k_x=k_0\\sin\\theta$ |\n",
    "| one period | `y_max`, `y_min` | Floquet ports, the plane wave fed from above |\n",
    "| source | all outer faces (behind the absorbing layers) | perfect electric conductor |\n",
    "\n",
    "**Reference** (P. Yeh, *Optical Waves in Layered Media*, Wiley 1988, §5.1 and §6.2; A. Poddubny\n",
    "et al., *Nature Photonics* 7, 948 (2013)). The exact reflectance and transmittance of the finite\n",
    "stack follow from the characteristic matrices of its 16 layers; the cone angle from the effective\n",
    "permittivities is an approximation that holds when the period is much smaller than the wavelength\n",
    "of the waves that form the cone.\n",
    "\n",
    "The STEP parts are drawn in micrometres; `scaled` brings the meshes to metres, so the models are\n",
    "solved in SI units and the plots show micrometres again."
   ]
  },
  {
   "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",
    "    DrudeElectromagneticMaterial,\n",
    "    IsotropicElectromagneticMaterial,\n",
    "    RegionwiseElectromagneticMaterial,\n",
    ")\n",
    "from onesim.meshing import PeriodicPair, TriangularMesher, scaled\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 (\n",
    "    BlochPeriodicBoundary,\n",
    "    FloquetPort,\n",
    "    FrequencyDomainMaxwell,\n",
    "    PerfectElectricConductor,\n",
    "    diffraction_efficiencies,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()\n",
    "\n",
    "wavelength, dielectric, layer, pairs, um = 800e-9, 4.0, 20e-9, 8, 1e-6\n",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\n",
    "frequency, k0 = light / wavelength, 2 * np.pi / wavelength\n",
    "silver = DrudeElectromagneticMaterial(\n",
    "    plasma_frequency=1.37e16, collision_rate=3.2e13, high_frequency_permittivity=3.7\n",
    ")\n",
    "metal = silver.relative_permittivity_at(frequency)\n",
    "parallel = 0.5 * (metal + dielectric)\n",
    "across = metal * dielectric / (0.5 * dielectric + 0.5 * metal)\n",
    "print(\n",
    "    f\"silver at 800 nm: eps_m = {metal:.3f}; effective eps_parallel = {parallel:.3f}, eps_perp = {across:.3f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the period cell and the section with their silver and dielectric layers and the\n",
    "source; `sections` cuts them at half thickness, every layer a piece of its own. Quadratic triangles of 6 nm in the layers of the\n",
    "cell (10 nm in the section) and up to 50 nm in the air; the periodic sides are meshed alike."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "pieces = lambda name: load(f\"hyperbolic_metamaterial_layers{name}.step\").sections(\n",
    "    (0, 0, 1), origin=(0, 0, 0.05)\n",
    ")\n",
    "layers = lambda prefix: tuple(\n",
    "    piece.named(kind)\n",
    "    for kind in (\"metal\", \"dielectric\")\n",
    "    for piece in pieces(f\"{prefix}_{kind}\")\n",
    ")\n",
    "cell, plane = pieces(\"_cell\")[0], pieces(\"\")[0]\n",
    "cell_mesh = scaled(\n",
    "    TriangularMesher(\n",
    "        target_size=0.04,\n",
    "        embedded_regions=layers(\"_cell\"),\n",
    "        region_sizes={\"metal\": 0.006, \"dielectric\": 0.006},\n",
    "        periodic_pairs=(PeriodicPair(cell.boundaries.x_min, cell.boundaries.x_max),),\n",
    "    ).generate(cell),\n",
    "    \"um\",\n",
    ")\n",
    "mesh = scaled(\n",
    "    TriangularMesher(\n",
    "        target_size=0.05,\n",
    "        embedded_regions=layers(\"\") + (pieces(\"_source\")[0].named(\"source\"),),\n",
    "        region_sizes={\"metal\": 0.01, \"dielectric\": 0.01, \"source\": 0.004},\n",
    "    ).generate(plane),\n",
    "    \"um\",\n",
    ")\n",
    "\n",
    "fig = plots.figure(1, 3, size=(20, 6))\n",
    "plots.geometry(\n",
    "    plane,\n",
    "    selection={\"outer faces\": plane.boundaries.all},\n",
    "    labels=False,\n",
    "    title=\"Section with stack and source (STEP)\",\n",
    "    length_unit=\"um\",\n",
    "    drawing_unit=\"um\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Section: {mesh.cell_count} triangles\",\n",
    "    length_unit=\"um\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.mesh(\n",
    "    cell_mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Period cell: {cell_mesh.cell_count} triangles\",\n",
    "    length_unit=\"um\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Period cell: reflection and transmission\n",
    "\n",
    "For every angle the Bloch wavevector is $k_0\\sin\\theta$; the port above feeds the plane wave and\n",
    "`diffraction_efficiencies` returns the reflected (port 0) and transmitted (port 1) power."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = RegionwiseElectromagneticMaterial(\n",
    "    {\n",
    "        \"metal\": silver,\n",
    "        \"dielectric\": IsotropicElectromagneticMaterial(\n",
    "            relative_permittivity=dielectric\n",
    "        ),\n",
    "    },\n",
    "    default=IsotropicElectromagneticMaterial(),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=2)), linear_solver=ComplexSparseDirect()\n",
    ")\n",
    "periodic = FrequencyDomainMaxwell(\n",
    "    domain=cell.domain(),\n",
    "    frequency=frequency,\n",
    "    material=material,\n",
    "    polarization=\"Exy\",\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "angles = np.arange(0.0, 85.1, 5.0)\n",
    "efficiencies = {\n",
    "    angle: diffraction_efficiencies(\n",
    "        Simulation(\n",
    "            problem=Problem(\n",
    "                name=\"metamaterial cell\",\n",
    "                geometry=cell,\n",
    "                physics=(periodic,),\n",
    "                boundary_conditions=(\n",
    "                    BlochPeriodicBoundary(\n",
    "                        physics=periodic,\n",
    "                        pair=PeriodicPair(cell.boundaries.x_min, cell.boundaries.x_max),\n",
    "                        wavevector=(k0 * np.sin(np.radians(angle)), 0.0, 0.0),\n",
    "                    ),\n",
    "                    FloquetPort(\n",
    "                        physics=periodic,\n",
    "                        boundary=cell.boundaries.y_max,\n",
    "                        incident_amplitude=1.0,\n",
    "                    ),\n",
    "                    FloquetPort(physics=periodic, boundary=cell.boundaries.y_min),\n",
    "                ),\n",
    "            ),\n",
    "            mesh=cell_mesh,\n",
    "            numerics=numerics,\n",
    "        ).solve_stationary(),\n",
    "        periodic,\n",
    "    )\n",
    "    for angle in angles\n",
    "}\n",
    "\n",
    "\n",
    "def stack(angle):\n",
    "    kx, layers = k0 * np.sin(np.radians(angle)), [dielectric, metal] * pairs\n",
    "    admittance = lambda eps: eps * k0 / np.sqrt(eps * k0**2 - kx**2 + 0j)\n",
    "    product = np.linalg.multi_dot(\n",
    "        [\n",
    "            np.array(\n",
    "                [\n",
    "                    [\n",
    "                        np.cos(np.sqrt(e * k0**2 - kx**2 + 0j) * layer),\n",
    "                        -1j\n",
    "                        * np.sin(np.sqrt(e * k0**2 - kx**2 + 0j) * layer)\n",
    "                        / admittance(e),\n",
    "                    ],\n",
    "                    [\n",
    "                        -1j\n",
    "                        * admittance(e)\n",
    "                        * np.sin(np.sqrt(e * k0**2 - kx**2 + 0j) * layer),\n",
    "                        np.cos(np.sqrt(e * k0**2 - kx**2 + 0j) * layer),\n",
    "                    ],\n",
    "                ]\n",
    "            )\n",
    "            for e in layers\n",
    "        ]\n",
    "    )\n",
    "    y0 = admittance(1.0)\n",
    "    denominator = (\n",
    "        y0 * product[0, 0]\n",
    "        + y0 * y0 * product[0, 1]\n",
    "        + product[1, 0]\n",
    "        + y0 * product[1, 1]\n",
    "    )\n",
    "    return (\n",
    "        abs(\n",
    "            (\n",
    "                y0 * product[0, 0]\n",
    "                + y0 * y0 * product[0, 1]\n",
    "                - product[1, 0]\n",
    "                - y0 * product[1, 1]\n",
    "            )\n",
    "            / denominator\n",
    "        )\n",
    "        ** 2,\n",
    "        abs(2 * y0 / denominator) ** 2,\n",
    "    )\n",
    "\n",
    "\n",
    "exact = np.array([stack(angle) for angle in angles])\n",
    "computed = np.array(\n",
    "    [\n",
    "        (efficiencies[a].get((0, 0), 0.0), efficiencies[a].get((1, 0), 0.0))\n",
    "        for a in angles\n",
    "    ]\n",
    ")\n",
    "print(\"angle   R computed  R exact     T computed  T exact     A = 1 - R - T\")\n",
    "for angle, (r, t), (re, te) in zip(angles[::2], computed[::2], exact[::2]):\n",
    "    print(\n",
    "        f\"{angle:5.1f}   {r:.6f}    {re:.6f}    {t:.6f}    {te:.6f}    {1 - r - t:.4f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"\\nlargest deviation: R {np.max(np.abs(computed[:, 0] - exact[:, 0])):.1e}, T {np.max(np.abs(computed[:, 1] - exact[:, 1])):.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Section: the resonance cones\n",
    "\n",
    "A line current of 10 nm radius along $x$, 30 nm above the stack, radiates TM waves. The\n",
    "absorbing layers fill the outer 0.4 um on all sides; the stack runs into them, so it acts as an\n",
    "infinite slab. Poynting's theorem checks the solution: the power the current supplies,\n",
    "$-\\tfrac12\\mathrm{Re}\\int\\mathbf E\\cdot\\mathbf J^*\\,\\mathrm dA$, must equal the power absorbed in the\n",
    "silver plus the flux into the absorbing layers. The energy flow in the stack is then compared with\n",
    "the cone of the effective medium."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "source = FrequencyDomainMaxwell(\n",
    "    domain=plane.domain(),\n",
    "    frequency=frequency,\n",
    "    polarization=\"Exy\",\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    "    material=CartesianPML(\n",
    "        material=material,\n",
    "        damping=lambda x, y, z: 3\n",
    "        * 2\n",
    "        * np.pi\n",
    "        * frequency\n",
    "        * np.column_stack(\n",
    "            (\n",
    "                np.clip((np.abs(x) - 1.2 * um) / (0.4 * um), 0, None) ** 2,\n",
    "                np.clip((y - 0.3 * um) / (0.4 * um), 0, None) ** 2\n",
    "                + np.clip((-0.7 * um - y) / (0.4 * um), 0, None) ** 2,\n",
    "                0 * x,\n",
    "            )\n",
    "        ),\n",
    "    ),\n",
    "    impressed_current=lambda x, y, z: np.column_stack(\n",
    "        (\n",
    "            (np.hypot(x, y - 0.03 * um) < 0.01 * um) / (np.pi * (0.01 * um) ** 2) + 0j,\n",
    "            0 * x,\n",
    "            0 * x,\n",
    "        )\n",
    "    ),\n",
    ")\n",
    "cone = Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"metamaterial source\",\n",
    "        geometry=plane,\n",
    "        physics=(source,),\n",
    "        boundary_conditions=(\n",
    "            PerfectElectricConductor(physics=source, boundary=plane.boundaries.all),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=mesh,\n",
    "    numerics=numerics,\n",
    ").solve_stationary()\n",
    "radius = 0.01 * um\n",
    "rings, turns = np.meshgrid(\n",
    "    (np.arange(40) + 0.5) / 40 * radius, 2 * np.pi * np.arange(64) / 64, indexing=\"ij\"\n",
    ")\n",
    "inside = np.column_stack(\n",
    "    ((rings * np.cos(turns)).ravel(), (0.03 * um + rings * np.sin(turns)).ravel())\n",
    ")\n",
    "supplied = -0.5 * np.sum(\n",
    "    np.real(cone.field(source.electric_field).evaluate(inside)[:, 0])\n",
    "    / (np.pi * radius**2)\n",
    "    * (rings.ravel() * radius / 40 * 2 * np.pi / 64)\n",
    ")\n",
    "edges = [\n",
    "    ((-1.15 * um, 0.28 * um), (1.15 * um, 0.28 * um), (0.0, 1.0)),\n",
    "    ((-1.15 * um, -0.68 * um), (1.15 * um, -0.68 * um), (0.0, -1.0)),\n",
    "    ((1.15 * um, -0.68 * um), (1.15 * um, 0.28 * um), (1.0, 0.0)),\n",
    "    ((-1.15 * um, -0.68 * um), (-1.15 * um, 0.28 * um), (-1.0, 0.0)),\n",
    "]\n",
    "steps = np.linspace(0.0, 1.0, 4001)\n",
    "paths = [\n",
    "    (\n",
    "        np.asarray(a) + np.outer(steps, np.subtract(b, a)),\n",
    "        np.hypot(*np.subtract(b, a)),\n",
    "        np.asarray(n),\n",
    "    )\n",
    "    for a, b, n in edges\n",
    "]\n",
    "leaving = sum(\n",
    "    np.trapezoid(\n",
    "        0.5\n",
    "        * np.real(\n",
    "            np.column_stack(\n",
    "                (\n",
    "                    cone.field(source.electric_field).evaluate(points)[:, 1],\n",
    "                    -cone.field(source.electric_field).evaluate(points)[:, 0],\n",
    "                )\n",
    "            )\n",
    "            * np.conj(\n",
    "                cone.field(source.magnetic_flux_density).evaluate(points)[:, 2]\n",
    "                / VACUUM_PERMEABILITY\n",
    "            )[:, None]\n",
    "        )\n",
    "        @ n,\n",
    "        steps * length,\n",
    "    )\n",
    "    for points, length, n in paths\n",
    ")\n",
    "dissipated = cone.field(source.absorbed_power_density).integrate().value\n",
    "print(\n",
    "    f\"power of the line source {supplied:.5e} W/m = absorbed in the silver {dissipated:.5e} + leaving through the absorbing layers {leaving:.5e} \"\n",
    "    f\"(mismatch {abs(dissipated + leaving - supplied) / supplied:.1e})\"\n",
    ")\n",
    "line = np.linspace(0.0, 1.0 * um, 4001)\n",
    "depths = [-(2 * k + 0.5) * layer for k in (1, 3, 5, 7)]\n",
    "flow = {\n",
    "    depth: (\n",
    "        lambda E, H: (\n",
    "            0.5 * np.real(E[:, 1] * np.conj(H)),\n",
    "            -0.5 * np.real(E[:, 0] * np.conj(H)),\n",
    "        )\n",
    "    )(\n",
    "        cone.field(source.electric_field).evaluate(\n",
    "            np.column_stack((line, depth + 0 * line))\n",
    "        ),\n",
    "        cone.field(source.magnetic_flux_density).evaluate(\n",
    "            np.column_stack((line, depth + 0 * line))\n",
    "        )[:, 2]\n",
    "        / VACUUM_PERMEABILITY,\n",
    "    )\n",
    "    for depth in depths\n",
    "}\n",
    "theory = np.degrees(np.arctan(np.sqrt(-parallel.real / across.real)))\n",
    "print(f\"\\nresonance cone of the effective medium: {theory:.1f} deg from the normal\")\n",
    "print(\n",
    "    \"depth [nm]   strongest energy flow at x [nm]   cone of the effective medium at x [nm]   direction of the flow [deg]\"\n",
    ")\n",
    "for depth, (sx, sy) in flow.items():\n",
    "    i = int(np.argmax(np.hypot(sx, sy)))\n",
    "    print(\n",
    "        f\"{1e9 * depth:9.0f}    {1e9 * line[i]:12.1f}                     {1e9 * (abs(depth) + 0.03 * um) * np.tan(np.radians(theory)):12.1f}\"\n",
    "        f\"                      {np.degrees(np.arctan2(sx[i], -sy[i])):6.1f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The energy in the stack flows more steeply sideways than the cone of the effective medium. The near\n",
    "field of a source 30 nm above the stack consists of waves whose wavelength along the layers is\n",
    "comparable to the 40 nm period; for them the stack is no effective medium any more, and the finite\n",
    "stack of eight bilayers guides part of them along its layers. Thinner layers or a source further\n",
    "away bring the beams towards the effective-medium cone.\n",
    "\n",
    "## Figure\n",
    "\n",
    "Reflection and transmission of the stack against the angle of incidence, and the magnetic field\n",
    "of the line source with the two resonance cones in the stack."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x, y = np.asarray(mesh.coordinates).T\n",
    "field = np.abs(\n",
    "    cone.field(source.magnetic_flux_density).evaluate(np.column_stack((x, y)))[:, 2]\n",
    ")\n",
    "fig = plots.figure(1, 2, size=(20, 7))\n",
    "plots.line(\n",
    "    angles,\n",
    "    {\"R\": computed[:, 0], \"T\": computed[:, 1]},\n",
    "    reference={\"R\": exact[:, 0], \"T\": exact[:, 1]},\n",
    "    ylimits=(0, 1),\n",
    "    xlabel=\"angle of incidence [deg]\",\n",
    "    ylabel=\"fraction of the incident power\",\n",
    "    title=\"TM light on 8 bilayers (dashed: exact)\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.heatmap(\n",
    "    x,\n",
    "    y,\n",
    "    np.log10(field / field.max()),\n",
    "    triangles=np.asarray(mesh.cells),\n",
    "    limits=(-2.5, 0),\n",
    "    label=\"log10 |B_z| / max\",\n",
    "    length_unit=\"um\",\n",
    "    xlimits=(-1.0 * um, 1.0 * um),\n",
    "    ylimits=(-0.6 * um, 0.2 * um),\n",
    "    aspect=\"auto\",\n",
    "    title=\"Resonance cones of the line source\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the fill fraction or the dielectric in `hyperbolic_metamaterial_layers_geometry.py`: for\n",
    "$\\varepsilon_\\parallel>0>\\varepsilon_\\perp$ the hyperbola turns by 90 degrees (type I), and thinner\n",
    "layers bring the beams closer to the effective-medium cone. A stack bent into half cylinders\n",
    "is a hyperlens that magnifies details below the diffraction limit."
   ]
  }
 ]
}
