{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "480bb0a8",
   "metadata": {},
   "source": [
    "# Tank draining through an orifice\n",
    "\n",
    "An open tank of cross-section $A$ is filled to the level $h_0$ and drains through\n",
    "a small orifice of area $a$ in its bottom. With the discharge coefficient $C_d$\n",
    "the outflow follows Torricelli's law, and the volume balance of the tank reads\n",
    "\n",
    "$$A\\,\\frac{dh}{dt}=-C_d\\,a\\,\\sqrt{2\\,g\\,h}.$$\n",
    "\n",
    "OneSimulation models the tank as a compliant pressure node of a lumped hydraulic\n",
    "network: the gauge pressure at the bottom is $p=\\rho g h$, so the node compliance\n",
    "is $C=A/(\\rho g)$ and the orifice is a branch to the atmosphere with the\n",
    "nonlinear flow law $q=C_d\\,a\\sqrt{2\\,(p-p_\\mathrm{atm})/\\rho}$. The network is\n",
    "integrated with the classical fourth-order Runge-Kutta method.\n",
    "\n",
    "**Reference.** The square root of the level falls linearly in time,\n",
    "\n",
    "$$\\sqrt{h(t)}=\\sqrt{h_0}-\\frac{C_d\\,a}{2A}\\sqrt{2g}\\;t,\\qquad\n",
    "  t_e=\\frac{A}{C_d\\,a}\\sqrt{\\frac{2h_0}{g}},$$\n",
    "\n",
    "where $t_e$ is the time at which the tank is empty. We compare $h(t)$ at every\n",
    "stored time, recover $t_e$ from the simulated curve, and check that the drained\n",
    "volume equals the integrated orifice flow."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4544f211",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from onesim.physics.systems import (\n",
    "    HydraulicBranch,\n",
    "    HydraulicNode,\n",
    "    DEFAULT_SYSTEMS_PROVIDER_REGISTRY,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f1488a27",
   "metadata": {},
   "source": [
    "## Parameters and model\n",
    "\n",
    "The parameters can be changed; the reference stays valid for a prismatic tank\n",
    "(constant $A$), a constant discharge coefficient and a liquid that is much\n",
    "deeper than the orifice. The values describe a 0.5 m² water tank, 1.2 m deep,\n",
    "emptying through a sharp-edged 20 mm hole."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f5d44625",
   "metadata": {},
   "outputs": [],
   "source": [
    "gravity = 9.81\n",
    "density = 1000.0\n",
    "tank_area = 0.5\n",
    "orifice_diameter = 0.02\n",
    "orifice_area = np.pi * (orifice_diameter / 2.0) ** 2\n",
    "discharge_coefficient = 0.62\n",
    "initial_level = 1.2\n",
    "\n",
    "drain_rate = (\n",
    "    discharge_coefficient * orifice_area * np.sqrt(2.0 * gravity) / (2.0 * tank_area)\n",
    ")\n",
    "empty_time = np.sqrt(initial_level) / drain_rate\n",
    "end_time = 0.9 * empty_time\n",
    "time_step = 1.0\n",
    "print(\n",
    "    f\"orifice area = {orifice_area * 1e4:.3f} cm^2,  initial outflow = \"\n",
    "    f\"{discharge_coefficient * orifice_area * np.sqrt(2 * gravity * initial_level) * 1e3:.3f} L/s\"\n",
    ")\n",
    "print(f\"emptying time t_e = {empty_time:.1f} s ({empty_time / 60:.1f} min)\")\n",
    "\n",
    "compliance = tank_area / (density * gravity)\n",
    "\n",
    "\n",
    "def orifice_flow(upstream_pressure, downstream_pressure, time, parameters):\n",
    "    \"\"\"Torricelli outflow q = C_d a sqrt(2 (p_up - p_down) / rho); no reverse flow.\"\"\"\n",
    "    head = max(upstream_pressure - downstream_pressure, 0.0)\n",
    "    return (\n",
    "        parameters[\"discharge_coefficient\"]\n",
    "        * parameters[\"area\"]\n",
    "        * np.sqrt(2.0 * head / parameters[\"density\"])\n",
    "    )\n",
    "\n",
    "\n",
    "network = DEFAULT_SYSTEMS_PROVIDER_REGISTRY.create(\n",
    "    \"systems.hydraulic_systems\",\n",
    "    nodes=(\n",
    "        HydraulicNode(\n",
    "            \"tank\",\n",
    "            compliance=compliance,\n",
    "            initial_pressure=density * gravity * initial_level,\n",
    "        ),\n",
    "        HydraulicNode(\"atmosphere\", imposed_pressure=0.0),\n",
    "    ),\n",
    "    branches=(\n",
    "        HydraulicBranch(\n",
    "            \"orifice\",\n",
    "            from_node=\"tank\",\n",
    "            to_node=\"atmosphere\",\n",
    "            parameters={\n",
    "                \"discharge_coefficient\": discharge_coefficient,\n",
    "                \"area\": orifice_area,\n",
    "                \"density\": density,\n",
    "            },\n",
    "            flow_law=orifice_flow,\n",
    "        ),\n",
    "    ),\n",
    "    final_time=end_time,\n",
    "    time_step=time_step,\n",
    "    time_integration=\"classical_rk4\",\n",
    ")\n",
    "run = network.execute()\n",
    "times = np.asarray(run.times)\n",
    "levels = np.asarray(run.pressures[\"tank\"]) / (density * gravity)\n",
    "outflows = np.asarray(run.flows[\"orifice\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4465cd7b",
   "metadata": {},
   "source": [
    "## Comparison with the closed-form solution\n",
    "\n",
    "We evaluate the square-root law at every stored time, extrapolate the emptying\n",
    "time from the simulated $\\sqrt{h}$ trace, and check the volume balance. A passing\n",
    "check shows that this numerical example agrees with Torricelli's law; it is not\n",
    "a measurement of a real tank."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1d439ca9",
   "metadata": {},
   "outputs": [],
   "source": [
    "reference_levels = (np.sqrt(initial_level) - drain_rate * times) ** 2\n",
    "max_level_error = float(np.max(np.abs(levels - reference_levels)))\n",
    "print(\n",
    "    f\"Maximum level error: {max_level_error:.3e} m  (h0 = {initial_level} m, final level {levels[-1] * 1e2:.2f} cm)\"\n",
    ")\n",
    "\n",
    "slope, intercept = np.polyfit(times, np.sqrt(levels), 1)\n",
    "fitted_empty_time = -intercept / slope\n",
    "print(\n",
    "    f\"Emptying time: extrapolated {fitted_empty_time:.2f} s, exact {empty_time:.2f} s\"\n",
    ")\n",
    "drained_volume = tank_area * (initial_level - levels[-1])\n",
    "integrated_outflow = float(np.trapezoid(outflows, times))\n",
    "print(\n",
    "    f\"Drained volume: {drained_volume * 1e3:.2f} L, integrated orifice flow: {integrated_outflow * 1e3:.2f} L\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b3d2dfc",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7bf9bd0a",
   "metadata": {},
   "outputs": [],
   "source": [
    "dense_t = np.linspace(0.0, empty_time, 600)\n",
    "dense_h = (np.sqrt(initial_level) - drain_rate * dense_t) ** 2\n",
    "stride = max(1, len(times) // 40)\n",
    "fig = plots.figure(2, 1, size=(8, 7))\n",
    "plots.line(\n",
    "    points={\"OneSimulation RK4\": (times[::stride] / 60, levels[::stride])},\n",
    "    reference={\"Torricelli closed form\": (dense_t / 60, dense_h)},\n",
    "    vlines={\"emptying time\": empty_time / 60},\n",
    "    ylabel=\"liquid level [m]\",\n",
    "    title=\"Tank draining through an orifice\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"OneSimulation RK4\": (times[::stride] / 60, np.sqrt(levels[::stride]))},\n",
    "    reference={\"closed form (straight line)\": (dense_t / 60, np.sqrt(dense_h))},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"sqrt(h) [m^1/2]\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2a04747",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Double the orifice diameter and the tank empties four times faster; double the\n",
    "tank area and it takes twice as long. Add a constant `external_flow` to the tank\n",
    "node and the level settles where inflow and Torricelli outflow balance,\n",
    "$h_\\infty=\\left(Q_\\mathrm{in}/(C_d a)\\right)^2/(2g)$. A second tank node fed by\n",
    "the orifice branch turns the example into the classical two-tank system, whose\n",
    "levels no longer have an elementary closed form but can be checked against a\n",
    "fine-step reference integration."
   ]
  }
 ],
 "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
}
