{
 "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": [
    "# Aquifer-system compaction above a bedrock step\n",
    "\n",
    "Fluid in the pores of an aquifer carries part of the weight of the overlying sediments. When\n",
    "pumping lowers the pore pressure, the solid skeleton has to take over that load and the\n",
    "sediments compact; at the land surface this appears as subsidence. Where the sediment thickness\n",
    "changes abruptly over a buried bedrock step, the compaction is uneven and the ground is\n",
    "stretched horizontally, the classical mechanism for earth fissures.\n",
    "\n",
    "The set-up is the idealized basin section of S.A. Leake and P.A. Hsieh, *Simulation of\n",
    "deformation of sediments from decline of ground-water levels in an aquifer underlain by a\n",
    "bedrock step*, U.S. Geological Survey Open-File Report 97-47, 1997:\n",
    "\n",
    "| layer | depth | conductivity $K$ | skeletal storage $S_{sk}$ | Young's modulus | Poisson's ratio |\n",
    "|---|---|---|---|---|---|\n",
    "| upper aquifer | 0-20 m | 25 m/d | $10^{-5}$ 1/m | $8\\cdot10^{8}$ Pa | 0.25 |\n",
    "| confining unit | 20-40 m | 0.01 m/d | $10^{-4}$ 1/m | $8\\cdot10^{7}$ Pa | 0.25 |\n",
    "| lower aquifer | 40-440 m | 25 m/d | $10^{-5}$ 1/m | $8\\cdot10^{8}$ Pa | 0.25 |\n",
    "\n",
    "The bedrock under the right part of the basin ($x>4000$ m) rises to 120 m depth. At the basin\n",
    "centre ($x=0$) the head in the lower aquifer is lowered by 6 m per year for 10 years; the upper\n",
    "aquifer is held at constant head.\n",
    "\n",
    "The basin comes from the CAD file `terzaghi_aquifer_compaction.step`, the confining unit alone\n",
    "from `terzaghi_aquifer_compaction_confining.step`; the script\n",
    "`terzaghi_aquifer_compaction_geometry.py` builds both with the CAD objects of OneSimulation. The\n",
    "faces carry the name of their layer (`deep`: lower aquifer left of the step, `lower`,\n",
    "`confining`, `upper`):\n",
    "\n",
    "| sides | flow | mechanics (Biot) |\n",
    "|---|---|---|\n",
    "| `deep.y_min`, `deep.x_max`, `lower.y_min`: base with the step | no flow | fixed |\n",
    "| `deep.x_min`, `lower.x_min`: lower aquifer at $x=0$ (pumping) | head $-(6\\ \\mathrm{m/yr})\\,t$ | roller |\n",
    "| `confining.x_min`, `confining.x_max`, `lower.x_max` | no flow | roller |\n",
    "| `upper.x_min`, `upper.x_max` | head held constant | roller |\n",
    "| `upper.y_max`: land surface | head held constant | traction free |\n",
    "\n",
    "**Two models.** The *Terzaghi method* solves transient groundwater flow,\n",
    "$S_{sk}\\,\\partial_t h-\\nabla\\cdot(K\\nabla h)=0$, and stacks the one-dimensional compaction\n",
    "$-S_{sk}\\,h\\,\\mathrm dy$ from the base upward. The *Biot method* couples Darcy flow and\n",
    "plane-strain elasticity:\n",
    "\n",
    "$$\\nabla\\cdot\\big(\\mathbf C:\\boldsymbol\\varepsilon(\\mathbf u)-\\alpha\\,p\\,\\mathbf I\\big)=0,\\qquad\n",
    "  \\partial_t\\big(S\\,p+\\alpha\\,\\nabla\\cdot\\mathbf u\\big)-\\nabla\\cdot\\Big(\\frac{\\kappa}{\\mu}\\nabla p\\Big)=0 .$$\n",
    "\n",
    "Heads are in metres, times in days; stiffness is divided by $\\rho g$, so the pore pressure of the\n",
    "Biot model is the head change."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import Geometric, merge_blocks, rectangle_block, region_mesh\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, Nitsche\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.numerics.time import BDF, AdaptiveTimeStep\n",
    "from onesim.physics.geotechnics import (\n",
    "    BiotConsolidation,\n",
    "    BiotFixedComponent,\n",
    "    BiotNormalTraction,\n",
    "    GroundwaterFlow,\n",
    "    PoreFluidFlux,\n",
    "    PrescribedPorePressure,\n",
    ")\n",
    "from onesim.physics.solid_mechanics import FixedDisplacement\n",
    "from onesim.results.comparisons import convergence\n",
    "from onesim.results.storage import Output\n",
    "from onesim.simulation import (\n",
    "    OutwardFluxBoundary,\n",
    "    PrescribedValueBoundary,\n",
    "    Problem,\n",
    "    Simulation,\n",
    "    regionwise,\n",
    ")\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`section` cuts the loaded solids at mid-thickness; the sides of the section keep the face names.\n",
    "A graded block of triangles over the bounding rectangle, with rows on the layer boundaries and a\n",
    "column on the step, is restricted to the basin by `region_mesh`. Three levels halve the cells."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "solid = load(\"terzaghi_aquifer_compaction.step\")\n",
    "basin = solid.section((0, 0, 1), origin=(0, 0, 50.0))\n",
    "confining = load(\"terzaghi_aquifer_compaction_confining.step\").section(\n",
    "    (0, 0, 1), origin=(0, 0, 50.0)\n",
    ")\n",
    "sides = basin.boundaries\n",
    "width, depth = basin.size[:2]\n",
    "step, shelf = 4000.0, -120.0\n",
    "base = sides[\"deep.y_min\"] | sides[\"deep.x_max\"] | sides[\"lower.y_min\"]\n",
    "outlet = sides[\"deep.x_min\"] | sides[\"lower.x_min\"]\n",
    "sealed = sides[\"confining.x_min\"] | sides[\"confining.x_max\"] | sides[\"lower.x_max\"]\n",
    "constant_head = sides[\"upper.x_min\"] | sides[\"upper.x_max\"] | sides[\"upper.y_max\"]\n",
    "\n",
    "levels = [2, 3, 4]\n",
    "meshes = []\n",
    "for level in levels:\n",
    "    x = np.r_[\n",
    "        step * Geometric(12 * level, ratio=20.0, toward=\"end\").reference(),\n",
    "        step + (width - step) * Geometric(6 * level, ratio=12.0).reference()[1:],\n",
    "    ]\n",
    "    y = np.r_[\n",
    "        -depth\n",
    "        + (depth + shelf) * Geometric(5 * level, ratio=6.0, toward=\"end\").reference(),\n",
    "        shelf + 80.0 * Geometric(3 * level, ratio=3.0, toward=\"end\").reference()[1:],\n",
    "        np.linspace(-40.0, -20.0, 2 * level + 1)[1:],\n",
    "        np.linspace(-20.0, 0.0, level + 1)[1:],\n",
    "    ]\n",
    "    block = rectangle_block(\n",
    "        (0.0, -depth), width, depth, (len(x) - 1, len(y) - 1), grading=(x, y)\n",
    "    )\n",
    "    meshes.append(\n",
    "        region_mesh(\n",
    "            merge_blocks([block]).triangulated(\"alternating\"), basin, geometry=basin\n",
    "        )\n",
    "    )\n",
    "\n",
    "fig = plots.figure(2, 1, size=(14, 5))\n",
    "plots.geometry(\n",
    "    basin,\n",
    "    selection={\"pumped side\": outlet, \"constant head\": constant_head, \"base\": base},\n",
    "    labels=False,\n",
    "    title=\"Section of the basin (drawn to scale)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Coarsest mesh: {meshes[0].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Models\n",
    "\n",
    "Material values differ between the confining unit and the aquifers: `regionwise` takes the\n",
    "confining unit read from its own file as the region. Both models run with second-order BDF and\n",
    "error-controlled time steps over ten years."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "year, decline, poisson = 365.25, 6.0 / 365.25, 0.25\n",
    "layered = lambda in_confining, in_aquifers: regionwise(\n",
    "    ((confining, in_confining),), default=in_aquifers\n",
    ")\n",
    "shear, lame = 1 / (2 * (1 + poisson)), poisson / ((1 + poisson) * (1 - 2 * poisson))\n",
    "unit_stiffness = np.diag([2 * shear] * 3 + [shear] * 3) + lame * np.pad(\n",
    "    np.ones((3, 3)), (0, 3)\n",
    ")\n",
    "youngs_modulus = layered(8e7 / 9820.0, 8e8 / 9820.0)\n",
    "head_at_outlet = lambda time, coordinate: [-decline * time]\n",
    "steps = AdaptiveTimeStep(\n",
    "    initial=year / (2**19 - 1),\n",
    "    minimum=1e-6,\n",
    "    maximum=year,\n",
    "    relative_tolerance=1e-3,\n",
    "    absolute_tolerance=1e-3,\n",
    ")\n",
    "elements = dict(\n",
    "    spatial=FiniteElement(\n",
    "        element=Lagrange(2), boundary_enforcement=Nitsche(penalty=16)\n",
    "    ),\n",
    "    linear_solver=SparseDirect(),\n",
    "    time_integrator=BDF(order=2),\n",
    ")\n",
    "\n",
    "biot = BiotConsolidation(\n",
    "    domain=basin.domain(),\n",
    "    kinematics=\"plane_strain\",\n",
    "    biot_coefficient=1.0,\n",
    "    fluid_viscosity=1.0,\n",
    "    elastic_stiffness=lambda x, y: youngs_modulus(x, y, 0 * x)[:, None, None]\n",
    "    * unit_stiffness,\n",
    "    specific_storage=layered(1e-5, 1e-6),\n",
    "    permeability=layered(0.01, 25.0),\n",
    ")\n",
    "coupled = Problem(\n",
    "    name=\"Biot method, bedrock step\",\n",
    "    geometry=basin,\n",
    "    physics=(biot,),\n",
    "    boundary_conditions=(\n",
    "        FixedDisplacement(physics=biot, boundary=base, value=(0.0, 0.0)),\n",
    "        BiotFixedComponent(\n",
    "            physics=biot,\n",
    "            boundary=sides.all - base - sides[\"upper.y_max\"],\n",
    "            component=\"x\",\n",
    "        ),\n",
    "        BiotNormalTraction(physics=biot, boundary=sides[\"upper.y_max\"], value=0.0),\n",
    "        PrescribedPorePressure(physics=biot, boundary=outlet, value=head_at_outlet),\n",
    "        PrescribedPorePressure(physics=biot, boundary=constant_head, value=0.0),\n",
    "        PoreFluidFlux(physics=biot, boundary=base | sealed, flux=0.0),\n",
    "    ),\n",
    "    initial_conditions=(InitialValue(biot.fluid_content, 0.0),),\n",
    ")\n",
    "solver = Numerics(\n",
    "    **elements,\n",
    "    nonlinear_solver=Newton(\n",
    "        linear_solver=SparseDirect(),\n",
    "        jacobian=\"analytic\",\n",
    "        relative_tolerance=1e-3,\n",
    "        absolute_tolerance=1e-12,\n",
    "    )\n",
    ")\n",
    "results = [\n",
    "    Simulation(problem=coupled, mesh=mesh, numerics=solver).run(\n",
    "        start_time=0.0,\n",
    "        end_time=10 * year,\n",
    "        time_step=steps,\n",
    "        output=Output(fields=(biot.pore_pressure, biot.displacement), interval=year),\n",
    "    )\n",
    "    for mesh in meshes\n",
    "]\n",
    "head, displacement = results[-1].field(biot.pore_pressure), results[-1].field(\n",
    "    biot.displacement\n",
    ")\n",
    "\n",
    "flow = GroundwaterFlow(\n",
    "    domain=basin.domain(),\n",
    "    conductivity=layered(0.01, 25.0),\n",
    "    specific_storage=layered(1e-4, 1e-5),\n",
    ")\n",
    "uncoupled = Problem(\n",
    "    name=\"Terzaghi method, bedrock step\",\n",
    "    geometry=basin,\n",
    "    physics=(flow,),\n",
    "    boundary_conditions=(\n",
    "        PrescribedValueBoundary(physics=flow, boundary=outlet, value=head_at_outlet),\n",
    "        PrescribedValueBoundary(\n",
    "            physics=flow, boundary=constant_head, value=lambda time, coordinate: [0.0]\n",
    "        ),\n",
    "        OutwardFluxBoundary(\n",
    "            physics=flow,\n",
    "            boundary=base | sealed,\n",
    "            flux=lambda interior, time, normal, coordinate: [0.0],\n",
    "            jacobian=((0,),),\n",
    "        ),\n",
    "    ),\n",
    "    initial_conditions=(InitialValue(flow.head, 0.0),),\n",
    ")\n",
    "terzaghi_head = (\n",
    "    Simulation(\n",
    "        problem=uncoupled,\n",
    "        mesh=meshes[-1],\n",
    "        numerics=Numerics(\n",
    "            **elements,\n",
    "            nonlinear_solver=Newton(\n",
    "                linear_solver=SparseDirect(),\n",
    "                jacobian=\"analytic\",\n",
    "                relative_tolerance=1e-6,\n",
    "                absolute_tolerance=1e-12,\n",
    "            )\n",
    "        ),\n",
    "    )\n",
    "    .run(\n",
    "        start_time=0.0,\n",
    "        end_time=10 * year,\n",
    "        time_step=steps,\n",
    "        output=Output(fields=(flow.head,), interval=year),\n",
    "    )\n",
    "    .field(flow.head)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the published results\n",
    "\n",
    "Leake and Hsieh report the settlement in the columns next to the step after ten years. The\n",
    "Terzaghi settlement is the integral of $S_{sk}\\,h$ over each vertical line from the base up; the\n",
    "horizontal strain at the land surface is the gradient of the Biot displacement."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "times = np.asarray(head.times)\n",
    "end = float(times[-1])\n",
    "columns_x = np.r_[np.linspace(1.0, width - 1.0, 261), step - 40.0, step + 40.0]\n",
    "X, Y = np.meshgrid(columns_x, np.linspace(-depth, 0.0, 881), indexing=\"ij\")\n",
    "Y = np.maximum(Y, np.where(X > step, shelf, -depth))\n",
    "column_points = np.column_stack((X.ravel(), Y.ravel()))\n",
    "compaction = (\n",
    "    layered(1e-4, 1e-5).evaluate(column_points)\n",
    "    * np.ravel(terzaghi_head.evaluate(column_points, time=end))\n",
    ").reshape(X.shape)\n",
    "terzaghi_settlement = -np.trapezoid(compaction, Y, axis=1)\n",
    "terzaghi_near_surface = -np.trapezoid(np.where(Y <= -10.0, compaction, 0.0), Y, axis=1)\n",
    "probes = np.array([[step - 40.0, -10.0], [step + 40.0, -10.0]])\n",
    "surface_x = np.linspace(step, width, 601)\n",
    "tension = lambda field: field.gradient(\n",
    "    np.column_stack((surface_x, np.full_like(surface_x, -0.01))), time=end\n",
    ")[:, 0, 0]\n",
    "biot_near_step = -displacement.evaluate(probes, time=end)[:, 1]\n",
    "\n",
    "print(\n",
    "    \"after 10 years, at 10 m depth next to the step      thick side x = 3960 m   thin side x = 4040 m\"\n",
    ")\n",
    "print(\n",
    "    f\"  Biot settlement [m]                               {biot_near_step[0]:21.4f} {biot_near_step[1]:21.4f}\"\n",
    ")\n",
    "print(\n",
    "    \"  published Biot settlement [m]                                      0.10            below 0.08\"\n",
    ")\n",
    "print(\n",
    "    f\"  Terzaghi settlement [m]                           {terzaghi_near_surface[-2]:21.4f} {terzaghi_near_surface[-1]:21.4f}\"\n",
    ")\n",
    "print(\n",
    "    \"  published Terzaghi settlement [m]                            above 0.18            below 0.08\"\n",
    ")\n",
    "print(\n",
    "    f\"largest horizontal strain at the land surface above the step (Biot): {tension(displacement).max():.2e} at x = \"\n",
    "    f\"{surface_x[tension(displacement).argmax()]:.0f} m; published: tension above 1e-4\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Mesh study\n",
    "\n",
    "Three quantities of the Biot result on the three meshes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "quantities = {\n",
    "    \"settlement at x = 3960 m [m]\": [\n",
    "        -result.field(biot.displacement).evaluate(probes[:1], time=end)[0, 1]\n",
    "        for result in results\n",
    "    ],\n",
    "    \"settlement at the surface, x = 0 [m]\": [\n",
    "        -result.field(biot.displacement).evaluate([[1e-3, 0.0]], time=end)[0, 1]\n",
    "        for result in results\n",
    "    ],\n",
    "    \"largest surface strain [1e-4]\": [\n",
    "        1e4 * tension(result.field(biot.displacement)).max() for result in results\n",
    "    ],\n",
    "}\n",
    "print(\n",
    "    \"quantity                              \"\n",
    "    + \"\".join(f\"{mesh.cell_count:>10d} cells\" for mesh in meshes)\n",
    "    + \"   change between the two finest\"\n",
    ")\n",
    "for name, values in quantities.items():\n",
    "    print(\n",
    "        f\"{name:38s}\"\n",
    "        + \"\".join(f\"{value:16.5f}\" for value in values)\n",
    "        + f\"   {100 * convergence(values, [1 / level for level in levels]).change:.3f} %\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Head change and settlement of the Biot model after ten years (heights five times enlarged), the\n",
    "settlement of the land surface with both methods, and the horizontal strain at the land surface."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "line_x = np.linspace(1.0, width - 1.0, 521)\n",
    "at_surface = np.column_stack((line_x, np.full_like(line_x, -0.01)))\n",
    "yearly = {\n",
    "    years: float(times[np.argmin(np.abs(times - years * year))]) for years in (2, 5, 10)\n",
    "}\n",
    "fig = plots.figure(2, 2, size=(16, 9))\n",
    "plots.surface(\n",
    "    head,\n",
    "    time=end,\n",
    "    limits=(-60.0, 0.0),\n",
    "    contours=6,\n",
    "    subdivisions=2,\n",
    "    aspect=5.0,\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    label=\"head change [m]\",\n",
    "    title=\"Head change after 10 years (Biot)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.surface(\n",
    "    displacement,\n",
    "    time=end,\n",
    "    component=lambda u, position: -u[:, 1],\n",
    "    limits=(0.0, 0.3),\n",
    "    contours=6,\n",
    "    subdivisions=2,\n",
    "    aspect=5.0,\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    label=\"settlement [m]\",\n",
    "    title=\"Settlement after 10 years (Biot)\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"Biot, {years} years\": (\n",
    "            line_x,\n",
    "            -displacement.evaluate(at_surface, time=t)[:, 1],\n",
    "        )\n",
    "        for years, t in yearly.items()\n",
    "    },\n",
    "    reference={\"Terzaghi method, 10 years\": (columns_x[:-2], terzaghi_settlement[:-2])},\n",
    "    points={\"published Biot, 10 years\": ([step - 40.0], [0.10])},\n",
    "    vlines={\"step in the bedrock\": step},\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"settlement [m]\",\n",
    "    title=\"Settlement of the land surface\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"{years} years\": (\n",
    "            surface_x[1:-1],\n",
    "            1e4\n",
    "            * displacement.gradient(\n",
    "                np.column_stack((surface_x, np.full_like(surface_x, -0.01))), time=t\n",
    "            )[1:-1, 0, 0],\n",
    "        )\n",
    "        for years, t in yearly.items()\n",
    "    },\n",
    "    hlines={\"published: tension above 1e-4\": 1.0},\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"horizontal strain [1e-4]\",\n",
    "    title=\"Horizontal strain at the land surface above the step (Biot)\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Move the step or change the thickness of the confining unit in\n",
    "`terzaghi_aquifer_compaction_geometry.py` and write the STEP files again: the tensile strain\n",
    "above the step, which controls earth fissuring, follows. Raise the decline rate or extend the\n",
    "pumping period; with `kinematics=\"axisymmetric\"` the same model describes a single pumping well\n",
    "in a layered aquifer."
   ]
  }
 ]
}
