{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "823fd824",
   "metadata": {},
   "source": [
    "# Shallow-water waves: how fast a small disturbance travels\n",
    "\n",
    "A shallow lake of still-water depth $h$ is disturbed by a small, smooth ridge\n",
    "on its surface. The ridge immediately splits into two pulses that travel\n",
    "outward in opposite directions. For a small disturbance the shallow-water\n",
    "(Saint-Venant) equations predict that each pulse moves at the celerity\n",
    "\n",
    "$$c = \\sqrt{g\\,h},$$\n",
    "\n",
    "independent of its shape or amplitude. We solve the full nonlinear\n",
    "shallow-water system and check the measured pulse speed against this formula.\n",
    "\n",
    "OneSimulation integrates the conservative 2-D shallow-water equations\n",
    "\n",
    "$$\\partial_t h + \\nabla\\cdot(h\\,\\mathbf u)=0,\\qquad\n",
    "  \\partial_t(h\\,\\mathbf u) + \\nabla\\cdot(h\\,\\mathbf u\\otimes\\mathbf u)\n",
    "  + \\nabla\\!\\big(\\tfrac12 g h^2\\big) = 0,$$\n",
    "\n",
    "with a first-order Rusanov finite-volume scheme on a periodic unit-square mesh.\n",
    "The initial ridge depends only on $x$, so the flow stays one-dimensional and\n",
    "produces one left-going and one right-going pulse."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aee26598",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from onesim.meshing import TensorCollocationMesh\n",
    "from onesim.numerics.time import ForwardEulerTimeIntegrator\n",
    "from onesim.physics.hydrodynamics import (\n",
    "    PeriodicShallowWaterRusanov,\n",
    "    ShallowWater2DSolver,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c90c366d",
   "metadata": {},
   "source": [
    "## Parameters\n",
    "\n",
    "The unit square carries a still-water depth $h$. A narrow Gaussian ridge of\n",
    "tiny amplitude (one part in a thousand of the depth) sits at the centre. The\n",
    "final time is chosen so the two pulses travel well into the domain without\n",
    "reaching the periodic boundary, so no wrap-around contaminates the measurement."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ccefaabe",
   "metadata": {},
   "outputs": [],
   "source": [
    "g = 9.81\n",
    "h = 1.0\n",
    "amplitude = 1.0e-3\n",
    "sigma = 0.03\n",
    "x0 = 0.5\n",
    "n = 200\n",
    "final_time = 0.10\n",
    "\n",
    "c_formula = np.sqrt(g * h)\n",
    "print(\n",
    "    f\"predicted celerity c = sqrt(g*h) = {c_formula:.4f} m/s,  c*t = {c_formula*final_time:.3f}\"\n",
    ")\n",
    "\n",
    "\n",
    "def initial_state(x, y):\n",
    "    depth = h + amplitude * np.exp(-((x - x0) ** 2) / (2.0 * sigma**2))\n",
    "    return depth, np.zeros_like(x), np.zeros_like(y)\n",
    "\n",
    "\n",
    "axis = (np.arange(n) + 0.5) / n\n",
    "mesh = TensorCollocationMesh(\n",
    "    axes=(axis, axis), coordinate_system=\"cartesian\", periodic=(True, True)\n",
    ")\n",
    "result = ShallowWater2DSolver(\n",
    "    mesh=mesh,\n",
    "    spatial=PeriodicShallowWaterRusanov(),\n",
    "    time_integrator=ForwardEulerTimeIntegrator(),\n",
    "    gravity=g,\n",
    "    final_time=final_time,\n",
    "    cfl=0.4,\n",
    ").run(initial_state)\n",
    "print(f\"Integrated {result.step_count} explicit steps to t = {result.time:.4f} s\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cd1b1f36",
   "metadata": {},
   "source": [
    "## Measure the pulse speed\n",
    "\n",
    "The flow is uniform in $y$, so we average along $y$ and work with the surface\n",
    "deviation $\\delta h(x)=h(x)-h$. Each outgoing pulse keeps its shape, so the\n",
    "centroid of $|\\delta h|$ on each half of the domain marks the pulse position.\n",
    "Dividing the travelled distance by the elapsed time gives the measured speed,\n",
    "which we compare with $c=\\sqrt{g h}$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4bcdcf7d",
   "metadata": {},
   "outputs": [],
   "source": [
    "delta_h = result.depth.mean(axis=1) - h\n",
    "weight = np.abs(delta_h)\n",
    "\n",
    "right = axis > x0\n",
    "left = axis < x0\n",
    "centroid_right = np.sum(axis[right] * weight[right]) / np.sum(weight[right])\n",
    "centroid_left = np.sum(axis[left] * weight[left]) / np.sum(weight[left])\n",
    "\n",
    "speed_right = (centroid_right - x0) / result.time\n",
    "speed_left = (x0 - centroid_left) / result.time\n",
    "speed_measured = 0.5 * (speed_right + speed_left)\n",
    "rel_error = abs(speed_measured - c_formula) / c_formula\n",
    "\n",
    "print(f\"right-going pulse speed = {speed_right:.4f} m/s\")\n",
    "print(f\"left-going  pulse speed = {speed_left:.4f} m/s\")\n",
    "print(f\"measured celerity       = {speed_measured:.4f} m/s\")\n",
    "print(f\"relative error vs sqrt(g*h) = {100*rel_error:.2f} %\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a818bf57",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "683e5c9d",
   "metadata": {},
   "outputs": [],
   "source": [
    "predicted = [x0 - c_formula * result.time, x0 + c_formula * result.time]\n",
    "plots.line(\n",
    "    axis,\n",
    "    {\"computed surface deviation\": delta_h * 1000.0},\n",
    "    points={\n",
    "        \"predicted x0 ± sqrt(g h) t\": (\n",
    "            predicted,\n",
    "            np.interp(predicted, axis, delta_h * 1000.0),\n",
    "        )\n",
    "    },\n",
    "    vlines={\n",
    "        \"measured left pulse\": centroid_left,\n",
    "        \"measured right pulse\": centroid_right,\n",
    "    },\n",
    "    xlabel=\"position x [m]\",\n",
    "    ylabel=\"surface deviation [mm]\",\n",
    "    title=f\"Shallow-water pulse: measured c = {speed_measured:.3f} m/s, sqrt(g h) = {c_formula:.3f} m/s\",\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41c7a655",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lengthen `final_time` (keeping the pulses inside the domain) or refine the mesh\n",
    "with a larger `n` and watch the measured speed settle ever closer to\n",
    "$\\sqrt{g h}$. Change the still-water depth `h` and confirm the celerity scales\n",
    "as its square root. Raise `amplitude` towards the depth and the leading edge\n",
    "begins to steepen into a bore, where the small-disturbance formula no longer\n",
    "applies."
   ]
  }
 ],
 "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
}
