{
 "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": [
    "# Inflation of an artery wall\n",
    "\n",
    "The wall of an artery is a fibre-reinforced soft tissue. At low pressure the soft elastin matrix\n",
    "carries the load and the artery is compliant; as the vessel widens, the wavy collagen fibres,\n",
    "wound helically around it, straighten and the wall stiffens sharply. This protects the vessel\n",
    "against overdistension and is the typical J-shaped response of soft tissue.\n",
    "\n",
    "The model of G.A. Holzapfel, T.C. Gasser and R.W. Ogden (J. Elasticity 61, 2000, 1-48) adds to a\n",
    "neo-Hookean matrix two fibre families at the angles $\\pm\\beta$ to the circumferential direction:\n",
    "\n",
    "$$\\Psi=\\frac{\\mu}{2}(\\bar I_1-3)+\\sum_{i=4,6}\\frac{k_1}{2k_2}\\Big[e^{k_2(\\bar I_i-1)^2}-1\\Big]+\\frac K2(J-1)^2 ,$$\n",
    "\n",
    "with $\\bar I_{4,6}=\\mathbf a_{4,6}\\cdot\\bar{\\mathbf C}\\mathbf a_{4,6}$, the squared stretch of each\n",
    "fibre family; fibres only carry load when stretched, $\\bar I_i>1$.\n",
    "\n",
    "**Setup.** The media of a rabbit carotid artery with the parameters of Holzapfel, Gasser and\n",
    "Ogden (2000): $\\mu=3.0$ kPa, $k_1=2.3632$ kPa, $k_2=0.8393$, $\\beta=29°$; unloaded inner radius\n",
    "0.71 mm, wall thickness 0.26 mm. The adventitia and residual stresses are left out. The\n",
    "segment is first stretched axially by $\\lambda_z=1.5$, then inflated to 16 kPa (120 mmHg).\n",
    "A quarter of a 0.5 mm long segment comes from the CAD file `arterial_wall_inflation.step`,\n",
    "written by `arterial_wall_inflation_geometry.py` with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `lumen` | blood pressure $p$, following the deformed wall |\n",
    "| `adventitia` | free |\n",
    "| `plane_x`, `plane_y` | symmetry |\n",
    "| `bottom`, `top` | axial displacement $0$ and $(\\lambda_z-1)L$, free radially |\n",
    "\n",
    "**Reference.** With smooth ends the tube deforms uniformly along its axis. For the incompressible\n",
    "material the radius $R$ maps to $r^2=r_i^2+(R^2-R_i^2)/\\lambda_z$, and the radial equilibrium\n",
    "integrates to the pressure for a given inner radius $r_i$ (e.g. Holzapfel et al. 2000, Sec. 5):\n",
    "\n",
    "$$p=\\int_{r_i}^{r_o}(\\sigma_{\\theta\\theta}-\\sigma_{rr})\\,\\frac{\\mathrm dr}{r},\\qquad\n",
    "  \\sigma_{\\theta\\theta}-\\sigma_{rr}=\\mu(\\lambda_\\theta^2-\\lambda_r^2)+4k_1(I_4-1)\\,e^{k_2(I_4-1)^2}\\lambda_\\theta^2\\cos^2\\beta ,$$\n",
    "\n",
    "with $\\lambda_\\theta=r/R$, $\\lambda_r=1/(\\lambda_\\theta\\lambda_z)$ and $I_4=\\lambda_\\theta^2\\cos^2\\beta+\\lambda_z^2\\sin^2\\beta$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import TetrahedralMesher\n",
    "from onesim.physics.biophysics import (\n",
    "    ContinuumTissue,\n",
    "    FiberReinforcedTissue,\n",
    "    TissueFiberFamily,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the quarter segment with its named faces; two tetrahedral meshes, 0.15 mm and\n",
    "0.1 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "segment = load(\"arterial_wall_inflation.step\")\n",
    "faces = segment.boundaries\n",
    "inner, wall, length = 0.71e-3, 0.26e-3, segment.size[2]\n",
    "sizes = [0.15e-3, 0.10e-3]\n",
    "meshes = [TetrahedralMesher(target_size=size).generate(segment) for size in sizes]\n",
    "\n",
    "view = plots.Camera(elevation=35, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(13, 6))\n",
    "plots.geometry(\n",
    "    segment,\n",
    "    selection={\n",
    "        \"lumen\": faces.lumen,\n",
    "        \"symmetry\": faces.plane_x | faces.plane_y,\n",
    "        \"ends\": faces.bottom | faces.top,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Quarter of the artery segment\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[-1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Finer mesh: {meshes[-1].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Each fibre family is a direction field: $\\cos\\beta\\,\\mathbf e_\\theta\\pm\\sin\\beta\\,\\mathbf e_z$\n",
    "at every point of the wall. The bulk modulus is $10^4$ times the shear modulus. Two steps\n",
    "stretch the segment, eight raise the pressure."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "shear, stiffness, exponent, angle, axial = (\n",
    "    3.0e3,\n",
    "    2.3632e3,\n",
    "    0.8393,\n",
    "    np.radians(29.0),\n",
    "    1.5,\n",
    ")\n",
    "helix = lambda sign: TissueFiberFamily(\n",
    "    stiffness=stiffness,\n",
    "    exponent=exponent,\n",
    "    direction=lambda x, y, z: np.stack(\n",
    "        (\n",
    "            -np.cos(angle) * y / np.hypot(x, y),\n",
    "            np.cos(angle) * x / np.hypot(x, y),\n",
    "            sign * np.sin(angle) * np.ones_like(x),\n",
    "        ),\n",
    "        axis=-1,\n",
    "    ),\n",
    ")\n",
    "media = ContinuumTissue(\n",
    "    material=FiberReinforcedTissue(\n",
    "        shear_modulus=shear, bulk_modulus=1e4 * shear, fibers=(helix(1), helix(-1))\n",
    "    )\n",
    ")\n",
    "times = np.r_[0.0, 0.1, np.linspace(0.2, 1.0, 9)]\n",
    "blood_pressure = lambda t: 16e3 * max(0.0, (t - 0.2) / 0.8)\n",
    "results = [\n",
    "    media.solve(\n",
    "        mesh=mesh,\n",
    "        times=times,\n",
    "        quadrature_order=3,\n",
    "        pressures=((faces.lumen, blood_pressure),),\n",
    "        displacements=(\n",
    "            (faces.plane_x, \"x\", 0.0),\n",
    "            (faces.plane_y, \"y\", 0.0),\n",
    "            (faces.bottom, \"z\", 0.0),\n",
    "            (faces.top, \"z\", lambda t: (axial - 1) * length * min(1.0, t / 0.2)),\n",
    "        ),\n",
    "    )\n",
    "    for mesh in meshes\n",
    "]\n",
    "nodes = [\n",
    "    int(\n",
    "        np.argmin(\n",
    "            np.linalg.norm(\n",
    "                result.displacement_space.dof_coordinates - (inner, 0.0, length / 2),\n",
    "                axis=1,\n",
    "            )\n",
    "        )\n",
    "    )\n",
    "    for result in results\n",
    "]\n",
    "radius = [\n",
    "    inner + result.displacement[2:, node, 0] for result, node in zip(results, nodes)\n",
    "]\n",
    "pressure = np.array([blood_pressure(t) for t in times[2:]])"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reference: the thick-walled tube\n",
    "\n",
    "The pressure for a given inner radius, integrated over the wall."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def tube_pressure(r_inner):\n",
    "    \"\"\"Inflation pressure of the incompressible HGO tube at the deformed inner radius.\"\"\"\n",
    "    R = np.linspace(inner, inner + wall, 400)\n",
    "    r = np.sqrt(r_inner**2 + (R**2 - inner**2) / axial)\n",
    "    hoop, radial = r / R, R / (r * axial)\n",
    "    fibre = np.maximum(\n",
    "        hoop**2 * np.cos(angle) ** 2 + axial**2 * np.sin(angle) ** 2 - 1, 0.0\n",
    "    )\n",
    "    difference = (\n",
    "        shear * (hoop**2 - radial**2)\n",
    "        + 4\n",
    "        * stiffness\n",
    "        * fibre\n",
    "        * np.exp(exponent * fibre**2)\n",
    "        * hoop**2\n",
    "        * np.cos(angle) ** 2\n",
    "    )\n",
    "    return np.trapezoid(difference * R / (axial * r**2), R)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "The reference pressure at each computed inner radius against the applied pressure, and the\n",
    "inner radius of the reference at the applied pressure against the computed one. Because the\n",
    "collagen stiffens the wall steeply, a small error in the radius is a large one in the pressure."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "line = np.linspace(\n",
    "    0.97 * radius[-1][0], 1.02 * max(values.max() for values in radius), 300\n",
    ")\n",
    "reference_radius = np.interp(pressure, np.array([tube_pressure(r) for r in line]), line)\n",
    "print(\n",
    "    f\"{'pressure [kPa]':>14s}\"\n",
    "    + \"\".join(\n",
    "        f\" {f'r_i, {mesh.cell_count} tets [mm]':>22s} {'p_ref [kPa]':>11s}\"\n",
    "        for mesh in meshes\n",
    "    )\n",
    ")\n",
    "for k, p in enumerate(pressure):\n",
    "    print(\n",
    "        f\"{p / 1e3:14.2f}\"\n",
    "        + \"\".join(\n",
    "            f\" {1e3 * values[k]:22.4f} {tube_pressure(values[k]) / 1e3:11.3f}\"\n",
    "            for values in radius\n",
    "        )\n",
    "    )\n",
    "print(\n",
    "    \"largest deviation of the inner radius from the reference: \"\n",
    "    + \", \".join(\n",
    "        f\"{100 * np.abs(values / reference_radius - 1).max():.2f} % ({mesh.cell_count} tetrahedra)\"\n",
    "        for mesh, values in zip(meshes, radius)\n",
    "    )\n",
    ")\n",
    "print(\n",
    "    \"largest deviation of the pressure from the reference, relative to 16 kPa: \"\n",
    "    + \", \".join(\n",
    "        f\"{100 * max(abs(tube_pressure(r) - p) for r, p in zip(values, pressure)) / 16e3:.2f} % ({mesh.cell_count} tetrahedra)\"\n",
    "        for mesh, values in zip(meshes, radius)\n",
    "    )\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The pressure-radius curve of both meshes with the thick-walled tube solution, and the deviation\n",
    "of the computed inner radius from it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"simulation, {mesh.cell_count} tetrahedra\": (1e3 * values, pressure / 1e3)\n",
    "        for mesh, values in zip(meshes, radius)\n",
    "    },\n",
    "    reference={\n",
    "        \"thick-walled tube\": (\n",
    "            1e3 * line,\n",
    "            np.array([tube_pressure(r) for r in line]) / 1e3,\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"inner radius r_i [mm]\",\n",
    "    ylabel=\"blood pressure p [kPa]\",\n",
    "    title=\"Pressure-radius response\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"{mesh.cell_count} tetrahedra\": (\n",
    "            pressure / 1e3,\n",
    "            100 * (values / reference_radius - 1),\n",
    "        )\n",
    "        for mesh, values in zip(meshes, radius)\n",
    "    },\n",
    "    hlines={\"thick-walled tube\": 0.0},\n",
    "    markers=True,\n",
    "    xlabel=\"blood pressure p [kPa]\",\n",
    "    ylabel=\"deviation of the inner radius [%]\",\n",
    "    title=\"Deviation from the tube solution\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add the adventitia as a second layer with its own parameters ($\\mu=0.3$ kPa, $k_1=0.562$ kPa,\n",
    "$k_2=0.7112$, $\\beta=62°$ in the same paper), or turn the fibres more axially and watch the\n",
    "stiffening move to larger radii. Fibre dispersion is a parameter of each family."
   ]
  }
 ]
}
