{
 "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": [
    "# Heating of perfused tissue: the Pennes bioheat equation\n",
    "\n",
    "Blood flowing through the capillaries carries heat away from warm tissue and brings it\n",
    "into cold tissue. H. H. Pennes (1948) modelled this as a heat sink proportional to the\n",
    "difference between the local tissue temperature and the arterial blood temperature\n",
    "$T_b$:\n",
    "\n",
    "$$\\rho c\\,\\frac{\\partial T}{\\partial t}=k\\,\\frac{\\partial^2T}{\\partial x^2}\n",
    "  +\\omega_b\\rho_bc_b\\,(T_b-T)+Q_m,$$\n",
    "\n",
    "with the perfusion rate $\\omega_b$ (volume of blood per volume of tissue and second).\n",
    "Here a contact heater brings the skin surface $x=0$ to $T_s=45$ °C at $t=0$, the deep\n",
    "tissue at $x=L$ stays at $T_b=37$ °C, and the metabolic heat $Q_m$ is neglected, so\n",
    "the tissue starts in equilibrium at $T_b$.\n",
    "\n",
    "OneSimulation solves the equation with its `PennesBioheat` model (temperature in K,\n",
    "perfusion as the volumetric capacity rate $\\omega_b\\rho_bc_b$, blood temperature) on a\n",
    "line through the tissue, with quadratic finite elements and BDF2 steps. Below,\n",
    "$\\alpha=k/\\rho c$ is the thermal diffusivity and $w=\\omega_b\\rho_bc_b/\\rho c$ the perfusion rate.\n",
    "\n",
    "| Boundary | Condition |\n",
    "|---|---|\n",
    "| $x=0$, skin surface | $T=T_s=45$ °C from $t=0$ |\n",
    "| $x=L$, deep tissue | $T=T_b=37$ °C |\n",
    "\n",
    "**Reference.** H. H. Pennes, *Analysis of tissue and arterial blood temperatures in\n",
    "the resting human forearm*, J. Appl. Physiol. 1, 93-122 (1948); H. S. Carslaw and\n",
    "J. C. Jaeger, *Conduction of Heat in Solids*, 2nd ed., Oxford 1959, §3.4 and §15.\n",
    "With $\\theta=T-T_b$, $m^2=\\omega_b\\rho_bc_b/k$ and $\\Delta T=T_s-T_b$ the solution is\n",
    "\n",
    "$$\\theta(x,t)=\\Delta T\\,\\frac{\\sinh m(L-x)}{\\sinh mL}\n",
    "  -\\Delta T\\sum_{n\\ge1}\\frac{2n\\pi}{(n\\pi)^2+(mL)^2}\\,\\sin\\frac{n\\pi x}{L}\\,\n",
    "  \\exp\\!\\Big[-\\Big(\\alpha\\frac{n^2\\pi^2}{L^2}+w\\Big)t\\Big].$$\n",
    "\n",
    "Perfusion shortens the thermal penetration depth to $1/m$ and lets the tissue reach its\n",
    "steady state faster, at the rate $\\alpha\\pi^2/L^2+w$ instead of $\\alpha\\pi^2/L^2$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d1 import Line\n",
    "from onesim.meshing import StructuredLineMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, Nitsche\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.numerics.time import BDF, BackwardEuler\n",
    "from onesim.physics.biophysics import PennesBioheat\n",
    "from onesim.simulation import PrescribedValueBoundary, Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Tissue\n",
    "\n",
    "Soft tissue 30 mm deep (density 1050 kg/m³, heat capacity 3600 J/(kg K), conductivity\n",
    "0.5 W/(m K)) perfused at $\\omega_b=5\\times10^{-4}$ 1/s by blood with\n",
    "$\\rho_bc_b=1060\\cdot3770$ J/(m³ K); one hour of heating. The same layer without\n",
    "perfusion serves as the contrast."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "depth, density, capacity, conductivity = 0.03, 1050.0, 3600.0, 0.5\n",
    "blood, surface, perfusion = 310.15, 318.15, 5e-4 * 1060.0 * 3770.0\n",
    "diffusivity = conductivity / (density * capacity)\n",
    "cases = {\"perfused\": perfusion, \"no perfusion\": 0.0}\n",
    "print(\n",
    "    f\"thermal diffusivity {diffusivity:.3e} m²/s, diffusion time L²/α = {depth**2 / diffusivity / 60:.0f} min, \"\n",
    "    f\"perfusion time ρc/(ω ρb cb) = {density * capacity / perfusion / 60:.0f} min, penetration depth 1/m = {1e3 * np.sqrt(conductivity / perfusion):.1f} mm\"\n",
    ")\n",
    "line = Line(start=(0.0, 0.0, 0.0), end=(depth, 0.0, 0.0))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulation and mesh study\n",
    "\n",
    "Each case on 10, 20 and 40 quadratic elements with 1800 BDF2 steps of 2 s."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "models = {\n",
    "    name: PennesBioheat(\n",
    "        domain=line.line,\n",
    "        density=density,\n",
    "        heat_capacity=capacity,\n",
    "        conductivity=conductivity,\n",
    "        perfusion_capacity_rate=w,\n",
    "        blood_temperature=blood,\n",
    "    )\n",
    "    for name, w in cases.items()\n",
    "}\n",
    "runs = {\n",
    "    (name, cells): Simulation(\n",
    "        problem=Problem(\n",
    "            name=f\"Pennes bioheat, {name}\",\n",
    "            geometry=line,\n",
    "            physics=(model,),\n",
    "            boundary_conditions=(\n",
    "                PrescribedValueBoundary(\n",
    "                    physics=model,\n",
    "                    boundary=line.boundaries.start,\n",
    "                    value=lambda time, **_: {\"temperature\": surface},\n",
    "                ),\n",
    "                PrescribedValueBoundary(\n",
    "                    physics=model,\n",
    "                    boundary=line.boundaries.end,\n",
    "                    value=lambda time, **_: {\"temperature\": blood},\n",
    "                ),\n",
    "            ),\n",
    "            initial_conditions=(InitialValue(model.temperature, blood),),\n",
    "        ),\n",
    "        mesh=StructuredLineMesher(cells=cells).generate(line),\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(\n",
    "                element=Lagrange(order=2), boundary_enforcement=Nitsche()\n",
    "            ),\n",
    "            nonlinear_solver=Newton(linear_solver=SparseDirect(), jacobian=\"analytic\"),\n",
    "            time_integrator=BDF(order=2, startup=BackwardEuler()),\n",
    "        ),\n",
    "    ).run(start_time=0.0, end_time=3600.0, time_step=2.0)\n",
    "    for name, model in models.items()\n",
    "    for cells in (10, 20, 40)\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Closed-form solution\n",
    "\n",
    "The steady profile and 2000 terms of the eigenfunction series."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def pennes(x, t, w):\n",
    "    m, n = np.sqrt(w / conductivity) + 1e-12, np.arange(1, 2001)[:, None]\n",
    "    series = (\n",
    "        2\n",
    "        * n\n",
    "        * np.pi\n",
    "        / ((n * np.pi) ** 2 + (m * depth) ** 2)\n",
    "        * np.sin(n * np.pi * x / depth)\n",
    "        * np.exp(\n",
    "            -(diffusivity * (n * np.pi / depth) ** 2 + w / (density * capacity)) * t\n",
    "        )\n",
    "    ).sum(axis=0)\n",
    "    return blood + (surface - blood) * (\n",
    "        np.sinh(m * (depth - x)) / np.sinh(m * depth) - series\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison\n",
    "\n",
    "The temperature on a fine line through the tissue at 5, 15, 30 and 60 minutes, and the\n",
    "largest deviation over these times for each mesh."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(0.0, depth, 301)\n",
    "points = np.column_stack((x, np.zeros_like(x), np.zeros_like(x)))\n",
    "moments = (300.0, 900.0, 1800.0, 3600.0)\n",
    "profiles = {\n",
    "    key: {\n",
    "        t: np.asarray(\n",
    "            r.field(models[key[0]].temperature).evaluate(points, time=t)\n",
    "        ).reshape(-1)\n",
    "        for t in moments\n",
    "    }\n",
    "    for key, r in runs.items()\n",
    "}\n",
    "print(\n",
    "    \"case            elements   largest deviation [K]   at t = 60 min: T(5 mm) [°C]   series [°C]\"\n",
    ")\n",
    "for (name, cells), profile in profiles.items():\n",
    "    deviation = max(\n",
    "        np.abs(profile[t] - pennes(x, t, cases[name])).max() for t in moments\n",
    "    )\n",
    "    print(\n",
    "        f\"{name:15s} {cells:8d} {deviation:22.2e} {profile[3600.0][50] - 273.15:28.3f} {pennes(x[50:51], 3600.0, cases[name])[0] - 273.15:13.3f}\"\n",
    "    )\n",
    "errors = {\n",
    "    name: [\n",
    "        max(np.abs(profiles[(name, c)][t] - pennes(x, t, w)).max() for t in moments)\n",
    "        for c in (10, 20, 40)\n",
    "    ]\n",
    "    for name, w in cases.items()\n",
    "}\n",
    "print(\n",
    "    \"observed orders:\",\n",
    "    {\n",
    "        name: [round(float(np.log2(e[i] / e[i + 1])), 2) for i in range(2)]\n",
    "        for name, e in errors.items()\n",
    "    },\n",
    ")\n",
    "steady = {name: pennes(x, 1e9, w) for name, w in cases.items()}\n",
    "print(\n",
    "    f\"depth where the tissue is heated by 4 K after one hour: perfused {1e3 * x[np.argmax(profiles[('perfused', 40)][3600.0] < blood + 4)]:.1f} mm, \"\n",
    "    f\"without perfusion {1e3 * x[np.argmax(profiles[('no perfusion', 40)][3600.0] < blood + 4)]:.1f} mm\"\n",
    ")\n",
    "print(\n",
    "    f\"one hour reaches {np.trapezoid(profiles[('perfused', 40)][3600.0] - blood, x) / np.trapezoid(steady['perfused'] - blood, x):.1%} of the \"\n",
    "    f\"steady heat content with perfusion, {np.trapezoid(profiles[('no perfusion', 40)][3600.0] - blood, x) / np.trapezoid(steady['no perfusion'] - blood, x):.1%} without\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The heating profiles with and without perfusion against the closed form, and the\n",
    "mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(17, 5))\n",
    "for index, name in enumerate(cases):\n",
    "    plots.line(\n",
    "        points={\n",
    "            f\"{t / 60:.0f} min\": (1e3 * x[::10], profiles[(name, 40)][t][::10] - 273.15)\n",
    "            for t in moments\n",
    "        },\n",
    "        reference={\n",
    "            f\"{t / 60:.0f} min\": (1e3 * x, pennes(x, t, cases[name]) - 273.15)\n",
    "            for t in moments\n",
    "        }\n",
    "        | {\"steady state\": (1e3 * x, steady[name] - 273.15)},\n",
    "        xlabel=\"depth below the skin x [mm]\",\n",
    "        ylabel=\"tissue temperature [°C]\",\n",
    "        ylimits=(36.5, 45.5),\n",
    "        title=f\"{name.capitalize()} (dashed: closed form)\",\n",
    "        legend=\"upper right\",\n",
    "        ax=fig[index],\n",
    "    )\n",
    "plots.convergence(\n",
    "    1e3 * depth / np.array([10, 20, 40]),\n",
    "    {name: np.array(e) for name, e in errors.items()},\n",
    "    order=3,\n",
    "    xlabel=\"element size [mm]\",\n",
    "    ylabel=\"largest temperature deviation [K]\",\n",
    "    title=\"Mesh study\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add the metabolic heat as a further source term, $Q_m/\\rho c$, and the equilibrium\n",
    "shifts to $T_b+Q_m/(\\omega_b\\rho_bc_b)$. A time-dependent surface temperature turns the\n",
    "case into the periodic skin-heating problem, whose penetration depth depends on both the\n",
    "frequency and the perfusion. Thermal dose (CEM43) follows from the computed history\n",
    "by integrating $R^{43-T}$ over time at each depth."
   ]
  }
 ]
}
