{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Arterial pulse wave: how fast a pressure pulse travels along an elastic vessel\n",
    "\n",
    "Blood vessels are compliant tubes: a local rise in pressure widens the vessel,\n",
    "and the interplay between the inertia of the blood and the elasticity of the\n",
    "wall lets a pressure pulse run along the artery much faster than the blood\n",
    "itself moves. For a thin-walled elastic tube of resting radius $r_0$, wall\n",
    "thickness $h$, Young's modulus $E$ and Poisson ratio $\\nu$ the small-amplitude\n",
    "pulse-wave speed is the Moens-Korteweg speed\n",
    "\n",
    "$$c_0=\\sqrt{\\frac{E\\,h}{2\\,\\rho\\,(1-\\nu^2)\\,r_0}} .$$\n",
    "\n",
    "We launch a small, smooth area pulse in a straight vessel, let it split into a\n",
    "forward- and a backward-running pulse, and measure how fast they travel.\n",
    "\n",
    "OneSimulation integrates the one-dimensional cross-section-averaged blood-flow\n",
    "equations for the lumen area $A(x,t)$ and the volume flow $Q(x,t)$,\n",
    "\n",
    "$$\\partial_t A + \\partial_x Q = 0,\\qquad\n",
    "  \\partial_t Q + \\partial_x\\!\\Big(\\frac{Q^2}{A}\\Big) + \\frac{A}{\\rho}\\,\\partial_x p = 0,$$\n",
    "\n",
    "closed by the elastic tube law of `ArterialSegment`,\n",
    "\n",
    "$$p(A) = p_\\mathrm{ext} + \\beta\\Big(\\sqrt{A/A_0}-1\\Big),$$\n",
    "\n",
    "with a second-order finite-volume scheme (minmod reconstruction, Rusanov flux)\n",
    "and characteristic-based junction and terminal conditions.\n",
    "\n",
    "**Reference.** Linearising the system about the resting area $A_0$ gives the\n",
    "wave speed $c^2 = (A/\\rho)\\,\\mathrm{d}p/\\mathrm{d}A$. For the tube law above\n",
    "$\\mathrm{d}p/\\mathrm{d}A = \\beta/(2\\sqrt{A A_0})$, so at $A=A_0$\n",
    "\n",
    "$$c_0=\\sqrt{\\frac{\\beta}{2\\rho}} .$$\n",
    "\n",
    "Matching the tube law to a thin elastic wall gives\n",
    "$\\beta=\\sqrt{\\pi}\\,E h/\\big((1-\\nu^2)\\sqrt{A_0}\\big)$, and with\n",
    "$A_0=\\pi r_0^2$ this $c_0$ is exactly the Moens-Korteweg speed. A linear\n",
    "forward-running pulse also fixes the ratio of its pressure and flow\n",
    "perturbations, the characteristic impedance $Z_0=\\rho c_0/A_0$; we check both."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from onesim.physics.biophysics import (\n",
    "    ArterialNetwork,\n",
    "    ArterialPressure,\n",
    "    ArterialSegment,\n",
    "    WindkesselTerminal,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parameters\n",
    "\n",
    "The vessel is of aortic size with a wall of moderate stiffness, filled with\n",
    "blood. The initial disturbance is a narrow Gaussian area bump of one part in a\n",
    "thousand of the resting area, so the wave stays linear. The run ends before the\n",
    "two pulses reach the ends of the vessel, so the terminals do not influence the\n",
    "speed measurement."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "rho = 1060.0\n",
    "r0 = 0.010\n",
    "h = 1.5e-3\n",
    "E = 4.0e5\n",
    "nu = 0.5\n",
    "L = 1.0\n",
    "x0 = 0.5 * L\n",
    "sigma = 0.03\n",
    "amplitude = 1.0e-3\n",
    "cells = 400\n",
    "final_time = 0.05\n",
    "\n",
    "A0 = np.pi * r0**2\n",
    "beta = np.sqrt(np.pi) * E * h / ((1.0 - nu**2) * np.sqrt(A0))\n",
    "c_formula = np.sqrt(E * h / (2.0 * rho * (1.0 - nu**2) * r0))\n",
    "c_tube_law = np.sqrt(beta / (2.0 * rho))\n",
    "Z0 = rho * c_formula / A0\n",
    "print(f\"A0 = {A0*1e4:.3f} cm^2,  beta = {beta:.0f} Pa\")\n",
    "print(\n",
    "    f\"Moens-Korteweg speed c0 = {c_formula:.4f} m/s,  tube-law speed sqrt(beta/2rho) = {c_tube_law:.4f} m/s,\"\n",
    "    f\"  c0*t = {c_formula*final_time:.3f} m\"\n",
    ")\n",
    "\n",
    "\n",
    "def initial_area(x):\n",
    "    return A0 * (1.0 + amplitude * np.exp(-((x - x0) ** 2) / (2.0 * sigma**2)))\n",
    "\n",
    "\n",
    "vessel = ArterialSegment(\n",
    "    name=\"aorta\",\n",
    "    start=\"inlet\",\n",
    "    end=\"outlet\",\n",
    "    length=L,\n",
    "    cells=cells,\n",
    "    reference_area=A0,\n",
    "    wall_stiffness=beta,\n",
    ")\n",
    "network = ArterialNetwork(\n",
    "    segments=(vessel,),\n",
    "    density=rho,\n",
    "    terminals=(\n",
    "        ArterialPressure(node=\"inlet\", pressure=0.0),\n",
    "        WindkesselTerminal(\n",
    "            node=\"outlet\",\n",
    "            proximal_resistance=Z0,\n",
    "            distal_resistance=5.0 * Z0,\n",
    "            compliance=1.0e-9,\n",
    "            reference_pressure=0.0,\n",
    "            initial_pressure=0.0,\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "result = network.solve(\n",
    "    times=np.linspace(0.0, final_time, 6),\n",
    "    max_step=1.0e-3,\n",
    "    initial_area={\"aorta\": initial_area},\n",
    "    initial_flow={\"aorta\": lambda x: np.zeros_like(x)},\n",
    ")\n",
    "print(\n",
    "    f\"Integrated to t = {result.times[-1]:.4f} s with {len(result.stage_times)} explicit stages\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Measure the pulse speed and the characteristic impedance\n",
    "\n",
    "The relative area perturbation $\\delta A/A_0$ at the final time consists of\n",
    "two pulses that keep their shape. The centroid of $|\\delta A|$ on each half of\n",
    "the vessel marks the pulse position; the travelled distance divided by the\n",
    "elapsed time is the measured speed. On the forward pulse the flow and pressure\n",
    "perturbations are tied by $\\delta p = Z_0\\,Q$ (and $\\delta p=-Z_0 Q$ on the\n",
    "backward pulse), which gives an independent check of the wall law."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "x = result.coordinates[\"aorta\"]\n",
    "area_final = result.area[\"aorta\"][-1]\n",
    "flow_final = result.flow[\"aorta\"][-1]\n",
    "pressure_final = result.pressure[\"aorta\"][-1]\n",
    "t_end = float(result.times[-1])\n",
    "\n",
    "delta_a = area_final / A0 - 1.0\n",
    "weight = np.abs(delta_a)\n",
    "right = x > x0\n",
    "left = x < x0\n",
    "centroid_right = np.sum(x[right] * weight[right]) / np.sum(weight[right])\n",
    "centroid_left = np.sum(x[left] * weight[left]) / np.sum(weight[left])\n",
    "speed_right = (centroid_right - x0) / t_end\n",
    "speed_left = (x0 - centroid_left) / t_end\n",
    "speed_measured = 0.5 * (speed_right + speed_left)\n",
    "rel_error = abs(speed_measured - c_formula) / c_formula\n",
    "\n",
    "print(f\"forward  pulse speed = {speed_right:.4f} m/s\")\n",
    "print(f\"backward pulse speed = {speed_left:.4f} m/s\")\n",
    "print(f\"measured pulse speed = {speed_measured:.4f} m/s\")\n",
    "print(f\"relative error vs Moens-Korteweg = {100*rel_error:.2f} %\")\n",
    "\n",
    "peak_right = np.argmax(np.where(right, delta_a, -np.inf))\n",
    "peak_left = np.argmax(np.where(left, delta_a, -np.inf))\n",
    "Z_right = pressure_final[peak_right] / flow_final[peak_right]\n",
    "Z_left = -pressure_final[peak_left] / flow_final[peak_left]\n",
    "Z_measured = 0.5 * (Z_right + Z_left)\n",
    "Z_error = abs(Z_measured - Z0) / Z0\n",
    "print(\n",
    "    f\"peak pressure of the forward pulse = {pressure_final[peak_right]:.2f} Pa,\"\n",
    "    f\"  peak flow = {flow_final[peak_right]*1e6:.3f} ml/s\"\n",
    ")\n",
    "print(\n",
    "    f\"characteristic impedance: measured {Z_measured:.4e}, rho*c0/A0 = {Z0:.4e} Pa·s/m^3\"\n",
    "    f\"  (relative error {100*Z_error:.2f} %)\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "predicted = [x0 - c_formula * t_end, x0 + c_formula * t_end]\n",
    "fig = plots.figure(1, 2, size=(12, 4.8))\n",
    "plots.line(\n",
    "    x,\n",
    "    {\n",
    "        f\"computed, t = {t_end * 1e3:.0f} ms\": delta_a * 1e3,\n",
    "        \"initial area bump\": (result.area[\"aorta\"][0] / A0 - 1.0) * 1e3,\n",
    "    },\n",
    "    points={\"predicted x0 ± c0 t\": (predicted, np.interp(predicted, x, delta_a * 1e3))},\n",
    "    vlines={\"measured pulse centroids\": centroid_left, \"\": centroid_right},\n",
    "    xlabel=\"position along the vessel x [m]\",\n",
    "    ylabel=\"area perturbation dA/A0 [‰]\",\n",
    "    title=f\"Pulse speed: measured {speed_measured:.3f} m/s, Moens-Korteweg {c_formula:.3f} m/s\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    x,\n",
    "    {\"pressure perturbation\": pressure_final},\n",
    "    reference={\"Z0 Q with Z0 = rho c0 / A0\": Z0 * flow_final},\n",
    "    xlabel=\"position along the vessel x [m]\",\n",
    "    ylabel=\"pressure [Pa]\",\n",
    "    title=\"Forward pulse: p = +Z0 Q, backward pulse: p = -Z0 Q\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Stiffen the wall (`E`) or thin the lumen (`r0`) and watch the pulse run faster\n",
    "as $\\sqrt{E h/r_0}$: arterial stiffening with age shows up directly as a\n",
    "higher pulse-wave velocity. Lengthen `final_time` so the forward pulse reaches\n",
    "the outlet: with the proximal resistance matched to $Z_0$ it is absorbed almost\n",
    "without reflection, while a sealed outlet (`ArterialInflow(flow=0)`) sends it\n",
    "back doubled in pressure. Raise `amplitude` towards unity and the crest, which\n",
    "travels faster than the trough, steepens into a shock-like front."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
