{
 "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": [
    "# Conical dielectric probe on skin\n",
    "\n",
    "Millimetre waves near 35 GHz are absorbed strongly by water, and skin tumours hold more water than\n",
    "healthy skin. A small probe pressed onto the skin therefore reflects differently over a tumour:\n",
    "microwave reflectometry. The probe here is a circular waveguide of 2.5 mm radius filled with PTFE\n",
    "($\\varepsilon_r=2.08$) that tapers into a PTFE cone of 6 mm length with a tip of 1 mm radius. The\n",
    "skin is 1.5 mm thick on fat; the lesion under the tip is 5 mm across and 1 mm deep.\n",
    "\n",
    "The TE11 mode of a circular guide varies as $\\cos\\varphi$, $\\sin\\varphi$: it is the azimuthal mode\n",
    "$m=1$ of a body of revolution. `FrequencyDomainMaxwell` with polarization `Erphiz` and\n",
    "`azimuthal_mode=1` solves all three field components $(E_r,E_\\varphi,E_z)\\,e^{\\mathrm i\\varphi}$ on\n",
    "the meridian plane with Nédélec elements; a `SectionWaveguidePort` on the guide cross-section\n",
    "solves the modes of its line, feeds the TE11 mode and absorbs what comes back. Absorbing layers\n",
    "(`CartesianPML`) 2 mm thick close the air and the tissue.\n",
    "\n",
    "| boundary | condition |\n",
    "|---|---|\n",
    "| `port` (cross-section of the guide) | waveguide port, TE11 ($m=1$), 1 W |\n",
    "| `metal` (guide wall) | perfect electric conductor |\n",
    "| `outer` (behind the absorbing layers) | perfect electric conductor |\n",
    "| axis | regular for $m=1$: $E_\\varphi$ and $E_z$ vanish |\n",
    "\n",
    "Permittivities at 35 GHz (written $\\varepsilon'+\\mathrm i\\varepsilon''$): skin $13.9+14.5\\mathrm i$\n",
    "and fat $3.2+0.9\\mathrm i$ from the Cole-Cole fits of Gabriel et al.; for the tumour tissue of the\n",
    "lesion the model assumes $21+22\\mathrm i$, the skin value with about 50 % more water. They are kept constant over\n",
    "the band.\n",
    "\n",
    "**Reference** (D. M. Pozar, *Microwave Engineering*, 4th ed., §3.4; S. Gabriel, R. W. Lau and\n",
    "C. Gabriel, *Phys. Med. Biol.* 41, 2271 (1996); Poynting's theorem). The port mode must have the\n",
    "propagation constant of the TE11 mode of the PTFE-filled guide,\n",
    "$\\beta=\\sqrt{\\varepsilon_rk_0^2-(x'_{11}/a)^2}$ with $x'_{11}=1.8412$ the first zero of $J_1'$. The\n",
    "reflection is checked by the power balance $1-|S_{11}|^2=P_{abs}+P_{rad}$: $P_{abs}$ from the\n",
    "absorbed power density in skin, lesion and fat, $P_{rad}$ from the Poynting flux\n",
    "$\\tfrac12\\mathrm{Re}(\\mathbf E\\times\\mathbf H^*)\\cdot\\mathbf n\\,2\\pi r$ through the surfaces just inside\n",
    "the absorbing layers - three parts of the solution that are computed independently. A mesh study\n",
    "gives the discretization error of $S_{11}$."
   ]
  },
  {
   "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 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",
    "    SectionWaveguidePort,\n",
    "    port_modes,\n",
    "    scattering_parameters,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.special import jnp_zeros\n",
    "\n",
    "theme.set()\n",
    "\n",
    "mm, radius, ptfe = 1e-3, 2.5e-3, 2.08\n",
    "light = 1 / np.sqrt(VACUUM_PERMEABILITY * VACUUM_PERMITTIVITY)\n",
    "tissue = {\"skin\": 13.9 + 14.5j, \"fat\": 3.2 + 0.9j, \"tumour\": 21.0 + 22.0j}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` reads the half solids of revolution; `section` with the plane $y=0$ returns their meridians:\n",
    "the air, the PTFE of guide and cone, the skin, the fat and the lesion. Quadratic triangles of\n",
    "0.4 mm, 0.16 mm in skin and lesion (the wavelength in skin is about 1.9 mm)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plane = {\n",
    "    name: load(f\"conical_dielectric_probe{name}.step\").section((0, 1, 0))\n",
    "    for name in (\"\", \"_ptfe\", \"_skin\", \"_fat\", \"_lesion\")\n",
    "}\n",
    "section = plane[\"\"]\n",
    "sides = section.boundaries\n",
    "regions = tuple(\n",
    "    plane[f\"_{name}\"].named(name) for name in (\"ptfe\", \"skin\", \"fat\", \"lesion\")\n",
    ")\n",
    "mesher = lambda size: TriangularMesher(\n",
    "    target_size=size,\n",
    "    embedded_regions=regions,\n",
    "    region_sizes={\"skin\": 0.4 * size, \"lesion\": 0.4 * size},\n",
    ")\n",
    "mesh = mesher(0.4 * mm).generate(section)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(12, 9))\n",
    "plots.geometry(\n",
    "    section,\n",
    "    selection={\"port\": sides.port, \"metal\": sides.metal, \"outer\": sides.outer},\n",
    "    labels=False,\n",
    "    title=\"Meridian of probe, skin and fat (STEP)\",\n",
    "    length_unit=\"mm\",\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",
    "    length_unit=\"mm\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The absorbing layers fill the outer 2 mm: beyond $r=6$ mm, below $z=-4$ mm and above $z=8$ mm\n",
    "outside the guide wall. One model per frequency and tissue."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "medium = lambda permittivity: IsotropicElectromagneticMaterial(\n",
    "    relative_permittivity=permittivity\n",
    ")\n",
    "material = lambda frequency, tumour: CartesianPML(\n",
    "    material=RegionwiseElectromagneticMaterial(\n",
    "        {\n",
    "            \"ptfe\": medium(ptfe),\n",
    "            \"skin\": medium(tissue[\"skin\"]),\n",
    "            \"fat\": medium(tissue[\"fat\"]),\n",
    "            \"lesion\": medium(tissue[\"tumour\" if tumour else \"skin\"]),\n",
    "        },\n",
    "        default=medium(1.0),\n",
    "    ),\n",
    "    damping=lambda x, y, z: 4\n",
    "    * np.pi\n",
    "    * frequency\n",
    "    * np.column_stack(\n",
    "        (\n",
    "            np.clip((x - 6 * mm) / (2 * mm), 0, None) ** 2,\n",
    "            0 * x,\n",
    "            np.clip((-4 * mm - z) / (2 * mm), 0, None) ** 2\n",
    "            + np.clip((z - 8 * mm) / (2 * mm), 0, None) ** 2 * (x > 2.8 * mm),\n",
    "        )\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Nedelec(order=2), provider=RevolvedH1SpaceFactory()),\n",
    "    linear_solver=ComplexSparseDirect(),\n",
    ")\n",
    "model = lambda frequency, tumour: FrequencyDomainMaxwell(\n",
    "    domain=section.domain(),\n",
    "    frequency=frequency,\n",
    "    material=material(frequency, tumour),\n",
    "    polarization=\"Erphiz\",\n",
    "    azimuthal_mode=1,\n",
    "    phasor_convention=\"exp(-i*omega*t)\",\n",
    "    amplitude_convention=\"peak\",\n",
    ")\n",
    "solve = lambda physics, grid=mesh: Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"conical probe\",\n",
    "        geometry=section,\n",
    "        physics=(physics,),\n",
    "        boundary_conditions=(\n",
    "            SectionWaveguidePort(\n",
    "                physics=physics, boundary=sides.port, modes=1, incident_power=1.0\n",
    "            ),\n",
    "            PerfectElectricConductor(\n",
    "                physics=physics, boundary=sides.metal | sides.outer\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=grid,\n",
    "    numerics=numerics,\n",
    ").solve_stationary()\n",
    "\n",
    "frequencies = np.linspace(30e9, 40e9, 11)\n",
    "cases = {\n",
    "    (frequency, tumour): model(frequency, tumour)\n",
    "    for frequency in frequencies\n",
    "    for tumour in (False, True)\n",
    "}\n",
    "results = {key: solve(physics) for key, physics in cases.items()}\n",
    "reflection = {\n",
    "    key: scattering_parameters(result, cases[key])[(0, 0)]\n",
    "    for key, result in results.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The port mode against the Bessel cutoff, the reflection with and without tumour, and the power\n",
    "balance. The Poynting flux leaves through $r=6$ mm, $z=-4$ mm and $z=8$ mm ($r>2.8$ mm);\n",
    "$\\mathbf H=\\mathbf B/\\mu_0$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "surfaces = [\n",
    "    ((6 * mm, -4 * mm), (6 * mm, 8 * mm), (1.0, 0.0)),\n",
    "    ((0.0, -4 * mm), (6 * mm, -4 * mm), (0.0, -1.0)),\n",
    "    ((2.8 * mm, 8 * mm), (6 * mm, 8 * mm), (0.0, 1.0)),\n",
    "]\n",
    "steps = np.linspace(0.0, 1.0, 2001)\n",
    "lines = [\n",
    "    (\n",
    "        np.asarray(a) + np.outer(steps, np.subtract(b, a)),\n",
    "        np.hypot(*np.subtract(b, a)),\n",
    "        np.asarray(normal),\n",
    "    )\n",
    "    for a, b, normal in surfaces\n",
    "]\n",
    "flux = {\n",
    "    key: sum(\n",
    "        np.trapezoid(\n",
    "            (\n",
    "                0.5\n",
    "                * np.cross(\n",
    "                    result.field(cases[key].electric_field).evaluate(points),\n",
    "                    np.conj(\n",
    "                        result.field(cases[key].magnetic_flux_density).evaluate(points)\n",
    "                    )\n",
    "                    / VACUUM_PERMEABILITY,\n",
    "                )[:, [0, 2]]\n",
    "                @ normal\n",
    "            ).real\n",
    "            * 2\n",
    "            * np.pi\n",
    "            * points[:, 0],\n",
    "            steps * length,\n",
    "        )\n",
    "        for points, length, normal in lines\n",
    "    )\n",
    "    for key, result in results.items()\n",
    "}\n",
    "absorbed = {\n",
    "    key: result.field(cases[key].absorbed_power_density).integrate().value\n",
    "    for key, result in results.items()\n",
    "}\n",
    "print(\n",
    "    \"frequency   beta TE11 [rad/m]          |S11| [dB]            1-|S11|^2   P_abs    P_rad    P_abs+P_rad\"\n",
    ")\n",
    "print(\"[GHz]       computed      exact        healthy   tumour      (tumour)\")\n",
    "for frequency in frequencies:\n",
    "    k0 = 2 * np.pi * frequency / light\n",
    "    beta = port_modes(results[(frequency, True)], cases[(frequency, True)])[0][\n",
    "        \"propagation_constant\"\n",
    "    ][0].real\n",
    "    exact = np.sqrt(ptfe * k0**2 - (jnp_zeros(1, 1)[0] / radius) ** 2)\n",
    "    key = (frequency, True)\n",
    "    print(\n",
    "        f\"{frequency / 1e9:6.1f}     {beta:9.3f}   {exact:9.3f}     {20 * np.log10(abs(reflection[(frequency, False)])):7.2f}  {20 * np.log10(abs(reflection[key])):7.2f}\"\n",
    "        f\"      {1 - abs(reflection[key]) ** 2:.4f}     {absorbed[key]:.4f}   {flux[key]:.4f}   {absorbed[key] + flux[key]:.4f}\"\n",
    "    )\n",
    "contrast = max(\n",
    "    abs(20 * np.log10(abs(reflection[(f, True)]) / abs(reflection[(f, False)])))\n",
    "    for f in frequencies\n",
    ")\n",
    "balance = max(\n",
    "    abs(1 - abs(reflection[key]) ** 2 - absorbed[key] - flux[key]) for key in results\n",
    ")\n",
    "print(\n",
    "    f\"\\nlargest change of |S11| by the tumour: {contrast:.2f} dB; largest power-balance mismatch: {balance:.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The mesh study at 35 GHz: triangles of 0.25 mm (0.1 mm in skin and lesion)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = mesher(0.25 * mm).generate(section)\n",
    "refined = {\n",
    "    tumour: scattering_parameters(\n",
    "        solve(cases[(35e9, tumour)], fine), cases[(35e9, tumour)]\n",
    "    )[(0, 0)]\n",
    "    for tumour in (False, True)\n",
    "}\n",
    "for tumour, value in refined.items():\n",
    "    print(\n",
    "        f\"{'tumour ' if tumour else 'healthy'}  S11 = {reflection[(35e9, tumour)]:.4f} ({mesh.cell_count} triangles), {value:.4f} ({fine.cell_count} triangles): \"\n",
    "        f\"change {abs(value - reflection[(35e9, tumour)]):.1e}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The reflection over the band with and without tumour, and the electric field in the probe and the\n",
    "tissue at 35 GHz with the tumour."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "r, z = np.asarray(mesh.coordinates).T\n",
    "values = np.linalg.norm(\n",
    "    results[(35e9, True)]\n",
    "    .field(cases[(35e9, True)].electric_field)\n",
    "    .evaluate(np.column_stack((r, z))),\n",
    "    axis=1,\n",
    ")\n",
    "fig = plots.figure(1, 2, size=(14, 7.5))\n",
    "plots.line(\n",
    "    frequencies / 1e9,\n",
    "    {\n",
    "        \"healthy skin\": [\n",
    "            20 * np.log10(abs(reflection[(f, False)])) for f in frequencies\n",
    "        ],\n",
    "        \"tumour lesion under the tip\": [\n",
    "            20 * np.log10(abs(reflection[(f, True)])) for f in frequencies\n",
    "        ],\n",
    "    },\n",
    "    xlabel=\"frequency [GHz]\",\n",
    "    ylabel=\"|S11| [dB]\",\n",
    "    title=\"Reflection of the probe\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.heatmap(\n",
    "    r,\n",
    "    z,\n",
    "    values,\n",
    "    triangles=np.asarray(mesh.cells),\n",
    "    limits=(0, np.percentile(values, 99)),\n",
    "    label=\"|E| [V/m]\",\n",
    "    length_unit=\"mm\",\n",
    "    xlabel=\"r [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    ylimits=(-4 * mm, 12 * mm),\n",
    "    title=\"|E| at 35 GHz with tumour\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the size or depth of the lesion in `conical_dielectric_probe_geometry.py`, or give the probe a longer\n",
    "cone: the field at the tip, and with it the sensitivity, depends on how much of the guided power\n",
    "the cone delivers to its tip rather than radiating it from its flanks. The absorbed power density\n",
    "is the heat source of a bioheat model that gives the temperature rise of the skin."
   ]
  }
 ]
}
