{
 "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": [
    "# Gold nanoparticle on a glass substrate\n",
    "\n",
    "Small gold particles absorb and scatter light strongly near their plasmon resonance. On a substrate\n",
    "the particle sees the light reflected and transmitted by the interface and its own image in it, so\n",
    "the cross-sections depend on the angle of incidence. The scattered-field formulation splits the\n",
    "field into the known background $\\mathbf E_b$ - here the plane wave with its Fresnel reflection\n",
    "above the glass and its transmission below, `FresnelPlaneWave` - and the scattered field\n",
    "$\\mathbf E_s$, which `FrequencyDomainMaxwell` solves with the source\n",
    "$(\\varepsilon-\\varepsilon_b)\\,\\omega^2\\mathbf E_b$ in the particle. Absorbing layers (`CartesianPML`)\n",
    "0.1 um thick close the cube of 0.6 um.\n",
    "\n",
    "Gold is the Drude-Lorentz model of Rakić et al.; the glass has $n=1.5$; the vacuum wavelength is\n",
    "550 nm, near the plasmon resonance of the particle.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| all faces of the cube (behind the absorbing layers) | perfect electric conductor on the scattered field |\n",
    "\n",
    "The absorbed power $P_a$ is the integral of the absorbed power density over the gold; the\n",
    "scattered power $P_s$ is the flux of $\\tfrac12\\mathrm{Re}(\\mathbf E_s\\times\\mathbf H_s^*)$ through a\n",
    "sphere of 0.1 um radius around the particle (it crosses the interface: the flux of the scattered\n",
    "field through any closed surface around the particle is the same, since air and glass are\n",
    "lossless). Divided by the incident intensity $I_0=\\tfrac12|E_0|^2/\\eta_0$ they give the cross-sections\n",
    "$\\sigma_a$ and $\\sigma_s$.\n",
    "\n",
    "**Reference** (C. F. Bohren and D. R. Huffman, *Absorption and Scattering of Light by Small\n",
    "Particles*, Wiley 1983, §4.4; A. D. Rakić et al., *Appl. Opt.* 37, 5271 (1998)). With the substrate\n",
    "replaced by air the cross-sections must equal the Mie series of the sphere; on the substrate the\n",
    "results at the azimuthal angles 0 and 45 degrees must agree, since a sphere over a flat interface is\n",
    "rotationally symmetric.\n",
    "\n",
    "The STEP parts are drawn in micrometres; `scaled` brings the mesh to metres, so the model is solved\n",
    "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",
    "    DrudeLorentzElectromagneticMaterial,\n",
    "    IsotropicElectromagneticMaterial,\n",
    "    LorentzOscillator,\n",
    "    RegionwiseElectromagneticMaterial,\n",
    "    electronvolts_to_angular_frequency,\n",
    ")\n",
    "from onesim.meshing import LocalRefinement, TetrahedralMesher, 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",
    "    FrequencyDomainMaxwell,\n",
    "    FresnelPlaneWave,\n",
    "    PerfectElectricConductor,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.special import spherical_jn, spherical_yn\n",
    "\n",
    "theme.set()\n",
    "\n",
    "um, radius, centre, wavelength, glass = 1e-6, 50e-9, 55e-9, 550e-9, 1.5**2\n",
    "light, impedance = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY), np.sqrt(\n",
    "    VACUUM_PERMEABILITY / VACUUM_PERMITTIVITY\n",
    ")\n",
    "frequency = light / wavelength\n",
    "plasma, oscillators = 9.03, [\n",
    "    (0.024, 0.241, 0.415),\n",
    "    (0.010, 0.345, 0.830),\n",
    "    (0.071, 0.870, 2.969),\n",
    "    (0.601, 2.494, 4.304),\n",
    "    (4.384, 2.214, 13.32),\n",
    "]\n",
    "gold = DrudeLorentzElectromagneticMaterial(\n",
    "    plasma_frequency=electronvolts_to_angular_frequency(np.sqrt(0.760) * plasma),\n",
    "    collision_rate=electronvolts_to_angular_frequency(0.053),\n",
    "    oscillators=tuple(\n",
    "        LorentzOscillator(\n",
    "            strength=f * plasma**2 / w**2,\n",
    "            resonance_frequency=electronvolts_to_angular_frequency(w),\n",
    "            damping=electronvolts_to_angular_frequency(g),\n",
    "        )\n",
    "        for f, g, w in oscillators\n",
    "    ),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the cube, the glass half and the sphere. Tetrahedra of 80 nm in the air and glass and\n",
    "10 nm in the gold, where the field decays within 30 nm of the surface; `scaled(..., \"um\")` turns\n",
    "the micrometres of the drawing into metres."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "parts = {\n",
    "    name: load(f\"gold_nanoparticle_on_substrate{name}.step\")\n",
    "    for name in (\"\", \"_glass\", \"_gold\")\n",
    "}\n",
    "cube, substrate, particle = (\n",
    "    parts[\"\"],\n",
    "    parts[\"_glass\"].named(\"glass\"),\n",
    "    parts[\"_gold\"].named(\"gold\"),\n",
    ")\n",
    "mesh = scaled(\n",
    "    TetrahedralMesher(\n",
    "        target_size=0.08,\n",
    "        embedded_regions=(substrate, particle),\n",
    "        refinements=(LocalRefinement(region=particle, target_size=0.01),),\n",
    "    ).generate(cube),\n",
    "    \"um\",\n",
    ")\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6.5))\n",
    "plots.geometry(\n",
    "    [cube, substrate, particle],\n",
    "    title=\"Cube, glass and gold sphere (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\"{mesh.cell_count} tetrahedra\",\n",
    "    length_unit=\"um\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "One model per case: the substrate permittivity (1 for the Mie check, at normal incidence) and the\n",
    "angles. The background\n",
    "material is the same layered medium without the particle, wrapped in the same absorbing layers, so\n",
    "only the gold drives the scattered field."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "damping = (\n",
    "    lambda x, y, z: 3\n",
    "    * 2\n",
    "    * np.pi\n",
    "    * frequency\n",
    "    * np.column_stack(\n",
    "        [np.clip((np.abs(v) - 0.2 * um) / (0.1 * um), 0, None) ** 2 for v in (x, y, z)]\n",
    "    )\n",
    ")\n",
    "layered = lambda substrate_permittivity, extra: CartesianPML(\n",
    "    material=RegionwiseElectromagneticMaterial(\n",
    "        {\n",
    "            \"glass\": IsotropicElectromagneticMaterial(\n",
    "                relative_permittivity=substrate_permittivity\n",
    "            ),\n",
    "            **extra,\n",
    "        },\n",
    "        default=IsotropicElectromagneticMaterial(),\n",
    "    ),\n",
    "    damping=damping,\n",
    ")\n",
    "model = lambda substrate_permittivity, polar, azimuth: FrequencyDomainMaxwell(\n",
    "    domain=cube.volume,\n",
    "    frequency=frequency,\n",
    "    material=layered(substrate_permittivity, {\"gold\": gold}),\n",
    "    background_material=layered(substrate_permittivity, {}),\n",
    "    background_field=FresnelPlaneWave(\n",
    "        frequency=frequency,\n",
    "        polar_angle=np.radians(polar),\n",
    "        azimuth=np.radians(azimuth),\n",
    "        polarization=\"TE\",\n",
    "        lower=substrate_permittivity,\n",
    "    ),\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=2)), linear_solver=ComplexSparseDirect()\n",
    ")\n",
    "solve = lambda physics: Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"particle on substrate\",\n",
    "        geometry=cube,\n",
    "        physics=(physics,),\n",
    "        boundary_conditions=(\n",
    "            PerfectElectricConductor(\n",
    "                physics=physics, boundary=cube.boundaries.all, total_field=False\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=mesh,\n",
    "    numerics=numerics,\n",
    ").solve_stationary()\n",
    "\n",
    "cases = {\n",
    "    (\"air\", 0.0, 0.0): model(1.0, 0.0, 0.0),\n",
    "    (\"glass\", 45.0, 0.0): model(glass, 45.0, 0.0),\n",
    "    (\"glass\", 45.0, 45.0): model(glass, 45.0, 45.0),\n",
    "}\n",
    "results = {key: solve(physics) for key, physics in cases.items()}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The cross-sections in units of the geometric cross-section $\\pi a^2$. The scattered field on the\n",
    "sphere around the particle is the computed total field minus the background field."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "cosines, weights = np.polynomial.legendre.leggauss(24)\n",
    "c, a = np.meshgrid(cosines, 2 * np.pi * np.arange(48) / 48, indexing=\"ij\")\n",
    "normals = np.column_stack(\n",
    "    (\n",
    "        (np.sqrt(1 - c**2) * np.cos(a)).ravel(),\n",
    "        (np.sqrt(1 - c**2) * np.sin(a)).ravel(),\n",
    "        c.ravel(),\n",
    "    )\n",
    ")\n",
    "patch = (\n",
    "    np.meshgrid(weights, np.full(48, 2 * np.pi / 48), indexing=\"ij\")[0] * 2 * np.pi / 48\n",
    ").ravel() * (0.1 * um) ** 2\n",
    "sphere = np.array([0.0, 0.0, centre]) + 0.1 * um * normals\n",
    "intensity, area = 0.5 / impedance, np.pi * radius**2\n",
    "absorption = {\n",
    "    key: result.field(cases[key].absorbed_power_density).integrate().value\n",
    "    / intensity\n",
    "    / area\n",
    "    for key, result in results.items()\n",
    "}\n",
    "scattering = {\n",
    "    key: np.sum(\n",
    "        0.5\n",
    "        * np.real(\n",
    "            np.sum(\n",
    "                np.cross(\n",
    "                    result.field(cases[key].electric_field).evaluate(sphere)\n",
    "                    - cases[key].background_field(*sphere.T),\n",
    "                    np.conj(\n",
    "                        result.field(cases[key].magnetic_flux_density).evaluate(sphere)\n",
    "                        - cases[key].background_field.magnetic_flux_density(*sphere.T)\n",
    "                    )\n",
    "                    / VACUUM_PERMEABILITY,\n",
    "                )\n",
    "                * normals,\n",
    "                axis=1,\n",
    "            )\n",
    "        )\n",
    "        * patch\n",
    "    )\n",
    "    / intensity\n",
    "    / area\n",
    "    for key, result in results.items()\n",
    "}\n",
    "\n",
    "\n",
    "def mie(m, x):\n",
    "    n = np.arange(1, int(x + 4 * x ** (1 / 3) + 3))\n",
    "    psi, dpsi = (lambda z: z * spherical_jn(n, z)), (\n",
    "        lambda z: spherical_jn(n, z) + z * spherical_jn(n, z, True)\n",
    "    )\n",
    "    xi, dxi = x * (spherical_jn(n, x) + 1j * spherical_yn(n, x)), spherical_jn(\n",
    "        n, x\n",
    "    ) + 1j * spherical_yn(n, x) + x * (\n",
    "        spherical_jn(n, x, True) + 1j * spherical_yn(n, x, True)\n",
    "    )\n",
    "    an = (m * psi(m * x) * dpsi(x) - psi(x) * dpsi(m * x)) / (\n",
    "        m * psi(m * x) * dxi - xi * dpsi(m * x)\n",
    "    )\n",
    "    bn = (psi(m * x) * dpsi(x) - m * psi(x) * dpsi(m * x)) / (\n",
    "        psi(m * x) * dxi - m * xi * dpsi(m * x)\n",
    "    )\n",
    "    return 2 / x**2 * np.sum(\n",
    "        (2 * n + 1) * (np.real(an + bn) - np.abs(an) ** 2 - np.abs(bn) ** 2)\n",
    "    ), 2 / x**2 * np.sum((2 * n + 1) * (np.abs(an) ** 2 + np.abs(bn) ** 2))\n",
    "\n",
    "\n",
    "exact = mie(\n",
    "    np.sqrt(gold.relative_permittivity_at(frequency)), 2 * np.pi * radius / wavelength\n",
    ")\n",
    "print(f\"gold at 550 nm: eps = {gold.relative_permittivity_at(frequency):.3f}\")\n",
    "print(\"\\nbelow       polar  azimuth   sigma_abs / pi a^2   sigma_sca / pi a^2\")\n",
    "for below, polar, azimuth in results:\n",
    "    print(\n",
    "        f\"{below:9s}  {polar:5.1f}  {azimuth:6.1f}     {absorption[(below, polar, azimuth)]:10.4f}         {scattering[(below, polar, azimuth)]:10.4f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"\\nMie series of the free sphere: sigma_abs / pi a^2 = {exact[0]:.4f}, sigma_sca / pi a^2 = {exact[1]:.4f}; \"\n",
    "    f\"deviation {abs(absorption[('air', 0.0, 0.0)] / exact[0] - 1):.1e} and {abs(scattering[('air', 0.0, 0.0)] / exact[1] - 1):.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"azimuth 0 against 45 deg at 45 deg incidence: sigma_abs differs by {abs(absorption[('glass', 45.0, 0.0)] / absorption[('glass', 45.0, 45.0)] - 1):.1e}, \"\n",
    "    f\"sigma_sca by {abs(scattering[('glass', 45.0, 0.0)] / scattering[('glass', 45.0, 45.0)] - 1):.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The field in the plane of incidence through the particle at 45 degrees incidence: the total field,\n",
    "with the standing wave above the glass, and the scattered field alone."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "grid = np.linspace(-0.2 * um, 0.2 * um, 201)\n",
    "x, z = [values.ravel() for values in np.meshgrid(grid, grid)]\n",
    "points = np.column_stack((x, 0 * x, z))\n",
    "key = (\"glass\", 45.0, 0.0)\n",
    "total = np.linalg.norm(\n",
    "    results[key].field(cases[key].electric_field).evaluate(points), axis=1\n",
    ")\n",
    "alone = np.linalg.norm(\n",
    "    results[key].field(cases[key].electric_field).evaluate(points)\n",
    "    - cases[key].background_field(*points.T),\n",
    "    axis=1,\n",
    ")\n",
    "fig = plots.figure(1, 2, size=(16, 6.5))\n",
    "plots.heatmap(\n",
    "    grid,\n",
    "    grid,\n",
    "    total.reshape(len(grid), len(grid)).T,\n",
    "    limits=(0, np.percentile(total, 99)),\n",
    "    label=\"|E| / |E_0|\",\n",
    "    length_unit=\"um\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=\"Total field, 45 deg incidence (TE)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.heatmap(\n",
    "    grid,\n",
    "    grid,\n",
    "    alone.reshape(len(grid), len(grid)).T,\n",
    "    limits=(0, np.percentile(alone, 99)),\n",
    "    label=\"|E_s| / |E_0|\",\n",
    "    length_unit=\"um\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=\"Scattered field\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Sweep the wavelength from 450 to 700 nm to see the plasmon resonance shift on the glass, or turn\n",
    "the polarization to TM (`polarization=\"TM\"` of `FresnelPlaneWave`), where the field normal to the\n",
    "substrate couples the particle more strongly to its image."
   ]
  }
 ]
}
