{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Dam break on a column (shallow-water equations)\n",
    "\n",
    "A tank 1.60 m long and 0.61 m wide holds a 0.40 m long, 0.30 m deep body of water\n",
    "behind a gate; the rest of the floor is covered by a 0.01 m layer. A tall column\n",
    "with a 0.12 m square base stands 0.50 m downstream of the gate and 0.25 m from one\n",
    "side wall. At $t=0$ the gate is removed: a bore runs down the tank, strikes the\n",
    "column, wraps around it, is reflected by the far wall and strikes the column a\n",
    "second time from behind. The arrangement follows the dam-break experiment reported by\n",
    "Raad & Bidoae (J. Comput. Phys. 203, 668-699, 2005).\n",
    "\n",
    "The depth-averaged flow obeys the 2D shallow-water (Saint-Venant) equations over a\n",
    "flat, frictionless floor,\n",
    "\n",
    "$$\\partial_t h+\\nabla\\cdot(h\\mathbf u)=0,\\qquad\n",
    "  \\partial_t(h\\mathbf u)+\\nabla\\cdot\\Bigl(h\\mathbf u\\otimes\\mathbf u+\\tfrac12 g h^2\\mathbf I\\Bigr)=0,$$\n",
    "\n",
    "with depth $h$ and depth-averaged velocity $\\mathbf u$. The pressure is hydrostatic,\n",
    "so the force per unit length on a wall is $\\rho g h^2/2$ and the force on the column\n",
    "is the integral of $\\rho g h^2\\mathbf n/2$ over its four faces.\n",
    "\n",
    "**Method.** These are exactly the 2D gas-dynamics equations of a barotropic fluid\n",
    "with \"density\" $h$ and \"pressure\" $p=g h^2/2$ (the hydraulic analogy, $\\gamma=2$).\n",
    "OneSimulation's compressible cell-face finite-volume provider\n",
    "(`CompressibleFaceFiniteVolume` on an `UnstructuredCompressibleGeometry`) accepts the\n",
    "equation of state, the face flux and the reconstruction as injected components, so\n",
    "the shallow-water system is solved with:\n",
    "\n",
    "* a cell-centred finite-volume method on a quadrilateral grid with the column cut\n",
    "  out, conservative face fluxes on every face;\n",
    "* a Godunov-type HLL Riemann flux with Einfeldt wave-speed estimates\n",
    "  (Toro, *Shock-Capturing Methods for Free-Surface Shallow Flows*, Wiley 2001);\n",
    "* MUSCL reconstruction of $(h, u, v)$ with OneSimulation's least-squares cell\n",
    "  gradients and the Barth-Jespersen limiter, velocity desingularisation in nearly\n",
    "  dry cells (Kurganov & Petrova, Commun. Math. Sci. 5, 2007) and first-order fluxes\n",
    "  next to them;\n",
    "* slip walls whose flux uses the exact solution of the wall Riemann problem;\n",
    "* explicit third-order strong-stability-preserving Runge-Kutta time stepping\n",
    "  (SSP-RK3, Shu & Osher 1988) with an adaptive CFL step; no linear solver is needed.\n",
    "\n",
    "The energy row of the gas-dynamics state is carried along passively: the closure\n",
    "below makes the pressure depend on $h$ only, so it never feeds back.\n",
    "\n",
    "**Reference.** (i) Until the bore reaches the column ($t<0.265$ s) the flow is\n",
    "exactly one-dimensional and equals Stoker's exact wet-bed dam-break solution\n",
    "(J. J. Stoker, *Water Waves*, Interscience 1957, Ch. 10; the dry-bed limit is\n",
    "Ritter's solution); the 2D field is compared with it over the whole tank.\n",
    "(ii) At the instant of impact the straight bore is reflected by the flat front face;\n",
    "the exact reflected depth gives the closed-form peak force. (iii) Mass is conserved\n",
    "to round-off. (iv) A three-grid study gives observed orders and Richardson estimates\n",
    "for the force history. The first impact converges well; the second impact, carried\n",
    "by bores that cross the nearly dry wake, still shifts by about 0.02 s per refinement\n",
    "on these grids. Tabulated measurements of the cited experiment are not\n",
    "available, so the measured forces are not compared."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import time\n",
    "from collections import Counter\n",
    "from dataclasses import dataclass\n",
    "\n",
    "import numpy as np\n",
    "from onesim.numerics.time import DEFAULT_TIME_INTEGRATOR_REGISTRY\n",
    "from onesim.physics.hydrodynamics import (\n",
    "    CompressibleBoundaryPatch,\n",
    "    CompressibleFaceFiniteVolume,\n",
    "    CompressibleFlowDiscretization,\n",
    "    CompressibleNavierStokesSolver,\n",
    "    ImpermeableCompressibleWall,\n",
    "    UnstructuredCompressibleGeometry,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.optimize import brentq\n",
    "\n",
    "theme.set()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parameters"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "g, rho_w = 9.81, 1000.0\n",
    "width, length = 0.61, 1.60\n",
    "y_gate = 0.40\n",
    "column = (0.24, 0.90, 0.12)\n",
    "h_up, h_bed = 0.30, 0.01\n",
    "t_end = 2.0\n",
    "grids = (0.02, 0.01, 0.005)\n",
    "x0, y0, side = column"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Stoker's wet-bed dam-break solution: a rarefaction into the reservoir, a uniform\n",
    "middle state (h_m, u_m) and a bore of speed S into the thin layer."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "f_bore = lambda h: (h - h_bed) * np.sqrt(0.5 * g * (h + h_bed) / (h * h_bed))\n",
    "f_rare = lambda h: 2 * (np.sqrt(g * h) - np.sqrt(g * h_up))\n",
    "h_mid = brentq(lambda h: f_rare(h) + f_bore(h), h_bed, h_up)\n",
    "u_mid = -f_rare(h_mid)\n",
    "bore_speed = h_mid * u_mid / (h_mid - h_bed)\n",
    "t_arrival = (y0 - y_gate) / bore_speed\n",
    "h_reflected = brentq(\n",
    "    lambda h: (h - h_mid) * np.sqrt(0.5 * g * (h + h_mid) / (h * h_mid)) - u_mid,\n",
    "    h_mid,\n",
    "    1.0,\n",
    ")\n",
    "F_impact = rho_w * g * side * (h_reflected**2 - h_bed**2) / 2\n",
    "print(\n",
    "    f\"Stoker middle state h_m = {h_mid:.5f} m, u_m = {u_mid:.5f} m/s, bore speed {bore_speed:.5f} m/s\"\n",
    ")\n",
    "print(\n",
    "    f\"bore reaches the column at t = {t_arrival:.4f} s; reflected depth {h_reflected:.5f} m, \"\n",
    "    f\"impact force {F_impact:.3f} N\"\n",
    ")\n",
    "\n",
    "\n",
    "def stoker(y, t):\n",
    "    \"\"\"Exact depth of the 1D dam break at time t (gate at y_gate, flow towards +y).\"\"\"\n",
    "    c_up, c_mid = np.sqrt(g * h_up), np.sqrt(g * h_mid)\n",
    "    s = (y - y_gate) / t\n",
    "    return np.where(\n",
    "        s < -c_up,\n",
    "        h_up,\n",
    "        np.where(\n",
    "            s < u_mid - c_mid,\n",
    "            (2 * c_up - s) ** 2 / (9 * g),\n",
    "            np.where(s < bore_speed, h_mid, h_bed),\n",
    "        ),\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The tank is covered by a tensor grid of quadrilaterals whose lines include the gate,\n",
    "the four column faces and the walls; cells inside the column are removed, so the\n",
    "column faces are exact mesh boundaries. Two boundary groups are declared: `tank` (the\n",
    "four walls) and `column` (the four column faces). The grid and its named exterior\n",
    "facets are handed to `UnstructuredCompressibleGeometry`, which builds the face\n",
    "normals, areas, cell volumes and least-squares gradient operators."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "def axis_nodes(keys, h):\n",
    "    nodes = [keys[0]]\n",
    "    for a, b in zip(keys[:-1], keys[1:]):\n",
    "        n = int(np.ceil((b - a) / h - 1e-9))\n",
    "        nodes += list(np.linspace(a, b, n + 1)[1:])\n",
    "    return np.array(nodes)\n",
    "\n",
    "\n",
    "def build_grid(h):\n",
    "    xs = axis_nodes([0.0, x0, x0 + side, width], h)\n",
    "    ys = axis_nodes([0.0, y_gate, y0, y0 + side, length], h)\n",
    "    nx, ny = len(xs) - 1, len(ys) - 1\n",
    "    I, J = (a.ravel() for a in np.meshgrid(np.arange(nx), np.arange(ny), indexing=\"xy\"))\n",
    "    xc, yc = 0.5 * (xs[I] + xs[I + 1]), 0.5 * (ys[J] + ys[J + 1])\n",
    "    fluid = ~((xc > x0) & (xc < x0 + side) & (yc > y0) & (yc < y0 + side))\n",
    "    I, J = I[fluid], J[fluid]\n",
    "    vid = lambda i, j: j * (nx + 1) + i\n",
    "    cells = np.stack(\n",
    "        (vid(I, J), vid(I + 1, J), vid(I + 1, J + 1), vid(I, J + 1)), axis=1\n",
    "    )\n",
    "    X, Y = np.meshgrid(xs, ys, indexing=\"xy\")\n",
    "    vertices = np.column_stack((X.ravel(), Y.ravel()))\n",
    "    used = np.unique(cells)\n",
    "    renumber = np.full(len(vertices), -1)\n",
    "    renumber[used] = np.arange(len(used))\n",
    "    vertices, cells = vertices[used], renumber[cells]\n",
    "    edges = Counter(\n",
    "        tuple(sorted((int(c[k]), int(c[(k + 1) % 4])))) for c in cells for k in range(4)\n",
    "    )\n",
    "    groups = {}\n",
    "    for edge, count in edges.items():\n",
    "        if count == 1:\n",
    "            mx, my = vertices[list(edge)].mean(axis=0)\n",
    "            on_column = (x0 - 1e-9 <= mx <= x0 + side + 1e-9) and (\n",
    "                y0 - 1e-9 <= my <= y0 + side + 1e-9\n",
    "            )\n",
    "            groups[edge] = \"column\" if on_column else \"tank\"\n",
    "    geometry = UnstructuredCompressibleGeometry(\n",
    "        artifact_id=f\"dam-break-tank-{h}\",\n",
    "        vertices=vertices,\n",
    "        cells=cells,\n",
    "        boundary_groups=groups,\n",
    "        cell_quadrature_order=2,\n",
    "        face_quadrature_order=1,\n",
    "    )\n",
    "    return dict(\n",
    "        geometry=geometry,\n",
    "        cells=geometry(geometry.carrier),\n",
    "        xs=xs,\n",
    "        ys=ys,\n",
    "        I=I,\n",
    "        J=J,\n",
    "        h_min=min(np.diff(xs).min(), np.diff(ys).min()),\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "**Closure.** Depth plays the role of density and $p=g h^2/2$ (per unit water\n",
    "density) the role of pressure; the sound speed is the wave celerity $\\sqrt{g h}$.\n",
    "The specific internal energy is offset by a large constant so that the passive\n",
    "energy row stays admissible."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "E_OFFSET, H_DRY = 1.0e6, 1.0e-3\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class HydrostaticClosure:\n",
    "    gravity: float = g\n",
    "    offset: float = E_OFFSET\n",
    "\n",
    "    def pressure_from_density_internal_energy(self, h, e):\n",
    "        return 0.5 * self.gravity * h * h\n",
    "\n",
    "    def evaluate_density_internal_energy_fields(self, h, e):\n",
    "        return 0.5 * self.gravity * h * h, np.ones_like(h)\n",
    "\n",
    "    def temperature_from_density_internal_energy(self, h, e):\n",
    "        return 1.0\n",
    "\n",
    "    def internal_energy_from_density_pressure(self, h, p):\n",
    "        return self.offset + p / h\n",
    "\n",
    "    def evaluate_internal_energy_pressure_field(self, h, p):\n",
    "        return self.offset + p / h\n",
    "\n",
    "    def sound_speed(self, h, e):\n",
    "        return np.sqrt(self.gravity * h)\n",
    "\n",
    "    def evaluate_sound_speed_field(self, h, e):\n",
    "        return np.sqrt(self.gravity * h)\n",
    "\n",
    "    def pressure_from_density_temperature(self, h, T):\n",
    "        return 0.5 * self.gravity * h * h\n",
    "\n",
    "    def density_from_pressure_temperature(self, p, T):\n",
    "        return np.sqrt(2 * p / self.gravity)\n",
    "\n",
    "    def specific_enthalpy_from_density_pressure(self, h, p):\n",
    "        return self.offset + 2 * p / h\n",
    "\n",
    "    def specific_entropy(self, h, e):\n",
    "        return 0.0\n",
    "\n",
    "\n",
    "def velocity(h, hu):\n",
    "    \"\"\"Desingularised velocity hu/h, identical to hu/h for h >> H_DRY.\"\"\"\n",
    "    return np.sqrt(2.0) * h * hu / np.sqrt(h**4 + np.maximum(h**4, H_DRY**4))\n",
    "\n",
    "\n",
    "def energy_row(h, u, v):\n",
    "    return h * E_OFFSET + 0.5 * g * h * h + 0.5 * h * (u * u + v * v)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**HLL flux.** The normal velocity of each face state follows from its mass flux;\n",
    "the outer wave speeds use the Einfeldt (Roe-average) estimates."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "def hll_flux(left, right, flux_left, flux_right, wave):\n",
    "    hl, hr = left[0], right[0]\n",
    "    ul, ur = flux_left[0] / hl, flux_right[0] / hr\n",
    "    cl, cr = np.sqrt(g * hl), np.sqrt(g * hr)\n",
    "    u_roe = (np.sqrt(hl) * ul + np.sqrt(hr) * ur) / (np.sqrt(hl) + np.sqrt(hr))\n",
    "    c_roe = np.sqrt(0.5 * g * (hl + hr))\n",
    "    s_left = np.minimum(np.minimum(ul - cl, u_roe - c_roe), 0.0)\n",
    "    s_right = np.maximum(np.maximum(ur + cr, u_roe + c_roe), 0.0)\n",
    "    return (\n",
    "        s_right * flux_left - s_left * flux_right + s_left * s_right * (right - left)\n",
    "    ) / (s_right - s_left)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Walls.** A slip wall is a mirror state; the exact Riemann solution between a cell\n",
    "state with normal velocity $u_n$ and its mirror image has $u^*=0$ and the depth\n",
    "$h^*=(\\sqrt{gh}+u_n/2)^2/g$ for $u_n\\le0$ (rarefaction) or the root of\n",
    "$(h^*-h)\\sqrt{g(h^*+h)/(2h^*h)}=u_n$ for $u_n>0$ (reflected bore). The wall flux is\n",
    "the hydrostatic thrust $g h^{*2}/2\\,\\mathbf n$, and the same $h^*$ gives the force on\n",
    "the column."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "def wall_depth(h, un):\n",
    "    hs = np.maximum(np.sqrt(g * h) + 0.5 * np.minimum(un, 0.0), 0.0) ** 2 / g\n",
    "    bore = un > 0\n",
    "    x, hb, ub = h[bore] + un[bore] * np.sqrt(h[bore] / g), h[bore], un[bore]\n",
    "    for _ in range(30):\n",
    "        q = np.sqrt(0.5 * g * (x + hb) / (x * hb))\n",
    "        x = x - ((x - hb) * q - ub) / (q - (x - hb) * 0.25 * g / (q * x * x))\n",
    "    hs[bore] = x\n",
    "    return hs\n",
    "\n",
    "\n",
    "def wall_flux(interior, trace, normal, points, time, turbulence, default):\n",
    "    h = np.asarray(interior.density)\n",
    "    un = velocity(h, normal @ (np.asarray(interior.velocity) * h))\n",
    "    thrust = 0.5 * g * wall_depth(h, un) ** 2\n",
    "    flux = np.zeros_like(default)\n",
    "    flux[1], flux[2] = thrust * normal[0], thrust * normal[1]\n",
    "    return flux"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**MUSCL reconstruction.** Cell gradients of $(h,u,v)$ come from the geometry's\n",
    "least-squares operator; the Barth-Jespersen limiter keeps every face value within\n",
    "the range of the cell and its face neighbours. Cells touching a nearly dry cell\n",
    "($h<1$ mm) use first-order (piecewise-constant) values."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "def muscl(cells, pressure, *, balance):\n",
    "    geo, inside = balance.geometry, balance.internal\n",
    "    owner, neighbour = geo.owner[inside], geo.neighbour[inside]\n",
    "    h = cells[0]\n",
    "    prim = np.stack((h, velocity(h, cells[1]), velocity(h, cells[2])))\n",
    "    grads = np.stack(\n",
    "        [\n",
    "            np.stack(balance.solver.operators.gradient(q.reshape(geo.shape))).reshape(\n",
    "                2, -1\n",
    "            )\n",
    "            for q in prim\n",
    "        ]\n",
    "    )\n",
    "    lo, hi = prim.copy(), prim.copy()\n",
    "    for k in range(3):\n",
    "        np.minimum.at(lo[k], owner, prim[k, neighbour])\n",
    "        np.minimum.at(lo[k], neighbour, prim[k, owner])\n",
    "        np.maximum.at(hi[k], owner, prim[k, neighbour])\n",
    "        np.maximum.at(hi[k], neighbour, prim[k, owner])\n",
    "    limiter = np.ones_like(prim)\n",
    "    d_owner = geo.points[inside] - geo.coordinates[owner]\n",
    "    d_neighbour = geo.points[inside] - geo.coordinates[neighbour]\n",
    "    for idx, offset in ((owner, d_owner), (neighbour, d_neighbour)):\n",
    "        for k in range(3):\n",
    "            delta = np.einsum(\"dq,qd->q\", grads[k][:, idx], offset)\n",
    "            room = np.where(\n",
    "                delta > 0, hi[k, idx] - prim[k, idx], lo[k, idx] - prim[k, idx]\n",
    "            )\n",
    "            with np.errstate(divide=\"ignore\", invalid=\"ignore\"):\n",
    "                ratio = np.where(np.abs(delta) > 1e-300, room / delta, 1.0)\n",
    "            np.minimum.at(limiter[k], idx, np.clip(ratio, 0.0, 1.0))\n",
    "    limiter[:, lo[0] < H_DRY] = 0.0\n",
    "    grads = grads * limiter[:, None, :]\n",
    "\n",
    "    def face_state(idx, offset):\n",
    "        hh, uu, vv = prim[:, idx] + np.einsum(\"kdq,qd->kq\", grads[:, :, idx], offset)\n",
    "        hh = np.maximum(hh, 1e-300)\n",
    "        return (\n",
    "            np.stack((hh, hh * uu, hh * vv, energy_row(hh, uu, vv))),\n",
    "            0.5 * g * hh * hh,\n",
    "        )\n",
    "\n",
    "    left, p_left = face_state(owner, d_owner)\n",
    "    right, p_right = face_state(neighbour, d_neighbour)\n",
    "    return (left, right), (p_left, p_right)\n",
    "\n",
    "\n",
    "def cfl_step(cfl, h_min):\n",
    "    def step(state, *, time, species=None, balance):\n",
    "        h = state[0]\n",
    "        c = np.sqrt(g * h)\n",
    "        rate = (\n",
    "            np.abs(velocity(h, state[1])) + c + np.abs(velocity(h, state[2])) + c\n",
    "        ) / h_min\n",
    "        return cfl / np.max(rate)\n",
    "\n",
    "    return step\n",
    "\n",
    "\n",
    "def make_solver(grid, second_order=True, cfl=0.45):\n",
    "    wall = CompressibleBoundaryPatch(\n",
    "        ImpermeableCompressibleWall(), advective_flux=wall_flux\n",
    "    )\n",
    "    balance = CompressibleFaceFiniteVolume(\n",
    "        geometry_factory=grid[\"geometry\"],\n",
    "        boundaries={\"tank\": wall, \"column\": wall},\n",
    "        numerical_flux=hll_flux,\n",
    "        reconstruction=muscl if second_order else None,\n",
    "        stability=cfl_step(cfl, grid[\"h_min\"]),\n",
    "        cfl=0.5,\n",
    "    )\n",
    "    return CompressibleNavierStokesSolver(\n",
    "        mesh=grid[\"cells\"],\n",
    "        spatial=CompressibleFlowDiscretization(derivatives=None, balance=balance),\n",
    "        time_integrator=DEFAULT_TIME_INTEGRATOR_REGISTRY.resolve_id(\"ssprk3\"),\n",
    "        viscosity=0.0,\n",
    "        thermal_conductivity=0.0,\n",
    "        density=1.0,\n",
    "        pressure=1.0,\n",
    "        final_time=0.01,\n",
    "        time_step=1.0,\n",
    "        equation_of_state=HydrostaticClosure(),\n",
    "        spatial_carrier=grid[\"geometry\"].carrier,\n",
    "    )\n",
    "\n",
    "\n",
    "def initial_state(grid):\n",
    "    y = grid[\"cells\"].coordinates[:, 1]\n",
    "    h = np.where(y < y_gate, h_up, h_bed)\n",
    "    return np.stack((h, 0 * h, 0 * h, energy_row(h, 0 * h, 0 * h)))\n",
    "\n",
    "\n",
    "def column_force(grid, state):\n",
    "    \"\"\"y-force on the column from the wall depth h* on its four faces (N).\"\"\"\n",
    "    cg = grid[\"cells\"]\n",
    "    on_column = np.array([key == \"column\" for key in cg.boundary_ids])\n",
    "    owner, normal, area = (\n",
    "        cg.owner[on_column],\n",
    "        cg.normals[on_column],\n",
    "        cg.areas[on_column],\n",
    "    )\n",
    "    h = state[0][owner]\n",
    "    un = velocity(h, normal[:, 0] * state[1][owner] + normal[:, 1] * state[2][owner])\n",
    "    return rho_w * np.sum(0.5 * g * wall_depth(h, un) ** 2 * area * normal[:, 1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Solve\n",
    "\n",
    "The solution is advanced in output intervals (5 ms, refined to 1 ms around the two\n",
    "impacts); after each interval the column force is evaluated. The depth is stored at\n",
    "$t=0.20$ s for the comparison with Stoker's solution and at four display times on\n",
    "the finest grid."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "t_out = np.unique(\n",
    "    np.round(\n",
    "        np.r_[\n",
    "            np.arange(0.0, t_end + 1e-9, 0.005),\n",
    "            np.arange(0.255, 0.330, 0.001),\n",
    "            np.arange(1.250, 1.450, 0.001),\n",
    "            0.20,\n",
    "        ],\n",
    "        9,\n",
    "    )\n",
    ")\n",
    "t_maps = (0.22, 0.38, 0.76, 1.44)\n",
    "\n",
    "\n",
    "def run(h, second_order=True, until=t_end):\n",
    "    grid = build_grid(h)\n",
    "    solver = make_solver(grid, second_order)\n",
    "    state = initial_state(grid)\n",
    "    volume0 = np.sum(state[0] * grid[\"cells\"].volumes)\n",
    "    times, forces, maps, steps, now = [0.0], [column_force(grid, state)], {}, 0, 0.0\n",
    "    start = time.time()\n",
    "    for t in t_out[(t_out > 0) & (t_out <= until + 1e-12)]:\n",
    "        solver.final_time = t - now\n",
    "        result = solver.run(initial_state=state)\n",
    "        state, now, steps = result.conserved_state, t, steps + result.step_count\n",
    "        times.append(t)\n",
    "        forces.append(column_force(grid, state))\n",
    "        if any(abs(t - m) < 1e-9 for m in (0.20, *t_maps)):\n",
    "            maps[round(t, 3)] = state[0].copy()\n",
    "    return dict(\n",
    "        grid=grid,\n",
    "        times=np.array(times),\n",
    "        force=np.array(forces),\n",
    "        maps=maps,\n",
    "        steps=steps,\n",
    "        volume_error=np.sum(state[0] * grid[\"cells\"].volumes) / volume0 - 1.0,\n",
    "        seconds=time.time() - start,\n",
    "        cells=len(grid[\"cells\"].volumes),\n",
    "    )\n",
    "\n",
    "\n",
    "runs = []\n",
    "for h in grids:\n",
    "    out = run(h)\n",
    "    runs.append(out)\n",
    "    print(\n",
    "        f\"grid {h * 1e3:4.1f} mm: {out['cells']:6d} cells, {out['steps']:5d} SSP-RK3 steps, \"\n",
    "        f\"peak force {out['force'].max():6.2f} N, relative volume change {out['volume_error']:+.1e} \"\n",
    "        f\"({out['seconds']:.0f} s)\"\n",
    "    )\n",
    "first_order = run(0.01, second_order=False, until=0.6)\n",
    "print(\n",
    "    f\"first-order Godunov (no MUSCL) on the 10 mm grid up to 0.6 s: {first_order['steps']} steps \"\n",
    "    f\"({first_order['seconds']:.0f} s)\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "**Stoker's solution at $t=0.20$ s.** The $L^1$ error of the depth over the whole\n",
    "tank, $\\sum|h_i-h_\\mathrm{exact}(y_i)|A_i/A$, contains the rarefaction (smooth) and\n",
    "the bore (a discontinuity, first-order in $L^1$ at best), so an observed order\n",
    "between 1 and 2 is expected."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "def stoker_error(out):\n",
    "    cg = out[\"grid\"][\"cells\"]\n",
    "    exact = stoker(cg.coordinates[:, 1], 0.20)\n",
    "    return np.sum(np.abs(out[\"maps\"][0.2] - exact) * cg.volumes) / np.sum(cg.volumes)\n",
    "\n",
    "\n",
    "errors = [stoker_error(out) for out in runs]\n",
    "print(\"Depth at t = 0.20 s vs Stoker's exact dam-break solution (L1 error, m)\")\n",
    "for h, err in zip(grids, errors):\n",
    "    print(f\"  grid {h * 1e3:4.1f} mm: {err:.3e}\")\n",
    "print(\n",
    "    f\"  observed orders {np.log2(errors[0] / errors[1]):.2f} and {np.log2(errors[1] / errors[2]):.2f}\"\n",
    ")\n",
    "print(\n",
    "    f\"  first-order Godunov on the 10 mm grid: {stoker_error(first_order):.3e} \"\n",
    "    f\"({stoker_error(first_order) / errors[1]:.1f} x the MUSCL error)\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Impact force.** When the straight bore meets the flat front face, the depth there\n",
    "jumps to the exact reflected depth while the back face still sees the 1 cm layer,\n",
    "so the force is $\\rho g\\,b\\,(h_r^2-h_0^2)/2$ at that instant. Lateral relief from the\n",
    "column edges lowers it immediately afterwards, so a finite grid, on which the bore\n",
    "is spread over a few cells, approaches this value from below."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "def richardson(values, ratio=2.0):\n",
    "    \"\"\"Observed order and extrapolated value from three grids refined by `ratio`.\"\"\"\n",
    "    f1, f2, f3 = values\n",
    "    r = (f1 - f2) / (f2 - f3)\n",
    "    p = np.log(r) / np.log(ratio) if r > 1 else np.nan\n",
    "    return p, (f3 + (f3 - f2) / (ratio**p - 1.0) if r > 1 else np.nan)\n",
    "\n",
    "\n",
    "def window_impulse(out, t0, t1):\n",
    "    t, F = out[\"times\"], out[\"force\"]\n",
    "    keep = (t >= t0) & (t <= t1)\n",
    "    return np.trapezoid(F[keep], t[keep])\n",
    "\n",
    "\n",
    "print(\n",
    "    f\"Peak force at the first impact (closed form {F_impact:.3f} N at t = {t_arrival:.4f} s)\"\n",
    ")\n",
    "for h, out in zip(grids, runs):\n",
    "    i = np.argmax(out[\"force\"])\n",
    "    print(\n",
    "        f\"  grid {h * 1e3:4.1f} mm: {out['force'][i]:7.3f} N at t = {out['times'][i]:.3f} s, \"\n",
    "        f\"deviation {100 * (out['force'][i] / F_impact - 1):+.2f} %\"\n",
    "    )\n",
    "i = np.argmax(first_order[\"force\"])\n",
    "print(\n",
    "    f\"  first-order Godunov, 10 mm: {first_order['force'][i]:7.3f} N \"\n",
    "    f\"({100 * (first_order['force'][i] / F_impact - 1):+.2f} %)\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Grid study of the force history.** The impulse of the first impact is a smooth\n",
    "functional of the solution. The second impact is caused by bores that travel round\n",
    "the column over the nearly dry wake and back from the far wall; its extreme force and\n",
    "its onset time (first drop below -5 N) are listed as well."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "def second_impact(out):\n",
    "    t, F = out[\"times\"], out[\"force\"]\n",
    "    late = t > 1.2\n",
    "    return F[late].min(), t[late][np.argmax(F[late] < -5.0)]\n",
    "\n",
    "\n",
    "print(\"Grid study of the force history\")\n",
    "quantities = (\n",
    "    (\n",
    "        \"impulse of the first impact, 0.25-0.80 s (N s)\",\n",
    "        [window_impulse(out, 0.25, 0.80) for out in runs],\n",
    "    ),\n",
    "    (\"extreme force of the second impact (N)\", [second_impact(out)[0] for out in runs]),\n",
    "    (\"onset of the second impact (s)\", [second_impact(out)[1] for out in runs]),\n",
    ")\n",
    "for label, vals in quantities:\n",
    "    p, ext = richardson(vals)\n",
    "    trend = (\n",
    "        f\"order {p:4.2f}, Richardson {ext:9.4f}\"\n",
    "        if np.isfinite(p)\n",
    "        else \"not in the asymptotic range, no extrapolation\"\n",
    "    )\n",
    "    print(\n",
    "        f\"  {label:50s} \"\n",
    "        + \"  \".join(f\"{v:9.4f}\" for v in vals)\n",
    "        + f\"; {trend}, change between the last two grids {100 * abs(vals[2] / vals[1] - 1):.2f} %\"\n",
    "    )\n",
    "\n",
    "print(\"Mass conservation (relative change of the water volume at t = 2 s)\")\n",
    "for h, out in zip(grids, runs):\n",
    "    print(f\"  grid {h * 1e3:4.1f} mm: {out['volume_error']:+.2e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Top: water depth on the finest grid at four times (impact, wrap-around, reflection\n",
    "from the far wall, second impact). Bottom left: depth along the tank at $t=0.20$ s\n",
    "against Stoker's solution. Bottom right: force on the column on the three grids with\n",
    "the closed-form impact force."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "fine = runs[-1]\n",
    "grid = fine[\"grid\"]\n",
    "xc, yc = 0.5 * (grid[\"xs\"][:-1] + grid[\"xs\"][1:]), 0.5 * (\n",
    "    grid[\"ys\"][:-1] + grid[\"ys\"][1:]\n",
    ")\n",
    "y_line = np.linspace(0.0, y0, 600)\n",
    "depth_lines, force_lines = {}, {}\n",
    "for out, h in zip(runs, grids):\n",
    "    cells = out[\"grid\"][\"cells\"]\n",
    "    strip = np.abs(cells.coordinates[:, 0] - 0.5 * width) < 0.6 * h + 1e-9\n",
    "    along = np.argsort(cells.coordinates[strip, 1])\n",
    "    depth_lines[f\"MUSCL-HLL, {h * 1e3:.0f} mm\"] = (\n",
    "        cells.coordinates[strip, 1][along],\n",
    "        out[\"maps\"][0.2][strip][along],\n",
    "    )\n",
    "    force_lines[f\"MUSCL-HLL, {h * 1e3:.0f} mm\"] = (out[\"times\"], out[\"force\"])\n",
    "force_lines[\"first-order Godunov, 10 mm\"] = (first_order[\"times\"], first_order[\"force\"])\n",
    "fig = plots.figure(\n",
    "    layout=[\n",
    "        [f\"map {k}\" for k in range(len(t_maps))],\n",
    "        [\"stoker\"] * (len(t_maps) // 2) + [\"force\"] * (len(t_maps) - len(t_maps) // 2),\n",
    "    ],\n",
    "    size=(16, 10.5),\n",
    ")\n",
    "for k, t in enumerate(t_maps):\n",
    "    depth = np.full((len(xc), len(yc)), np.nan)\n",
    "    depth[grid[\"I\"], grid[\"J\"]] = fine[\"maps\"][t]\n",
    "    plots.heatmap(\n",
    "        xc,\n",
    "        yc,\n",
    "        depth,\n",
    "        limits=(0.0, 0.30),\n",
    "        contours=8,\n",
    "        label=\"water depth h [m]\",\n",
    "        xlabel=\"x [m]\",\n",
    "        ylabel=\"y [m] (gate at 0.40 m)\",\n",
    "        title=f\"t = {t:.2f} s\",\n",
    "        ax=fig[f\"map {k}\"],\n",
    "    )\n",
    "plots.line(\n",
    "    y=depth_lines,\n",
    "    reference={\"Stoker, exact\": (y_line, stoker(y_line, 0.20))},\n",
    "    markers=True,\n",
    "    xlimits=(0, y0),\n",
    "    xlabel=\"y [m]\",\n",
    "    ylabel=\"h [m]\",\n",
    "    title=\"Depth along the tank at t = 0.20 s (before impact)\",\n",
    "    ax=fig[\"stoker\"],\n",
    ")\n",
    "plots.line(\n",
    "    y=force_lines,\n",
    "    styles={\"first-order Godunov, 10 mm\": \"dashed\"},\n",
    "    points={f\"exact impact force {F_impact:.1f} N\": ([t_arrival], [F_impact])},\n",
    "    hlines=0.0,\n",
    "    xlimits=(0, t_end),\n",
    "    xlabel=\"t [s]\",\n",
    "    ylabel=\"F_y on the column [N]\",\n",
    "    title=\"Pressure force on the column\",\n",
    "    ax=fig[\"force\"],\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add Manning bed friction as a momentum source to see how much of the peak force the\n",
    "frictionless model over-predicts, move the column closer to the side wall, or replace\n",
    "the column by a raised bed block that the water can overtop. The same injected\n",
    "closure runs unchanged on triangular or mixed meshes for curved obstacles."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
