{
 "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": [
    "# Wicking in a paper strip\n",
    "\n",
    "A strip of filter paper, 20 mm wide and 40 mm high, hangs with its lower edge in water. The\n",
    "pores of the dry paper suck the water up: fast at first, the wetted height growing with the\n",
    "square root of time, then ever slower as the weight of the lifted water balances the capillary\n",
    "suction. The water flow in the paper is unsaturated porous-media flow, the **Richards equation**\n",
    "for the pressure head $h$,\n",
    "\n",
    "$$\\frac{\\partial\\theta(h)}{\\partial t}=\\nabla\\cdot\\big(K(h)\\,(\\nabla h+\\mathbf e_y)\\big),$$\n",
    "\n",
    "with the van Genuchten water retention $\\theta(h)$ and the Mualem conductivity $K(h)$ of the\n",
    "paper: porosity 0.7, $\\alpha=12$ 1/m, $n=2.5$, saturated conductivity $10^{-6}$ m/s.\n",
    "\n",
    "| edge | condition |\n",
    "|---|---|\n",
    "| `y_min`, in the water | $h_0=0$ (saturated) |\n",
    "| `x_min`, `x_max`, `y_max` | no flow |\n",
    "| initial state | dry paper, $h_i=-1$ m |\n",
    "\n",
    "The strip comes from the CAD file `paper_strip_wicking.step`, written by\n",
    "`paper_strip_wicking_geometry.py` with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** While gravity is still negligible the uptake per unit width grows as\n",
    "$I=S\\sqrt t$ (Lucas-Washburn behaviour, J. R. Philip, Soil Sci. 84 (1957) 257-264), with the\n",
    "sorptivity from Parlange's integral (J.-Y. Parlange, Soil Sci. 119 (1975) 158-161),\n",
    "\n",
    "$$S^2=\\int_{h_i}^{0}\\big(\\theta_s+\\theta(h)-2\\theta_i\\big)\\,K(h)\\,\\mathrm dh .$$\n",
    "\n",
    "Later, gravity slows the rise. Treating the wetted zone as a sharp front driven by a constant\n",
    "suction $h_f=S^2/(2K_s\\Delta\\theta)$ gives Washburn's rise with gravity in the Green-Ampt form\n",
    "(W. H. Green, G. A. Ampt, J. Agric. Sci. 4 (1911) 1-24),\n",
    "\n",
    "$$t(L)=\\frac{\\Delta\\theta\\,h_f}{K_s}\\Big(-\\ln\\big(1-L/h_f\\big)-L/h_f\\Big),\\qquad \\Delta\\theta=\\theta_s-\\theta_i ,$$\n",
    "\n",
    "an approximation for the wetted height $L$ that is accurate when the front is sharp; the uptake\n",
    "is then $I=\\Delta\\theta\\,L$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import DampedNewton\n",
    "from onesim.numerics.time import BackwardEuler\n",
    "from onesim.physics.hydrodynamics import PressureHead, Richards, VanGenuchtenRetention\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.integrate import quad\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`section` cuts the loaded strip at half thickness; $x$ runs across the strip, $y$ upwards from\n",
    "the water surface. Linear triangles of 1 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sheet = load(\"paper_strip_wicking.step\")\n",
    "strip = sheet.section((0, 0, 1), origin=(0, 0, 1e-4))\n",
    "width, height = strip.size[:2]\n",
    "mesh = TriangularMesher(target_size=1e-3).generate(strip)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(12, 6))\n",
    "plots.geometry(\n",
    "    sheet,\n",
    "    selection={\"edge in the water\": sheet.boundaries.y_min},\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=20, azimuth=-60),\n",
    "    title=\"Paper strip from the STEP file\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Mid-plane: {mesh.cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`Richards` with the van Genuchten retention; gravity acts along $-y$ of the section by default.\n",
    "Backward Euler keeps the storage change exact in every step (mixed form); 1200 steps of 5 s\n",
    "follow the first 100 minutes. The damped Newton method handles the sharp front in the dry paper."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "paper = Richards(\n",
    "    domain=strip.domain(),\n",
    "    retention=VanGenuchtenRetention(alpha=12.0, n=2.5),\n",
    "    conductivity=1e-6,\n",
    "    saturated_water_content=0.7,\n",
    "    residual_water_content=0.0,\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Paper strip wicking\",\n",
    "    geometry=strip,\n",
    "    physics=(paper,),\n",
    "    initial_conditions=(InitialValue(paper.pressure_head, -1.0),),\n",
    "    boundary_conditions=(\n",
    "        PressureHead(physics=paper, boundary=strip.boundaries.y_min, value=0.0),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=1), quadrature_order=2),\n",
    "    nonlinear_solver=DampedNewton(\n",
    "        linear_solver=SparseDirect(),\n",
    "        relative_tolerance=1e-8,\n",
    "        absolute_tolerance=1e-10,\n",
    "        maximum_iterations=60,\n",
    "    ),\n",
    "    time_integrator=BackwardEuler(),\n",
    ")\n",
    "result = Simulation(problem=problem, mesh=mesh, numerics=numerics).run(\n",
    "    start_time=0.0, end_time=6000.0, time_step=5.0\n",
    ")\n",
    "water = result.field(paper.water_content)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The uptake per unit width is the integral of the water content gained, divided by the strip\n",
    "width; it is compared with $S\\sqrt t$. The wetted height is where the water content crosses half\n",
    "of the porosity $\\theta_s$ above $\\theta_i$ on the centre line. The uptake is compared\n",
    "with $S\\sqrt t$ and with the Green-Ampt rise."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "theta_i, theta_0, k_0 = (\n",
    "    float(paper.volumetric_water_content(-1.0)),\n",
    "    paper.saturated_water_content,\n",
    "    paper.conductivity,\n",
    ")\n",
    "sorptivity = np.sqrt(\n",
    "    quad(\n",
    "        lambda h: (theta_0 + paper.volumetric_water_content(h) - 2 * theta_i)\n",
    "        * paper.hydraulic_conductivity(h),\n",
    "        -1.0,\n",
    "        0.0,\n",
    "    )[0]\n",
    ")\n",
    "uptake = water.integrate()\n",
    "times, gained = (\n",
    "    np.asarray(uptake.times),\n",
    "    (np.asarray(uptake.values) - uptake.values[0]) / width,\n",
    ")\n",
    "y = np.linspace(0.0, height, 481)\n",
    "centre = np.column_stack((np.full_like(y, width / 2), y))\n",
    "wetted = lambda t: y[\n",
    "    np.argmax(water.evaluate(centre, time=t) < (theta_0 + theta_i) / 2)\n",
    "]\n",
    "suction = sorptivity**2 / (2 * k_0 * (theta_0 - theta_i))\n",
    "rise = np.linspace(0.0, 0.999 * suction, 4000)\n",
    "green_ampt = lambda t: np.interp(\n",
    "    t,\n",
    "    (theta_0 - theta_i)\n",
    "    * suction\n",
    "    / k_0\n",
    "    * (-np.log(1 - rise / suction) - rise / suction),\n",
    "    rise,\n",
    ")\n",
    "print(\n",
    "    f\"sorptivity (Parlange): {1e3 * sorptivity:.3f} mm/s^0.5, Green-Ampt suction head {1e3 * suction:.1f} mm\"\n",
    ")\n",
    "print(\n",
    "    \"   t [s]   uptake [mm]   S sqrt(t) [mm]   ratio   Green-Ampt [mm]   ratio   wetted height [mm]\"\n",
    ")\n",
    "for t in (60.0, 120.0, 300.0, 600.0, 1200.0, 3000.0, 6000.0):\n",
    "    i = int(np.argmin(np.abs(times - t)))\n",
    "    ga = (theta_0 - theta_i) * green_ampt(times[i])\n",
    "    print(\n",
    "        f\"{times[i]:8.0f} {1e3 * gained[i]:12.3f} {1e3 * sorptivity * np.sqrt(times[i]):15.3f} {gained[i] / (sorptivity * np.sqrt(times[i])):8.3f}\"\n",
    "        f\" {1e3 * ga:16.3f} {gained[i] / ga:8.3f} {1e3 * wetted(times[i]):17.1f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The water content in the strip after 2, 15 and 100 minutes; the uptake against $S\\sqrt t$ and the\n",
    "Green-Ampt rise; and the water content on the centre line at the same times."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "nearest = lambda t: float(times[np.argmin(np.abs(times - t))])\n",
    "fig = plots.figure(1, 5, size=(22, 7))\n",
    "for panel, t in zip((fig[0], fig[1], fig[2]), (120.0, 900.0, 6000.0)):\n",
    "    plots.surface(\n",
    "        water,\n",
    "        time=nearest(t),\n",
    "        limits=(0.0, 0.7),\n",
    "        xlabel=\"x [m]\",\n",
    "        ylabel=\"y [m]\",\n",
    "        label=\"water content\",\n",
    "        title=f\"after {nearest(t) / 60:.0f} min\",\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.line(\n",
    "    points={\"simulation\": (times[1:], 1e3 * gained[1:])},\n",
    "    reference={\n",
    "        \"S sqrt(t)\": (times[1:], 1e3 * sorptivity * np.sqrt(times[1:])),\n",
    "        \"Green-Ampt rise\": (\n",
    "            times[1:],\n",
    "            1e3 * (theta_0 - theta_i) * green_ampt(times[1:]),\n",
    "        ),\n",
    "    },\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"uptake per width [mm]\",\n",
    "    title=\"Square-root law, then gravity\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"{t / 60:.0f} min\": (water.evaluate(centre, time=nearest(t)), 1e3 * y)\n",
    "        for t in (120.0, 900.0, 6000.0)\n",
    "    },\n",
    "    xlabel=\"water content\",\n",
    "    ylabel=\"height y [mm]\",\n",
    "    title=\"Water content on the centre line\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[4],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lay the strip flat (`gravity=0.0` in `Richards`): the uptake then follows $S\\sqrt t$ for ever.\n",
    "Or change the pore-size parameter $\\alpha$ to see how far finer or coarser papers lift the water."
   ]
  }
 ]
}
