{
 "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": [
    "# Whispering-gallery modes of a dielectric microsphere\n",
    "\n",
    "A silica sphere of radius $a=4\\,\\mu$m and refractive index $n=1.45$ in air guides light along\n",
    "its surface: a ray grazing the rim is totally reflected over and over and closes on itself. The\n",
    "resulting resonances, whispering-gallery modes, are labelled by the polar order $l$, the\n",
    "azimuthal order $m$ ($|m|\\leq l$) and the radial order $q$ (the number of field maxima along the\n",
    "radius); the fundamental modes $l=m$, $q=1$ are confined to a thin belt at the equator. They\n",
    "radiate only by tunnelling through the curved surface, so their quality factor grows\n",
    "exponentially with $l$.\n",
    "\n",
    "The sphere is a body of revolution, so each azimuthal order is a 2D problem on the meridian plane:\n",
    "`FrequencyDomainMaxwell` with the polarization `Erphiz` and `azimuthal_mode=m` solves all three\n",
    "field components. Space outside the sphere is closed by a spherical perfectly matched layer\n",
    "(`spherical_pml`): the radius is stretched into the complex plane beyond 5.8 $\\mu$m, so outgoing\n",
    "waves decay without reflection, and the open resonator gets complex eigenfrequencies\n",
    "$f=f_r-i\\,f_r/(2Q)$. The layer itself supports strongly damped modes; they are recognized by\n",
    "their small $Q$ and set aside.\n",
    "\n",
    "| boundary or region | condition |\n",
    "|---|---|\n",
    "| silica sphere, $r<4\\,\\mu$m | $\\varepsilon_r=n^2=2.1025$ |\n",
    "| air, $4<r<5.8\\,\\mu$m | $\\varepsilon_r=1$ |\n",
    "| layer, $5.8<r<7\\,\\mu$m | spherical PML |\n",
    "| `outer`, $r=7\\,\\mu$m | perfect electric conductor (the field has decayed there) |\n",
    "\n",
    "**Reference.** The resonances of a dielectric sphere are the poles of the Mie coefficients\n",
    "(C. F. Bohren and D. R. Huffman, *Absorption and Scattering of Light by Small Particles*, §4.4):\n",
    "with $x=ka$, the Riccati-Bessel functions $\\psi_l(z)=z\\,j_l(z)$ and $\\xi_l(z)=z\\,h^{(1)}_l(z)$,\n",
    "\n",
    "$$\\text{TE}:\\ \\psi_l(nx)\\,\\xi_l'(x)-n\\,\\psi_l'(nx)\\,\\xi_l(x)=0,\\qquad\n",
    "  \\text{TM}:\\ n\\,\\psi_l(nx)\\,\\xi_l'(x)-\\psi_l'(nx)\\,\\xi_l(x)=0,$$\n",
    "\n",
    "whose complex roots $x$ give $f=c\\,x/(2\\pi a)$ and $Q=\\operatorname{Re}x/(2|\\operatorname{Im}x|)$.\n",
    "The asymptotic formula of C. C. Lam, P. T. Leung and K. Young (*J. Opt. Soc. Am. B* 9, 1585,\n",
    "1992), $nx\\approx\\nu+2^{-1/3}\\alpha_q\\nu^{1/3}-P/\\sqrt{n^2-1}$ with $\\nu=l+\\tfrac12$, the Airy zeros\n",
    "$\\alpha_q$ and $P=n$ (TE) or $1/n$ (TM), starts Newton's method for each root."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials.electromagnetic import (\n",
    "    IsotropicElectromagneticMaterial,\n",
    "    RegionwiseElectromagneticMaterial,\n",
    "    spherical_pml,\n",
    ")\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Nedelec, RevolvedH1SpaceFactory\n",
    "from onesim.numerics.linear import ComplexSparseDirect\n",
    "from onesim.physics.electromagnetics import (\n",
    "    FrequencyDomainMaxwell,\n",
    "    PerfectElectricConductor,\n",
    "    electromagnetic_modes,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.optimize import newton\n",
    "from scipy.special import ai_zeros, spherical_jn, spherical_yn\n",
    "\n",
    "theme.set()\n",
    "\n",
    "light = 299792458.0\n",
    "index, order = 1.45, 18"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The STEP files hold half of the air ball and half of the sphere as solids of revolution; their\n",
    "sections with the plane $y=0$ are half discs. The sphere is embedded in the mesh as a region with\n",
    "triangles of 0.11 $\\mu$m (a tenth of the wavelength in glass); the air and the layer take\n",
    "0.16 $\\mu$m."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "air = load(\"whispering_gallery_microsphere.step\").section((0, 1, 0))\n",
    "sphere = (\n",
    "    load(\"whispering_gallery_microsphere_sphere.step\")\n",
    "    .section((0, 1, 0))\n",
    "    .named(\"silica\")\n",
    ")\n",
    "radius, outer = sphere.size[1] / 2, air.size[1] / 2\n",
    "layer = outer - 1.2e-6\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.16e-6, embedded_regions=(sphere,), region_sizes={\"silica\": 0.11e-6}\n",
    ").generate(air)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 7))\n",
    "plots.geometry(\n",
    "    air,\n",
    "    selection={\"outer boundary\": air.boundaries.outer},\n",
    "    labels=False,\n",
    "    title=\"Meridian plane of the air ball (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"{mesh.cell_count} triangles, silica region finer\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model and eigenfrequency study\n",
    "\n",
    "One model for the azimuthal order $m=18$, solved once near the expected fundamental resonance\n",
    "at 1.55 $\\mu$m; `electromagnetic_modes` returns every mode with a vacuum wavelength between 1.40\n",
    "and 1.70 $\\mu$m. The stretch of the layer does not depend on the frequency, so the eigenvalue\n",
    "problem stays linear."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "glass = RegionwiseElectromagneticMaterial(\n",
    "    {\"silica\": IsotropicElectromagneticMaterial(relative_permittivity=index**2)},\n",
    "    default=IsotropicElectromagneticMaterial(),\n",
    ")\n",
    "model = FrequencyDomainMaxwell(\n",
    "    domain=air.domain(),\n",
    "    frequency=light / 1.55e-6,\n",
    "    material=spherical_pml(glass, layer, outer, strength=2.0),\n",
    "    polarization=\"Erphiz\",\n",
    "    azimuthal_mode=order,\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "result = Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Microsphere\",\n",
    "        geometry=air,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            PerfectElectricConductor(physics=model, boundary=air.boundaries.outer),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=mesh,\n",
    "    numerics=Numerics(\n",
    "        spatial=FiniteElement(\n",
    "            element=Nedelec(order=2), provider=RevolvedH1SpaceFactory()\n",
    "        ),\n",
    "        linear_solver=ComplexSparseDirect(),\n",
    "    ),\n",
    ").solve_stationary()\n",
    "modes = electromagnetic_modes(\n",
    "    result, model, frequency_range=(light / 1.70e-6, light / 1.40e-6)\n",
    ")\n",
    "confined = np.flatnonzero(modes.quality_factors > 20)\n",
    "print(\n",
    "    f\"{modes.mode_count} modes between 1.40 and 1.70 um: {len(confined)} confined in the sphere (Q > 20), \"\n",
    "    f\"{modes.mode_count - len(confined)} damped modes of the absorbing layer; Q from {modes.quality_factors.min():.1f} to {modes.quality_factors.max():.1f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with Mie theory\n",
    "\n",
    "For each confined mode the exact Mie resonance of the same family is found by Newton's method,\n",
    "started from the asymptotic formula for the polarization, polar order $l\\geq m$ and radial\n",
    "order $q$ whose start lies nearest; the table lists the computed and exact wavelength and $Q$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "psi = lambda l, z: z * spherical_jn(l, z)\n",
    "dpsi = lambda l, z: spherical_jn(l, z) + z * spherical_jn(l, z, derivative=True)\n",
    "xi = lambda l, z: z * (spherical_jn(l, z) + 1j * spherical_yn(l, z))\n",
    "dxi = lambda l, z: (spherical_jn(l, z) + 1j * spherical_yn(l, z)) + z * (\n",
    "    spherical_jn(l, z, derivative=True) + 1j * spherical_yn(l, z, derivative=True)\n",
    ")\n",
    "condition = {\n",
    "    \"TE\": lambda l: lambda x: psi(l, index * x) * dxi(l, x)\n",
    "    - index * dpsi(l, index * x) * xi(l, x),\n",
    "    \"TM\": lambda l: lambda x: index * psi(l, index * x) * dxi(l, x)\n",
    "    - dpsi(l, index * x) * xi(l, x),\n",
    "}\n",
    "airy = -ai_zeros(3)[0]\n",
    "start = {\n",
    "    (polarization, l, q): (\n",
    "        (l + 0.5)\n",
    "        + 2 ** (-1 / 3) * airy[q - 1] * (l + 0.5) ** (1 / 3)\n",
    "        - (index if polarization == \"TE\" else 1 / index) / np.sqrt(index**2 - 1)\n",
    "    )\n",
    "    / index\n",
    "    for polarization in (\"TE\", \"TM\")\n",
    "    for l in range(order, order + 6)\n",
    "    for q in (1, 2, 3)\n",
    "}\n",
    "computed_x = 2 * np.pi * radius * modes.frequencies / light\n",
    "print(\n",
    "    f\"{'mode':>14s} {'wavelength [um]':>16s} {'Mie [um]':>9s} {'deviation':>10s} {'Q computed':>11s} {'Q Mie':>8s} {'deviation':>10s}\"\n",
    ")\n",
    "labels, mie = {}, {}\n",
    "for i in confined:\n",
    "    family = min(start, key=lambda key: abs(start[key] - computed_x[i].real))\n",
    "    exact = newton(\n",
    "        condition[family[0]](family[1]),\n",
    "        computed_x[i].real - 1e-3j,\n",
    "        tol=1e-13,\n",
    "        maxiter=200,\n",
    "    )\n",
    "    labels[i], mie[i] = f\"{family[0]} l={family[1]} q={family[2]}\", exact\n",
    "    wavelength, reference = (\n",
    "        light / modes.resonance_frequencies[i],\n",
    "        2 * np.pi * radius / exact.real,\n",
    "    )\n",
    "    print(\n",
    "        f\"{labels[i]:>14s} {1e6 * wavelength:16.5f} {1e6 * reference:9.5f} {wavelength / reference - 1:10.1e} \"\n",
    "        f\"{modes.quality_factors[i]:11.1f} {exact.real / (2 * abs(exact.imag)):8.1f} {modes.quality_factors[i] / (exact.real / (2 * abs(exact.imag))) - 1:10.1e}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Top: the magnitude of the electric field near the rim of the sphere (normalized to 1 J; the\n",
    "glass surface lies at $r=4\\,\\mu$m): the fundamental TE and TM modes ($l=m$) run in a belt at the\n",
    "equator, within a fraction of a wavelength of the surface; the TM field jumps at the surface,\n",
    "where its normal component does. The mode $l=m+1$ has two lobes across the equator. Bottom: the\n",
    "quality factor against the polar order $l$, computed and from Mie theory, grows exponentially\n",
    "(the tunnelling barrier widens with $l$); the radial profiles at the equator with the\n",
    "evanescent tail outside the glass; the profiles along the latitude just inside the surface."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "nodes = np.asarray(mesh.coordinates)\n",
    "pick = lambda polarization, l: next(\n",
    "    i for i in confined if labels[i] == f\"{polarization} l={l} q=1\"\n",
    ")\n",
    "shown = [pick(\"TE\", order), pick(\"TM\", order), pick(\"TE\", order + 1)]\n",
    "fig = plots.figure(2, 3, size=(20, 13))\n",
    "for panel, i in enumerate(shown):\n",
    "    field = modes.mode(i).field(model.electric_field).evaluate((1 - 1e-4) * nodes)\n",
    "    plots.heatmap(\n",
    "        nodes[:, 0],\n",
    "        nodes[:, 1],\n",
    "        np.sqrt(np.sum(np.abs(field) ** 2, axis=1)),\n",
    "        triangles=np.asarray(mesh.cells),\n",
    "        length_unit=\"um\",\n",
    "        xlimits=(2.5e-6, 5e-6),\n",
    "        ylimits=(-1.25e-6, 1.25e-6),\n",
    "        xlabel=\"r [m]\",\n",
    "        ylabel=\"z [m]\",\n",
    "        label=\"|E| [V/m]\",\n",
    "        title=f\"{labels[i]}: {1e6 * light / modes.resonance_frequencies[i]:.4f} um, Q = {modes.quality_factors[i]:.0f}\",\n",
    "        ax=fig[panel],\n",
    "    )\n",
    "family = lambda polarization: [\n",
    "    i for i in confined if labels[i].startswith(polarization)\n",
    "]\n",
    "polar = lambda members: np.array(\n",
    "    [int(labels[i].split(\"l=\")[1].split()[0]) for i in members]\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"{p}, computed\": (polar(family(p)), modes.quality_factors[family(p)])\n",
    "        for p in (\"TE\", \"TM\")\n",
    "    },\n",
    "    reference={\n",
    "        f\"{p}, Mie theory\": (\n",
    "            polar(family(p)),\n",
    "            np.array([mie[i].real / (2 * abs(mie[i].imag)) for i in family(p)]),\n",
    "        )\n",
    "        for p in (\"TE\", \"TM\")\n",
    "    },\n",
    "    scale=\"logy\",\n",
    "    xlabel=\"polar order l (q = 1)\",\n",
    "    ylabel=\"quality factor Q\",\n",
    "    title=f\"Radiation Q of the modes with m = {order}\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "equator = np.linspace(0.5 * radius, 1.4 * radius, 300)\n",
    "plots.line(\n",
    "    y={\n",
    "        labels[i]: (\n",
    "            1e6 * equator,\n",
    "            np.sqrt(\n",
    "                np.sum(\n",
    "                    np.abs(\n",
    "                        modes.mode(i)\n",
    "                        .field(model.electric_field)\n",
    "                        .evaluate(np.column_stack((equator, np.zeros_like(equator))))\n",
    "                    )\n",
    "                    ** 2,\n",
    "                    axis=1,\n",
    "                )\n",
    "            ),\n",
    "        )\n",
    "        for i in shown\n",
    "    },\n",
    "    vlines={\"glass surface\": 1e6 * radius},\n",
    "    xlabel=\"r [um] (equator, z = 0)\",\n",
    "    ylabel=\"|E| [V/m]\",\n",
    "    title=\"Radial profiles at the equator\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[4],\n",
    ")\n",
    "latitude = np.linspace(-0.5, 0.5, 300)\n",
    "plots.line(\n",
    "    y={\n",
    "        labels[i]: (\n",
    "            np.degrees(latitude),\n",
    "            np.sqrt(\n",
    "                np.sum(\n",
    "                    np.abs(\n",
    "                        modes.mode(i)\n",
    "                        .field(model.electric_field)\n",
    "                        .evaluate(\n",
    "                            np.column_stack(\n",
    "                                (\n",
    "                                    0.97 * radius * np.cos(latitude),\n",
    "                                    0.97 * radius * np.sin(latitude),\n",
    "                                )\n",
    "                            )\n",
    "                        )\n",
    "                    )\n",
    "                    ** 2,\n",
    "                    axis=1,\n",
    "                )\n",
    "            ),\n",
    "        )\n",
    "        for i in shown\n",
    "    },\n",
    "    xlabel=\"latitude [degrees] (r = 0.97 a)\",\n",
    "    ylabel=\"|E| [V/m]\",\n",
    "    title=\"Confinement to the equator\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[5],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise `order` (and the wavelength window) to follow the exponential growth of $Q$ with $l$:\n",
    "for a larger sphere or higher $m$ the radiation $Q$ soon exceeds $10^6$, and absorption in the\n",
    "glass, a complex `relative_permittivity`, limits the total $Q$ through $1/Q=1/Q_{rad}+1/Q_{abs}$."
   ]
  }
 ]
}
