{
 "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": [
    "# Shallow-water equations: dam breaks and a lake at rest\n",
    "\n",
    "Where water is shallow compared with the length of its waves, the pressure is hydrostatic and\n",
    "the velocity nearly uniform over the depth. Mass and momentum balances over the water column\n",
    "give the shallow-water (Saint-Venant) equations for the depth $h$ and the discharge $q=hu$ over a\n",
    "bed of elevation $b(x)$:\n",
    "\n",
    "$$\\frac{\\partial h}{\\partial t}+\\frac{\\partial q}{\\partial x}=0,\\qquad\n",
    "  \\frac{\\partial q}{\\partial t}+\\frac{\\partial}{\\partial x}\\Big(\\frac{q^2}{h}+\\frac{g h^2}{2}\\Big)=-g\\,h\\,\\frac{\\partial b}{\\partial x}.$$\n",
    "\n",
    "They are used for rivers, floods, tides and tsunamis. Two classic problems test a solver:\n",
    "\n",
    "* **Dam break.** A channel of length 10 m holds water 1 m deep behind a gate at $x_0=5$ m and\n",
    "  water 0.1 m deep (or none) in front of it. When the gate is removed, a rarefaction runs back\n",
    "  into the reservoir and a bore (or, on a dry bed, a thin front) runs downstream.\n",
    "* **Lake at rest.** Still water over an uneven bed, with an island that rises above the\n",
    "  surface, must stay exactly still. A scheme that does not balance the pressure gradient and the\n",
    "  bed slope discretely produces spurious currents.\n",
    "\n",
    "| end | condition |\n",
    "|---|---|\n",
    "| $x=0$ and $x=10$ m | reflecting wall, $q=0$ (the waves do not reach them) |\n",
    "\n",
    "**Reference.** J. J. Stoker, *Water Waves*, Interscience 1957, ch. 10 (dam break on a wet bed:\n",
    "rarefaction, constant state $h_m$, bore); A. Ritter, *Z. Vereines Deutscher Ingenieure* 36, 947\n",
    "(1892) (dry bed: $h=(2c_0-\\xi)^2/(9g)$ with $\\xi=(x-x_0)/t$, $c_0=\\sqrt{g h_0}$); E. Audusse,\n",
    "F. Bouchut, M.-O. Bristeau, R. Klein, B. Perthame, *SIAM J. Sci. Comput.* 25, 2050-2065 (2004)\n",
    "for the hydrostatic reconstruction that keeps the lake at rest."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d1 import Line\n",
    "from onesim.meshing import StructuredLineMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fvm import (\n",
    "    MUSCL,\n",
    "    ConvexInvariantDomain,\n",
    "    FiniteVolume,\n",
    "    HydrostaticReconstruction,\n",
    "    MinmodLimiter,\n",
    "    Rusanov,\n",
    ")\n",
    "from onesim.numerics.time import TimeMethod, TimeStepLimits\n",
    "from onesim.physics.hydrodynamics import TopographicShallowWater\n",
    "from onesim.simulation import Problem, ReflectingWall, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.optimize import brentq\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exact dam-break solution\n",
    "\n",
    "On a wet bed of depth $h_1$ the middle depth $h_m$ joins the rarefaction from the reservoir to the\n",
    "bore: $2(c_0-c_m)=(h_m-h_1)\\sqrt{g(h_m+h_1)/(2h_mh_1)}$. On a dry bed $h_m=0$ and the solution\n",
    "is Ritter's."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "g, gate, deep, end = 9.81, 5.0, 1.0, 0.6\n",
    "\n",
    "\n",
    "def dam_break(x, t, shallow):\n",
    "    \"\"\"Exact depth of the dam break at time t (Stoker; Ritter for a dry bed).\"\"\"\n",
    "    c0 = np.sqrt(g * deep)\n",
    "    middle = (\n",
    "        brentq(\n",
    "            lambda h: 2 * (c0 - np.sqrt(g * h))\n",
    "            - (h - shallow) * np.sqrt(g * (h + shallow) / (2 * h * shallow)),\n",
    "            shallow,\n",
    "            deep,\n",
    "        )\n",
    "        if shallow > 0\n",
    "        else 0.0\n",
    "    )\n",
    "    speed = 2 * (c0 - np.sqrt(g * middle))\n",
    "    front = middle * speed / (middle - shallow) if shallow > 0 else speed\n",
    "    xi = (x - gate) / t\n",
    "    return np.select(\n",
    "        [xi < -c0, xi < speed - np.sqrt(g * middle), xi < front],\n",
    "        [deep, (2 * c0 - xi) ** 2 / (9 * g), middle],\n",
    "        shallow,\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "One problem for each downstream depth, solved with two finite-volume schemes on four grids.\n",
    "Both use the Rusanov flux, the hydrostatic reconstruction for the bed and a two-stage\n",
    "strong-stability-preserving Runge-Kutta method with a CFL-limited time step; the second scheme\n",
    "adds MUSCL reconstruction with the minmod limiter and a positivity limiter for the dry front."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "channel = Line(start=(0, 0, 0), end=(10, 0, 0))\n",
    "model = TopographicShallowWater(domain=channel.line, bed_elevation=0.0)\n",
    "released = {\n",
    "    0.1: lambda x: np.where(x < gate, deep, 0.1),\n",
    "    0.0: lambda x: np.where(x < gate, deep, 0.0),\n",
    "}\n",
    "problems = {\n",
    "    shallow: Problem(\n",
    "        name=\"Dam break\",\n",
    "        geometry=channel,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            ReflectingWall(physics=model, boundary=channel.boundaries.all),\n",
    "        ),\n",
    "        initial_conditions=(\n",
    "            InitialValue(model.depth, initial),\n",
    "            InitialValue(model.discharge, 0.0),\n",
    "        ),\n",
    "    )\n",
    "    for shallow, initial in released.items()\n",
    "}\n",
    "schemes = {\n",
    "    \"first order\": FiniteVolume(\n",
    "        convection=Rusanov(),\n",
    "        provider=HydrostaticReconstruction(),\n",
    "        positivity=ConvexInvariantDomain(),\n",
    "        cell_quadrature_order=4,\n",
    "    ),\n",
    "    \"MUSCL, minmod\": FiniteVolume(\n",
    "        convection=Rusanov(),\n",
    "        provider=HydrostaticReconstruction(),\n",
    "        reconstruction=MUSCL(),\n",
    "        limiter=MinmodLimiter(),\n",
    "        positivity=ConvexInvariantDomain(),\n",
    "        cell_quadrature_order=4,\n",
    "    ),\n",
    "}\n",
    "grids = (100, 200, 400)\n",
    "depths = {\n",
    "    (shallow, scheme, cells): Simulation(\n",
    "        problem=problems[shallow],\n",
    "        mesh=StructuredLineMesher(cells=cells).generate(channel),\n",
    "        numerics=Numerics(\n",
    "            spatial=spatial,\n",
    "            time_integrator=TimeMethod(\"ssprk2\"),\n",
    "            step_limits=TimeStepLimits(stability_safety_factor=0.8),\n",
    "        ),\n",
    "    )\n",
    "    .run(start_time=0.0, end_time=end, time_step=0.05)\n",
    "    .field(model.depth)\n",
    "    for shallow in problems\n",
    "    for scheme, spatial in schemes.items()\n",
    "    for cells in grids\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The error is the mean absolute depth error over the channel at $t=0.6$ s; the water volume must\n",
    "stay $5.5$ m³ per metre width (wet bed) and $5.0$ m³ (dry bed)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(0.005, 9.995, 2000)\n",
    "points = np.column_stack((x, 0 * x, 0 * x))\n",
    "errors = {\n",
    "    key: np.mean(np.abs(np.ravel(depth.evaluate(points)) - dam_break(x, end, key[0])))\n",
    "    for key, depth in depths.items()\n",
    "}\n",
    "for shallow, label in (\n",
    "    (0.1, \"wet bed, h1 = 0.1 m (Stoker)\"),\n",
    "    (0.0, \"dry bed (Ritter)\"),\n",
    "):\n",
    "    print(label)\n",
    "    print(\n",
    "        \"  cells    first order    MUSCL      observed order (MUSCL)   volume change (MUSCL)\"\n",
    "    )\n",
    "    for index, cells in enumerate(grids):\n",
    "        second = errors[(shallow, \"MUSCL, minmod\", cells)]\n",
    "        order = (\n",
    "            np.log2(errors[(shallow, \"MUSCL, minmod\", grids[index - 1])] / second)\n",
    "            if index\n",
    "            else np.nan\n",
    "        )\n",
    "        volume = depths[(shallow, \"MUSCL, minmod\", cells)].integrate().value - 5 * (\n",
    "            deep + shallow\n",
    "        )\n",
    "        print(\n",
    "            f\"  {cells:5d} {errors[(shallow, 'first order', cells)]:13.2e} {second:10.2e} {order:16.2f} {volume:22.1e} m³\"\n",
    "        )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Lake at rest around an island\n",
    "\n",
    "A Gaussian hill 0.8 m high under water whose surface lies at 0.6 m: the hilltop is dry. The run\n",
    "lasts two seconds; the exact solution is the initial state, so depth and discharge must not\n",
    "change."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "hill = lambda x: 0.8 * np.exp(-(((x - 5.0) / 1.2) ** 2))\n",
    "lake = TopographicShallowWater(domain=channel.line, bed_elevation=hill)\n",
    "still = Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Lake at rest\",\n",
    "        geometry=channel,\n",
    "        physics=(lake,),\n",
    "        boundary_conditions=(\n",
    "            ReflectingWall(physics=lake, boundary=channel.boundaries.all),\n",
    "        ),\n",
    "        initial_conditions=(\n",
    "            InitialValue(lake.depth, lambda x: np.maximum(0.6 - hill(x), 0.0)),\n",
    "            InitialValue(lake.discharge, 0.0),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=StructuredLineMesher(cells=200).generate(channel),\n",
    "    numerics=Numerics(\n",
    "        spatial=schemes[\"MUSCL, minmod\"],\n",
    "        time_integrator=TimeMethod(\"ssprk2\"),\n",
    "        step_limits=TimeStepLimits(stability_safety_factor=0.8),\n",
    "    ),\n",
    ").run(start_time=0.0, end_time=2.0, time_step=0.1)\n",
    "lake_depth = still.field(lake.depth)\n",
    "level = np.ravel(still.field(lake.free_surface).evaluate(points))\n",
    "wet = np.ravel(lake_depth.evaluate(points)) > 0\n",
    "print(\n",
    "    f\"\\nlake at rest after 2 s: largest change of the depth {np.abs(lake_depth.values - lake_depth.at(0.0).values).max():.1e} m, \"\n",
    "    f\"largest discharge {np.abs(still.field(lake.discharge).values).max():.1e} m²/s, \"\n",
    "    f\"dry cells {np.count_nonzero(lake_depth.values == 0)} (island)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Depth profiles of both dam breaks at $t=0.6$ s on the 200-cell grid against the exact solutions,\n",
    "the grid study, and the lake at rest."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(2, 2, size=(15, 10))\n",
    "for panel, shallow, title in (\n",
    "    (fig[0], 0.1, \"Wet bed: rarefaction and bore\"),\n",
    "    (fig[1], 0.0, \"Dry bed: rarefaction and front\"),\n",
    "):\n",
    "    plots.line(\n",
    "        x,\n",
    "        {\n",
    "            scheme: np.ravel(depths[(shallow, scheme, 200)].evaluate(points))\n",
    "            for scheme in schemes\n",
    "        },\n",
    "        reference={\n",
    "            \"exact (Stoker)\" if shallow else \"exact (Ritter)\": dam_break(\n",
    "                x, end, shallow\n",
    "            )\n",
    "        },\n",
    "        xlabel=\"x [m]\",\n",
    "        ylabel=\"depth h [m]\",\n",
    "        ylimits=(-0.02, 1.05),\n",
    "        title=f\"{title}, t = {end} s, 200 cells\",\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.convergence(\n",
    "    [10 / cells for cells in grids],\n",
    "    {\n",
    "        f\"{scheme}, {'wet' if shallow else 'dry'} bed\": [\n",
    "            errors[(shallow, scheme, cells)] for cells in grids\n",
    "        ]\n",
    "        for shallow in problems\n",
    "        for scheme in schemes\n",
    "    },\n",
    "    order=1,\n",
    "    xlabel=\"cell width [m]\",\n",
    "    ylabel=\"mean depth error [m]\",\n",
    "    title=\"Grid study\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    x,\n",
    "    {\"water surface after 2 s\": np.where(wet, level, np.nan), \"bed\": hill(x)},\n",
    "    hlines={\"initial surface\": 0.6},\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"elevation [m]\",\n",
    "    ylimits=(0.0, 1.0),\n",
    "    title=\"Lake at rest around an island\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Give the bed a slope with `bed_elevation` and release the dam onto it, or add a rain source\n",
    "with `water_source`. The same model on a periodic channel carries a small wave, whose speed\n",
    "$\\sqrt{gh}$ the example on shallow-water wave speed checks."
   ]
  }
 ]
}
