{
 "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": [
    "# Horizontal infiltration into an unsaturated soil column\n",
    "\n",
    "A long horizontal column of soil is initially at a uniform (fairly dry) water\n",
    "content $\\theta_i$. From $t=0$ on, the inlet face $x=0$ is held close to\n",
    "saturation, so water is drawn into the column by capillarity alone; gravity\n",
    "plays no role in a horizontal column. The far end stays dry during the whole\n",
    "experiment.\n",
    "\n",
    "OneSimulation solves the mixed form of the Richards equation with a\n",
    "conservative finite-volume scheme,\n",
    "\n",
    "$$\\frac{\\partial\\theta(h)}{\\partial t}\n",
    "  =\\frac{\\partial}{\\partial x}\\Big(K(h)\\,\\frac{\\partial h}{\\partial x}\\Big),\\qquad\n",
    "  h(x,0)=h_i,\\quad h(0,t)=h_0,\\quad q(L,t)=0,$$\n",
    "\n",
    "with the van Genuchten-Mualem closure for the water content $\\theta(h)$ and\n",
    "the hydraulic conductivity $K(h)$. Written in terms of $\\theta$ this is a\n",
    "nonlinear diffusion equation with the soil-water diffusivity\n",
    "$D(\\theta)=K/C$, $C=d\\theta/dh$.\n",
    "\n",
    "**Reference.** Without gravity and without a length scale the profile depends on\n",
    "Boltzmann's similarity variable $\\varphi=x/\\sqrt{t}$ only,\n",
    "$\\theta(x,t)=\\Theta(\\varphi)$, where $\\Theta$ solves\n",
    "\n",
    "$$\\frac{d}{d\\varphi}\\Big(D(\\Theta)\\frac{d\\Theta}{d\\varphi}\\Big)\n",
    "  +\\frac{\\varphi}{2}\\frac{d\\Theta}{d\\varphi}=0,\\qquad\n",
    "  \\Theta(0)=\\theta_0,\\quad\\Theta(\\infty)=\\theta_i,$$\n",
    "\n",
    "and the cumulative infiltration grows as the square root of time,\n",
    "\n",
    "$$I(t)=S\\sqrt{t},\\qquad S=-2\\,D(\\theta_0)\\,\\Theta'(0),$$\n",
    "\n",
    "with $S$ the sorptivity of the soil. $D$ varies by a factor of forty across the\n",
    "wetting front, so $\\Theta(\\varphi)$ has no closed form; it is obtained as a\n",
    "boundary-value problem of this ordinary differential equation, independently of\n",
    "the finite-volume solver."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.meshing import TensorCollocationMesh\n",
    "from onesim.numerics.time import ForwardEulerTimeIntegrator\n",
    "from onesim.physics.hydrodynamics import Richards1DProvider\n",
    "from onesim.physics.hydrodynamics.porous.numerics.equations.multiphysics.richards import (\n",
    "    RichardsColumnFiniteVolume,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.integrate import solve_bvp\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Soil column\n",
    "\n",
    "A loam-type soil in a column of 0.5 m, 400 cells. The inlet is held at a small suction\n",
    "of 0.1 m (95 % of saturation), the far end is a no-flow face and gravity is switched\n",
    "off. The solver advances the stored water with explicit steps of 0.02 s and the\n",
    "harmonic mean of the cell conductivities."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "length, cells, inlet_head, initial_head = 0.5, 400, -0.10, -1.00\n",
    "x = (np.arange(cells) + 0.5) * length / cells\n",
    "column = TensorCollocationMesh(\n",
    "    axes=(x,), coordinate_system=\"cartesian\", periodic=(False,)\n",
    ")\n",
    "soil = Richards1DProvider(\n",
    "    mesh=column,\n",
    "    spatial=RichardsColumnFiniteVolume(),\n",
    "    time_integrator=ForwardEulerTimeIntegrator(),\n",
    "    residual_water_content=0.08,\n",
    "    saturated_water_content=0.43,\n",
    "    van_genuchten_alpha=3.6,\n",
    "    van_genuchten_n=1.56,\n",
    "    saturated_hydraulic_conductivity=1.0e-5,\n",
    "    gravity=0.0,\n",
    "    initial_pressure_head=initial_head,\n",
    "    bottom_pressure_head=inlet_head,\n",
    "    top_pressure_head=None,\n",
    "    final_time=60.0,\n",
    "    time_step=0.02,\n",
    ")\n",
    "inlet, initial = float(soil.water_content(inlet_head)), float(\n",
    "    soil.water_content(initial_head)\n",
    ")\n",
    "print(f\"water content: {inlet:.4f} at the inlet, {initial:.4f} initially\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulation\n",
    "\n",
    "One hour in segments of one minute, each started from the pressure head of the one\n",
    "before; the water that entered through the inlet in each segment adds up to the\n",
    "cumulative infiltration."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "times, infiltration, head, profiles, residual = [0.0], [0.0], None, {}, 0.0\n",
    "for minute in range(1, 61):\n",
    "    segment = soil.run(head)\n",
    "    head, residual = segment.pressure_head, max(residual, segment.mass_balance_residual)\n",
    "    times.append(60.0 * minute)\n",
    "    infiltration.append(infiltration[-1] + segment.boundary_exchange)\n",
    "    if minute in (10, 20, 40, 60):\n",
    "        profiles[60.0 * minute] = segment.water_content\n",
    "times, infiltration = np.array(times), np.array(infiltration)\n",
    "print(\n",
    "    f\"cumulative infiltration after one hour: {1e3 * infiltration[-1]:.2f} mm, largest mass-balance residual {residual:.1e} m\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Similarity solution\n",
    "\n",
    "With $q=D(\\Theta)\\,\\Theta'$ the similarity equation is the first-order system\n",
    "$\\Theta'=q/D$, $q'=-\\tfrac{\\varphi}{2}\\,q/D$ between $\\Theta(0)=\\theta_0$ and\n",
    "$\\Theta=\\theta_i$ far ahead of the front. The diffusivity comes from the conductivity\n",
    "and the water capacity of the same soil law."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "far = 6.5e-3\n",
    "diffusivity = lambda theta: (\n",
    "    soil.hydraulic_conductivity(soil.pressure_head(np.clip(theta, initial, inlet)))\n",
    "    / soil.water_capacity(soil.pressure_head(np.clip(theta, initial, inlet)))\n",
    ")\n",
    "phi = np.linspace(0.0, far, 600)\n",
    "similarity = solve_bvp(\n",
    "    lambda p, y: np.vstack(\n",
    "        (y[1] / diffusivity(y[0]), -0.5 * p * y[1] / diffusivity(y[0]))\n",
    "    ),\n",
    "    lambda left, right: np.array([left[0] - inlet, right[0] - initial]),\n",
    "    phi,\n",
    "    np.vstack(\n",
    "        (\n",
    "            initial + (inlet - initial) * np.exp(-((phi / 2e-3) ** 2)),\n",
    "            np.full_like(phi, -1e-4),\n",
    "        )\n",
    "    ),\n",
    "    tol=1e-9,\n",
    "    max_nodes=200000,\n",
    ")\n",
    "profile = lambda p: similarity.sol(np.minimum(p, far))[0]\n",
    "sorptivity = -2.0 * similarity.sol(0.0)[1]\n",
    "print(f\"sorptivity from the similarity solution: {sorptivity:.4e} m/√s\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison\n",
    "\n",
    "The profiles at four times against $\\Theta(x/\\sqrt{t})$, their collapse onto one curve\n",
    "in $\\varphi$, and the cumulative infiltration against $S\\sqrt{t}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\"time [min]   largest profile deviation   rms deviation   (fractions of θ0 - θi)\")\n",
    "for t, theta in profiles.items():\n",
    "    deviation = np.abs(theta - profile(x / np.sqrt(t))) / (inlet - initial)\n",
    "    print(\n",
    "        f\"{t / 60:10.0f} {100 * deviation.max():24.2f} % {100 * np.sqrt(np.mean(deviation**2)):13.2f} %\"\n",
    "    )\n",
    "common = np.linspace(0.0, 3.9e-3, 200)\n",
    "collapsed = np.array(\n",
    "    [np.interp(common, x / np.sqrt(t), theta) for t, theta in profiles.items()]\n",
    ")\n",
    "late = times >= 600.0\n",
    "print(\n",
    "    f\"spread of the four profiles at equal φ: {100 * np.ptp(collapsed, axis=0).max() / (inlet - initial):.2f} % of θ0 - θi\"\n",
    ")\n",
    "print(\n",
    "    f\"cumulative infiltration from 10 min on: I / (S √t) - 1 within \"\n",
    "    f\"{100 * np.abs(infiltration[late] / (sorptivity * np.sqrt(times[late])) - 1).max():.2f} %, \"\n",
    "    f\"fitted exponent {np.polyfit(np.log(times[late]), np.log(infiltration[late]), 1)[0]:.4f} (similarity: 0.5)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The wetting profiles in the column, the same profiles against the similarity variable,\n",
    "and the cumulative infiltration against $\\sqrt{t}$, a straight line of slope $S$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = np.linspace(0.0, 0.32, 800)\n",
    "fig = plots.figure(1, 3, size=(16, 4.8))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"{t / 60:.0f} min\": (1e2 * x[::5], theta[::5]) for t, theta in profiles.items()\n",
    "    },\n",
    "    reference={\n",
    "        f\"{t / 60:.0f} min\": (1e2 * fine, profile(fine / np.sqrt(t))) for t in profiles\n",
    "    },\n",
    "    xlimits=(0.0, 32.0),\n",
    "    xlabel=\"position x [cm]\",\n",
    "    ylabel=\"water content θ\",\n",
    "    title=\"Wetting profiles: simulation (markers), similarity (dashed)\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"{t / 60:.0f} min\": (1e3 * x[::5] / np.sqrt(t), theta[::5])\n",
    "        for t, theta in profiles.items()\n",
    "    },\n",
    "    reference={\"Θ(φ), similarity solution\": (1e3 * phi, profile(phi))},\n",
    "    xlimits=(0.0, 1e3 * far),\n",
    "    xlabel=\"φ = x / √t [mm/√s]\",\n",
    "    ylabel=\"water content θ\",\n",
    "    title=\"All profiles on one curve\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (np.sqrt(times[::3]), 1e3 * infiltration[::3])},\n",
    "    reference={\"S √t\": (np.sqrt(times), 1e3 * sorptivity * np.sqrt(times))},\n",
    "    xlabel=\"√t [√s]\",\n",
    "    ylabel=\"cumulative infiltration I [mm]\",\n",
    "    title=\"Sorptivity law I = S √t\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lower `initial_head` to start from a drier soil: the diffusivity contrast across the\n",
    "front grows and the harmonic-mean conductivity needs finer cells to keep the early\n",
    "infiltration right. Set `gravity=1.0` to turn the column vertical and watch the\n",
    "late-time infiltration rate approach the saturated conductivity instead of decaying as\n",
    "$1/\\sqrt{t}$ (Philip's two-term law $I=S\\sqrt{t}+At$)."
   ]
  }
 ]
}
