{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d750964c",
   "metadata": {},
   "source": [
    "# Womersley pulsatile flow between parallel plates\n",
    "\n",
    "A viscous fluid fills the gap between two fixed plates a distance $2h$ apart. A pressure gradient\n",
    "that oscillates in time, $-\\partial p/\\partial x = G\\cos\\omega t$, drives the flow $u(y,t)$:\n",
    "\n",
    "$$\\rho\\,\\frac{\\partial u}{\\partial t}=G\\cos\\omega t+\\mu\\,\\frac{\\partial^2 u}{\\partial y^2},\n",
    "  \\qquad u(\\pm h,t)=0 .$$\n",
    "\n",
    "The channel comes from the CAD file `womersley_pulsatile_flow.step`, a thin slab between the\n",
    "plates `y_min` and `y_max`. The script `womersley_pulsatile_flow_geometry.py` builds it with the\n",
    "CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** The periodic state is the Womersley solution $u=\\operatorname{Re}\\{U(y)\\,e^{i\\omega t}\\}$,\n",
    "\n",
    "$$U(y)=\\frac{G}{i\\rho\\omega}\\left[1-\\frac{\\cosh(k y)}{\\cosh(k h)}\\right],\\qquad k=\\sqrt{\\frac{i\\omega}{\\nu}} .$$\n",
    "\n",
    "It is governed by the Womersley number $\\alpha=h\\sqrt{\\omega/\\nu}$. For small $\\alpha$ the profile\n",
    "is a parabola in phase with the forcing. For $\\alpha=3$, as here, the core is flattened and lags\n",
    "the pressure gradient, while the layers near the walls respond first."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7d2b3702",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import NewtonianFluid\n",
    "from onesim.meshing import PeriodicPair, StructuredTetrahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, TaylorHood\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.hydrodynamics import IncompressibleNavierStokes, NoSlipWall\n",
    "from onesim.simulation import PeriodicBoundary, Problem, Simulation\n",
    "from onesim.simulation.field_constraints import MeanValue\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7991468c",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The slab is periodic along the flow and across the span; the mesher joins the opposite faces."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64be7465",
   "metadata": {},
   "outputs": [],
   "source": [
    "channel = load(\"womersley_pulsatile_flow.step\")\n",
    "faces = channel.boundaries\n",
    "length, gap, span = channel.size\n",
    "half_gap = gap / 2\n",
    "along, across = PeriodicPair(faces.x_min, faces.x_max), PeriodicPair(\n",
    "    faces.z_min, faces.z_max\n",
    ")\n",
    "mesh = StructuredTetrahedralMesher(\n",
    "    cells=(1, 12, 1), periodic_pairs=(along, across)\n",
    ").generate(channel)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(12, 5.5))\n",
    "plots.geometry(\n",
    "    channel,\n",
    "    selection={\"plates\": faces.y_min | faces.y_max},\n",
    "    labels=False,\n",
    "    title=\"Slab of the channel with its two plates\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"{mesh.cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae4b7f2e",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The pressure gradient acts as a body force. Taylor-Hood elements in space and the second-order\n",
    "BDF method with 40 steps per period in time; the flow starts from rest."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1341f41d",
   "metadata": {},
   "outputs": [],
   "source": [
    "forcing, womersley_number = 1.0, 3.0\n",
    "water = NewtonianFluid(density=1000.0, dynamic_viscosity=1.0e-3)\n",
    "viscosity = water.dynamic_viscosity / water.density\n",
    "omega = (womersley_number / half_gap) ** 2 * viscosity\n",
    "period = 2 * np.pi / omega\n",
    "\n",
    "\n",
    "def womersley(y, t):\n",
    "    \"\"\"Velocity of the Womersley solution at the distance y from the channel centre.\"\"\"\n",
    "    k = np.sqrt(1j * omega / viscosity)\n",
    "    return np.real(\n",
    "        forcing\n",
    "        / (1j * water.density * omega)\n",
    "        * (1 - np.cosh(k * y) / np.cosh(k * half_gap))\n",
    "        * np.exp(1j * omega * t)\n",
    "    )\n",
    "\n",
    "\n",
    "model = IncompressibleNavierStokes(\n",
    "    domain=channel.volume,\n",
    "    material=water,\n",
    "    body_force=lambda x, t: np.column_stack(\n",
    "        (np.full_like(x, forcing * np.cos(omega * t)), 0 * x, 0 * x)\n",
    "    ),\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Womersley pulsatile channel flow\",\n",
    "    geometry=channel,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        NoSlipWall(boundary=faces.y_min | faces.y_max, physics=model),\n",
    "        PeriodicBoundary(pair=along, physics=model),\n",
    "        PeriodicBoundary(pair=across, physics=model),\n",
    "    ),\n",
    "    constraints=(MeanValue(model.pressure, 0.0),),\n",
    "    initial_conditions=(InitialValue(model.velocity, (0.0, 0.0, 0.0)),),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=TaylorHood()),\n",
    "    time_integrator=BDF(order=2, startup=BackwardEuler()),\n",
    "    linear_solver=SparseDirect(),\n",
    "    nonlinear_solver=Newton(\n",
    "        linear_solver=SparseDirect(), absolute_tolerance=1e-12, relative_tolerance=0.0\n",
    "    ),\n",
    ")\n",
    "result = Simulation(problem=problem, mesh=mesh, numerics=numerics).run(\n",
    "    start_time=0.0, end_time=4 * period, time_step=period / 40\n",
    ")\n",
    "velocity = result.field(model.velocity)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad421c43",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The velocity across the gap is recorded over the fourth period, when the start-up has died out."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3d0aa1c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "y = np.linspace(-half_gap, half_gap, 25)\n",
    "times, history = velocity.time_series(\n",
    "    np.column_stack(\n",
    "        (np.full_like(y, length / 2), y + half_gap, np.full_like(y, span / 2))\n",
    "    )\n",
    ")\n",
    "times, u = times[-41:], history[-41:, :, 0]\n",
    "scale = np.abs(womersley(0.0, times)).max()\n",
    "print(\"phase of the forcing   largest deviation from the Womersley profile\")\n",
    "for step in (0, 10, 20, 30):\n",
    "    print(\n",
    "        f\"{9 * step:14d}°        {100 * np.abs(u[step] - womersley(y, times[step])).max() / scale:.2f} % of the centre-line amplitude\"\n",
    "    )\n",
    "print(\n",
    "    f\"centre-line amplitude: simulation {1e3 * np.abs(u[:, 12]).max():.4f} mm/s, Womersley {1e3 * scale:.4f} mm/s, \"\n",
    "    f\"quasi-steady parabola {1e3 * forcing * half_gap**2 / (2 * water.dynamic_viscosity):.4f} mm/s\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5bc8f22d",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Velocity profiles at four phases of the forcing, and the centre-line velocity over one period\n",
    "against the Womersley solution and the quasi-steady response."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23601365",
   "metadata": {},
   "outputs": [],
   "source": [
    "fine_y, fine_t = np.linspace(-half_gap, half_gap, 121), np.linspace(\n",
    "    times[0], times[-1], 200\n",
    ")\n",
    "phases = {f\"ωt = {9 * step}°\": step for step in (0, 10, 20, 30)}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(12, 5))\n",
    "plots.line(\n",
    "    points={label: (1e3 * u[step], 1e3 * y) for label, step in phases.items()},\n",
    "    reference={\n",
    "        label: (1e3 * womersley(fine_y, times[step]), 1e3 * fine_y)\n",
    "        for label, step in phases.items()\n",
    "    },\n",
    "    xlabel=\"velocity [mm/s]\",\n",
    "    ylabel=\"distance from the centre [mm]\",\n",
    "    title=\"Profiles: simulation (markers), Womersley (dashed)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (times / period, 1e3 * u[:, 12])},\n",
    "    reference={\n",
    "        \"Womersley\": (fine_t / period, 1e3 * womersley(0.0, fine_t)),\n",
    "        \"quasi-steady response\": (\n",
    "            fine_t / period,\n",
    "            1e3\n",
    "            * forcing\n",
    "            * half_gap**2\n",
    "            / (2 * water.dynamic_viscosity)\n",
    "            * np.cos(omega * fine_t),\n",
    "        ),\n",
    "    },\n",
    "    xlabel=\"time [periods]\",\n",
    "    ylabel=\"centre-line velocity [mm/s]\",\n",
    "    title=\"Centre line: smaller amplitude and phase lag\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "001f4692",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lower the Womersley number to 0.5 and the profile becomes a parabola in phase with the forcing;\n",
    "raise it to 10 and the core moves as a plug with thin Stokes layers at the walls. Change the gap\n",
    "in `womersley_pulsatile_flow_geometry.py` and write the STEP file again; the frequency follows\n",
    "from the Womersley number. A circular pipe gives the classical solution with Bessel functions."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
