{
 "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": [
    "# Water hammer after a fast valve closure\n",
    "\n",
    "A constant-head reservoir feeds a horizontal pipe of length $L$ and diameter $D$\n",
    "that ends in a valve discharging to the atmosphere. Water flows steadily at the\n",
    "mean velocity $v_0$. At $t=0$ the valve starts to close and is shut after the\n",
    "closure time $t_c$. The decelerated water column is slightly compressible and the\n",
    "pipe wall slightly elastic, so the stopped flow sends a pressure wave up the pipe\n",
    "at the speed $a$; it is reflected at the reservoir and returns to the valve.\n",
    "\n",
    "OneSimulation solves the one-dimensional water-hammer equations for the pressure\n",
    "$p(x,t)$ and the volume flow $Q(x,t)$,\n",
    "\n",
    "$$\\frac{A}{\\rho a^2}\\,\\frac{\\partial p}{\\partial t}+\\frac{\\partial Q}{\\partial x}=0,\\qquad\n",
    "  \\frac{\\rho}{A}\\,\\frac{\\partial Q}{\\partial t}+\\frac{\\partial p}{\\partial x}\n",
    "  +\\frac{f\\rho}{2DA^2}\\,Q\\,|Q|=0,$$\n",
    "\n",
    "on a staggered pipe grid with an energy-conserving implicit-midpoint time step.\n",
    "\n",
    "| End | Condition |\n",
    "|---|---|\n",
    "| $x=0$, reservoir | $p=p_r$ (constant head) |\n",
    "| $x=L$, valve | $p=R\\,Q\\,|Q|/\\tau(t)^2$, opening $\\tau$ from 1 to 0 in $t_c$ |\n",
    "\n",
    "**Reference.** For a closure faster than the return time $2L/a$ the pressure at the\n",
    "valve rises by the Joukowsky value (N. Joukowsky, 1898; E. B. Wylie and V. L.\n",
    "Streeter, *Fluid Transients in Systems*, Prentice Hall 1993, ch. 1-3)\n",
    "\n",
    "$$\\Delta p_J=\\rho\\,a\\,v_0,$$\n",
    "\n",
    "stays there for $2L/a$, then drops to $p_r-\\Delta p_J$ for another $2L/a$: without\n",
    "friction the valve pressure is a square wave of period $T=4L/a$. The exact solution\n",
    "of the frictionless pipe follows from the characteristics: with the valve wave\n",
    "$F(t)=Z\\,(Q_0-Q_v(t))$, $Z=\\rho a/A$, and the reflection $-1$ at the reservoir,\n",
    "\n",
    "$$p_v(t)-p_r=F(t)+2\\sum_{k\\ge1}(-1)^k\\,F\\!\\left(t-\\frac{2kL}{a}\\right),$$\n",
    "\n",
    "where $Q_v$ is the valve flow during the closure, from the valve law and the\n",
    "characteristic $p_v=p_r+Z\\,(Q_0-Q_v)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.physics.systems import (\n",
    "    HydraulicPressurePort,\n",
    "    HydraulicValvePort,\n",
    "    WaterHammerNetwork,\n",
    "    WaterHammerPipe,\n",
    ")\n",
    "from onesim.results.sampling import crossing_times\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Pipe and valve\n",
    "\n",
    "A steel water main of 600 m and 0.5 m diameter with a wave speed of 1200 m/s, fed by\n",
    "a reservoir 150 m above the valve. The valve loss coefficient is chosen so that the\n",
    "initial flow is 1 m/s; the valve closes with a smooth cosine schedule in 0.2 s, a\n",
    "fifth of the return time $2L/a=1$ s."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "density, length, diameter, wave_speed, velocity = 1000.0, 600.0, 0.5, 1200.0, 1.0\n",
    "reservoir_pressure, closure_time = density * 9.81 * 150.0, 0.2\n",
    "area = np.pi * diameter**2 / 4\n",
    "flow = velocity * area\n",
    "resistance = reservoir_pressure / flow**2\n",
    "impedance = density * wave_speed / area\n",
    "closing = lambda t: 0.5 + 0.5 * np.cos(np.pi * np.clip(t / closure_time, 0.0, 1.0))\n",
    "joukowsky, period = density * wave_speed * velocity, 4.0 * length / wave_speed\n",
    "print(\n",
    "    f\"initial flow {flow * 1e3:.1f} L/s, reservoir pressure {reservoir_pressure / 1e5:.2f} bar\"\n",
    ")\n",
    "print(\n",
    "    f\"Joukowsky rise ρ a v0 = {joukowsky / 1e5:.2f} bar, period 4L/a = {period:.2f} s, closure in {closure_time / (2 * length / wave_speed):.0%} of 2L/a\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulation on three grids\n",
    "\n",
    "Eight seconds (four periods) on 100, 200 and 400 cells with a time step of half the\n",
    "cell transit time. The pipe starts in the steady state: uniform reservoir pressure\n",
    "and the initial flow everywhere."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "times = np.linspace(0.0, 8.0, 1601)\n",
    "runs = {\n",
    "    cells: WaterHammerNetwork(\n",
    "        pipes=(\n",
    "            WaterHammerPipe(\n",
    "                name=\"main\",\n",
    "                start=\"reservoir\",\n",
    "                end=\"valve\",\n",
    "                length=length,\n",
    "                diameter=diameter,\n",
    "                wave_speed=wave_speed,\n",
    "                cells=cells,\n",
    "            ),\n",
    "        ),\n",
    "        ports=(\n",
    "            HydraulicPressurePort(node=\"reservoir\", pressure=reservoir_pressure),\n",
    "            HydraulicValvePort(\n",
    "                node=\"valve\",\n",
    "                downstream_pressure=0.0,\n",
    "                resistance=resistance,\n",
    "                opening=closing,\n",
    "            ),\n",
    "        ),\n",
    "        density=density,\n",
    "    ).solve(\n",
    "        times=times,\n",
    "        max_step=0.5 * length / wave_speed / cells,\n",
    "        initial_pressure=reservoir_pressure,\n",
    "        initial_flow=flow,\n",
    "    )\n",
    "    for cells in (100, 200, 400)\n",
    "}\n",
    "result = runs[400]\n",
    "surge = {\n",
    "    cells: run.pressure[\"main\"][:, -1] - reservoir_pressure\n",
    "    for cells, run in runs.items()\n",
    "}\n",
    "distance = {\n",
    "    cells: length - run.pressure_coordinates[\"main\"][-1] for cells, run in runs.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Characteristic solution\n",
    "\n",
    "The pressure is compared in the cell next to the valve, half a cell upstream of it.\n",
    "At the distance $d$ from the valve the outgoing wave arrives $d/a$ later and the wave\n",
    "reflected at the reservoir $d/a$ earlier than at the valve itself. The valve wave\n",
    "$F(t)$ solves the quadratic valve law along the characteristic; before $t=0$ it is\n",
    "zero by construction."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def characteristic_surge(t, d):\n",
    "    total = reservoir_pressure + impedance * flow\n",
    "    wave = lambda s: impedance * (\n",
    "        flow\n",
    "        - 2\n",
    "        * total\n",
    "        * closing(s)\n",
    "        / (\n",
    "            impedance * closing(s)\n",
    "            + np.sqrt((impedance * closing(s)) ** 2 + 4 * total * resistance)\n",
    "        )\n",
    "    )\n",
    "    return sum(\n",
    "        (-1) ** k\n",
    "        * (\n",
    "            wave(t - (2 * k * length + d) / wave_speed)\n",
    "            - wave(t - (2 * (k + 1) * length - d) / wave_speed)\n",
    "        )\n",
    "        for k in range(9)\n",
    "    )\n",
    "\n",
    "\n",
    "exact = {cells: characteristic_surge(times, d) for cells, d in distance.items()}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison\n",
    "\n",
    "The plateau pressure is the median of the surge in the first half period after the\n",
    "closure; the period comes from the interpolated downward zero crossings. The\n",
    "overshoot at the steep wave fronts and the rms deviation from the exact solution\n",
    "shrink as the grid is refined."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plateau = (times > 2 * closure_time) & (times < 2 * length / wave_speed)\n",
    "crossings = {\n",
    "    cells: crossing_times(times, p, 0.0, direction=\"falling\")\n",
    "    for cells, p in surge.items()\n",
    "}\n",
    "print(\n",
    "    \" cells   plateau rise [bar]   Joukowsky [bar]   peak [bar]   period [s]   rms deviation from exact\"\n",
    ")\n",
    "for cells, p in surge.items():\n",
    "    print(\n",
    "        f\"{cells:6d} {np.median(p[plateau]) / 1e5:17.4f} {joukowsky / 1e5:17.4f} {p.max() / 1e5:12.3f} \"\n",
    "        f\"{np.mean(np.diff(crossings[cells])):12.5f} {np.sqrt(np.mean((p - exact[cells]) ** 2)) / joukowsky:15.2%}\"\n",
    "    )\n",
    "print(\n",
    "    f\"period 4L/a = {period:.5f} s;  valve flow after closure: {np.abs(result.node_inflow['valve'][times > closure_time]).max():.1e} m³/s\"\n",
    ")\n",
    "energy = result.stored_energy + result.dissipated_energy - result.boundary_work\n",
    "print(\n",
    "    f\"energy balance of the pipe (400 cells): drift {np.ptp(energy) / energy[0]:.1e} of the initial energy\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The pressure next to the valve on the three grids against the characteristic solution, and the\n",
    "pressure in the whole pipe over the first two periods: the fronts travel at $a$ and\n",
    "reverse sign at the reservoir. Dotted lines: the Joukowsky values $\\pm\\rho a v_0$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "window = times <= 2.0 * period\n",
    "fig = plots.figure(1, 2, size=(15, 5))\n",
    "plots.line(\n",
    "    times,\n",
    "    {f\"{cells} cells\": p / 1e5 for cells, p in surge.items()},\n",
    "    reference={\"characteristic solution\": exact[400] / 1e5},\n",
    "    hlines=[joukowsky / 1e5, -joukowsky / 1e5],\n",
    "    xlimits=(0.0, 3.5),\n",
    "    xlabel=\"time t [s]\",\n",
    "    ylabel=\"pressure surge p - p_r [bar]\",\n",
    "    title=\"Pressure next to the valve\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.heatmap(\n",
    "    result.pressure_coordinates[\"main\"],\n",
    "    times[window],\n",
    "    (result.pressure[\"main\"][window] - reservoir_pressure).T / 1e5,\n",
    "    colormap=\"diverging\",\n",
    "    centre=0.0,\n",
    "    limits=(-1.1 * joukowsky / 1e5, 1.1 * joukowsky / 1e5),\n",
    "    label=\"p - p_r [bar]\",\n",
    "    xlabel=\"position along the pipe x [m]\",\n",
    "    ylabel=\"time t [s]\",\n",
    "    aspect=\"auto\",\n",
    "    title=\"Pressure waves in the pipe\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Close the valve more slowly than $2L/a$ and the first relief wave from the reservoir\n",
    "arrives before the closure is complete: the peak falls below $\\rho a v_0$ (Michaud's\n",
    "estimate $\\Delta p\\approx 2\\rho L v_0/t_c$). Give the pipe a `darcy_friction` and\n",
    "the square wave decays, with the line-packing rise above the Joukowsky value. A\n",
    "`HydraulicPumpPort` instead of the reservoir, or a branch to a second valve, turns\n",
    "the case into the classical pump-trip and network studies."
   ]
  }
 ]
}
