{
 "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": [
    "# The Mandel-Cryer effect in a sphere\n",
    "\n",
    "A sphere of saturated soil, radius $a=1$ m, is loaded at $t=0$ by a uniform surface\n",
    "pressure $P=100$ kPa and is free to drain through its surface. At the instant of loading\n",
    "the water cannot escape, so the load is carried by an **undrained** pore pressure $p_0$\n",
    "that is uniform in the whole sphere. Then the outer shell drains first, consolidates and\n",
    "contracts. The contracting shell squeezes the still undrained core, and the core pore\n",
    "pressure **rises above $p_0$** before it finally decays. This non-monotonic response,\n",
    "impossible in uncoupled (Terzaghi-type) diffusion, is the *Mandel-Cryer effect*\n",
    "(J. Mandel, Géotechnique 3, 287, 1953; C.W. Cryer, Q. J. Mech. Appl. Math. 16, 401, 1963).\n",
    "\n",
    "The physics is Biot's theory of poroelasticity:\n",
    "\n",
    "$$\\nabla\\cdot\\big(\\mathbf C:\\boldsymbol\\varepsilon(\\mathbf u)-\\alpha\\,p\\,\\mathbf I\\big)=0,\\qquad\n",
    "  \\zeta=S\\,p+\\alpha\\,\\nabla\\cdot\\mathbf u,\\qquad\n",
    "  \\partial_t\\zeta-\\nabla\\cdot\\Big(\\frac{\\kappa}{\\mu_f}\\nabla p\\Big)=0 ,$$\n",
    "\n",
    "with displacement $\\mathbf u$, pore pressure $p$, fluid content $\\zeta$, Biot coefficient\n",
    "$\\alpha$, storage coefficient $S$ and mobility $\\kappa/\\mu_f$.\n",
    "\n",
    "The sphere and its load are symmetric about the $z$ axis, so the model is axisymmetric: the\n",
    "fields depend on the radius $x$ and the height $z$ of the meridian plane only, and every\n",
    "integral carries the weight $2\\pi x$. One quarter of the sphere comes from the CAD file\n",
    "`mandel_cryer_consolidation.step`, written by `mandel_cryer_consolidation_geometry.py` with the\n",
    "CAD objects of OneSimulation as a quarter disc revolved by 180°; the model is its meridian\n",
    "plane, the quarter disc. Its sides keep the\n",
    "names of the faces they were cut from:\n",
    "\n",
    "| side | mechanics | flow |\n",
    "|---|---|---|\n",
    "| `surface`, $r=a$ | total normal traction $-P$ | drained, $p=0$ |\n",
    "| `equator`, $z=0$ | roller ($u_z=0$) | no flow |\n",
    "| axis line $x=0$, where the faces `start` and `end` meet | axis of symmetry | axis of symmetry |\n",
    "\n",
    "**Material.** A soft clayey silt: drained Young's modulus 10 MPa, drained Poisson's ratio 0\n",
    "(the case with the strongest effect), Biot coefficient 1, permeability $10^{-14}$ m², water\n",
    "viscosity $10^{-3}$ Pa s, porosity 0.4 and water bulk modulus 2.2 GPa. Pressures are in MPa and\n",
    "times in hours.\n",
    "\n",
    "**Reference.** Cryer's exact series for the pore pressure $p(r,t)$, with the compressibility of\n",
    "the water kept."
   ]
  },
  {
   "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, Nitsche\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.numerics.time import BDF, BackwardEuler\n",
    "from onesim.physics.geotechnics import (\n",
    "    BiotConsolidation,\n",
    "    BiotFixedComponent,\n",
    "    BiotNormalTraction,\n",
    "    PoreFluidFlux,\n",
    "    PrescribedPorePressure,\n",
    ")\n",
    "from onesim.results.comparisons import convergence\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.optimize import brentq\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the quarter sphere with its named faces; `section` with the plane $y=0$ gives the\n",
    "meridian plane, whose sides keep the names of the faces they were cut from. Three triangle meshes\n",
    "halve the cell size from one to the next."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "quarter = load(\"mandel_cryer_consolidation.step\")\n",
    "faces = quarter.boundaries\n",
    "meridian = quarter.section((0, 1, 0))\n",
    "sides = meridian.boundaries\n",
    "radius = meridian.size[0]\n",
    "sizes = [0.10, 0.05, 0.025]\n",
    "meshes = [TriangularMesher(target_size=size).generate(meridian) for size in sizes]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 6))\n",
    "plots.geometry(\n",
    "    quarter,\n",
    "    selection={\"draining surface\": faces.surface, \"equator\": faces.equator},\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=25, azimuth=-60),\n",
    "    title=\"Quarter of the sphere with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian plane, middle mesh: {meshes[1].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The undrained pore pressure $p_0$, the consolidation coefficient $c$ and the consolidation time\n",
    "$a^2/c$ follow from the material. The same problem runs on the three meshes with second-order\n",
    "BDF steps of $0.002\\,a^2/c$ after a backward-Euler start."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "load_pressure, youngs_modulus, storage, mobility = (\n",
    "    0.1,\n",
    "    10.0,\n",
    "    0.4 / 2.2e3,\n",
    "    1e-14 / 1e-3 * 1e6 * 3600.0,\n",
    ")\n",
    "stiffness_ratio = youngs_modulus * storage + 1\n",
    "undrained = load_pressure / (stiffness_ratio / 3 + 2 / 3)\n",
    "consolidation_time = radius**2 * (storage + 1 / youngs_modulus) / mobility\n",
    "model = BiotConsolidation(\n",
    "    domain=meridian.domain(),\n",
    "    kinematics=\"axisymmetric\",\n",
    "    youngs_modulus=youngs_modulus,\n",
    "    poisson_ratio=0.0,\n",
    "    biot_coefficient=1.0,\n",
    "    specific_storage=storage,\n",
    "    permeability=mobility,\n",
    "    fluid_viscosity=1.0,\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Cryer's sphere\",\n",
    "    geometry=meridian,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        BiotFixedComponent(physics=model, boundary=sides.equator, component=\"z\"),\n",
    "        BiotNormalTraction(physics=model, boundary=sides.surface, value=-load_pressure),\n",
    "        PrescribedPorePressure(physics=model, boundary=sides.surface, value=0.0),\n",
    "        PoreFluidFlux(physics=model, boundary=sides.equator, flux=0.0),\n",
    "    ),\n",
    "    initial_conditions=(InitialValue(model.fluid_content, 0.0),),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(\n",
    "        element=Lagrange(2), boundary_enforcement=Nitsche(penalty=16)\n",
    "    ),\n",
    "    linear_solver=SparseDirect(),\n",
    "    time_integrator=BDF(order=2, startup=BackwardEuler()),\n",
    "    nonlinear_solver=Newton(\n",
    "        linear_solver=SparseDirect(),\n",
    "        jacobian=\"analytic\",\n",
    "        relative_tolerance=1e-6,\n",
    "        absolute_tolerance=1e-10,\n",
    "    ),\n",
    ")\n",
    "pressures = [\n",
    "    Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "    .run(\n",
    "        start_time=0.0,\n",
    "        end_time=0.3 * consolidation_time,\n",
    "        time_step=0.002 * consolidation_time,\n",
    "    )\n",
    "    .field(model.pore_pressure)\n",
    "    for mesh in meshes\n",
    "]\n",
    "pressure = pressures[-1]\n",
    "histories = [\n",
    "    np.ravel(field.time_series([[0.0, 0.0]])[1]) / undrained for field in pressures\n",
    "]\n",
    "time = pressure.times / consolidation_time"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reference: Cryer's series\n",
    "\n",
    "With $\\eta=4\\mu\\alpha\\beta/(3K)$ the roots $\\xi_n$ of\n",
    "$(1+\\eta)\\,\\xi^2\\sin\\xi=3\\eta\\,(\\sin\\xi-\\xi\\cos\\xi)$ give the pore pressure as a sum of\n",
    "decaying modes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def cryer(T, r=0.0, terms=400):\n",
    "    \"\"\"Pore pressure p / p0 of the exact solution at the radii r / a (rows) and the times T = c t / a² (columns).\"\"\"\n",
    "    eta = 2 / stiffness_ratio\n",
    "    equation = lambda xi: (1 + eta) * xi**2 * np.sin(xi) - 3 * eta * (\n",
    "        np.sin(xi) - xi * np.cos(xi)\n",
    "    )\n",
    "    grid = np.linspace(1e-6, (terms + 2) * np.pi, 200 * (terms + 2))\n",
    "    xi = np.array(\n",
    "        [\n",
    "            brentq(equation, grid[i], grid[i + 1], xtol=1e-15)\n",
    "            for i in np.flatnonzero(np.diff(np.sign(equation(grid))))[:terms]\n",
    "        ]\n",
    "    )\n",
    "    cot, g = 1 / np.tan(xi), (1 - xi / np.tan(xi)) / xi**2\n",
    "    slope = -3 * eta * ((xi / np.sin(xi) ** 2 - cot) / xi**2 - 2 * g / xi) / (-2 * xi)\n",
    "    amplitude = (1 + eta) / (-(xi**2) * slope)\n",
    "    rr = np.maximum(np.atleast_1d(r), 1e-12)[:, None]\n",
    "    return (amplitude * (1 - np.sin(xi * rr) / (rr * np.sin(xi)))) @ np.exp(\n",
    "        -np.outer(xi**2, np.atleast_1d(T))\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "The centre pressure over time on the three meshes, its peak, and the mesh study of the peak."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "exact_time = np.linspace(0.004, 0.3, 1481)\n",
    "exact_centre = cryer(exact_time)[0]\n",
    "peaks = [history.max() for history in histories]\n",
    "study = convergence(peaks, sizes)\n",
    "\n",
    "print(\n",
    "    f\"undrained pore pressure p0 = {1e3 * undrained:.2f} kPa, consolidation time a²/c = {consolidation_time:.2f} h\"\n",
    ")\n",
    "print(\n",
    "    f\"exact peak of the centre pressure: {exact_centre.max():.4f} p0 at T = {exact_time[exact_centre.argmax()]:.4f}\"\n",
    ")\n",
    "print(\n",
    "    \"cell size [m]   triangles   peak [p0]   deviation   time of the peak T   largest deviation for T >= 0.01 [p0]\"\n",
    ")\n",
    "for size, mesh, history, peak in zip(sizes, meshes, histories, peaks):\n",
    "    error = np.abs(history - cryer(np.maximum(time, 1e-9))[0])[time >= 0.01].max()\n",
    "    print(\n",
    "        f\"{size:13.2f} {mesh.cell_count:12d} {peak:11.4f} {100 * (peak / exact_centre.max() - 1):+10.2f} % {time[history.argmax()]:20.3f} {error:14.4f}\"\n",
    "    )\n",
    "print(f\"change of the peak between the two finest meshes {100 * study.change:.2f} %\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The pore pressure in the meridian plane shortly after loading and at the peak, the centre\n",
    "pressure over time, and radial profiles along the 45° ray of the meridian plane at three times."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "over_undrained = lambda p, position: p / undrained\n",
    "shown = {\n",
    "    T: float(pressure.times[np.argmin(np.abs(time - T))]) for T in (0.006, 0.064, 0.25)\n",
    "}\n",
    "diagonal = np.linspace(0.0, 0.999 * radius, 25)[:, None] * np.ones(2) / np.sqrt(2)\n",
    "r = np.linspace(0.0, 1.0, 200)\n",
    "fig = plots.figure(2, 2, size=(14, 11))\n",
    "for panel, T in zip((fig[0], fig[1]), (0.006, 0.064)):\n",
    "    plots.surface(\n",
    "        pressure,\n",
    "        time=shown[T],\n",
    "        component=over_undrained,\n",
    "        limits=(0.0, 1.6),\n",
    "        contours=8,\n",
    "        subdivisions=3,\n",
    "        xlabel=\"radius x [m]\",\n",
    "        ylabel=\"height z [m]\",\n",
    "        label=\"pore pressure p / p0\",\n",
    "        title=f\"Meridian plane at T = c t / a² = {T}\",\n",
    "        ax=panel,\n",
    "    )\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"simulation, {mesh.cell_count} triangles\": (time[1:], history[1:])\n",
    "        for mesh, history in zip(meshes, histories)\n",
    "    },\n",
    "    reference={\"exact series (Cryer)\": (exact_time, exact_centre)},\n",
    "    hlines={\"undrained pressure\": 1.0},\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"T = c t / a²\",\n",
    "    ylabel=\"centre pore pressure p / p0\",\n",
    "    title=\"Mandel-Cryer effect at the centre\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"T = {T}\": (\n",
    "            np.linalg.norm(diagonal, axis=1) / radius,\n",
    "            np.ravel(pressure.evaluate(diagonal, time=t)) / undrained,\n",
    "        )\n",
    "        for T, t in shown.items()\n",
    "    },\n",
    "    reference={\n",
    "        f\"T = {T}\": (r, cryer(t / consolidation_time, r)[:, 0])\n",
    "        for T, t in shown.items()\n",
    "    },\n",
    "    xlabel=\"r / a\",\n",
    "    ylabel=\"pore pressure p / p0\",\n",
    "    title=\"Radial profiles: simulation (markers), exact (dashed)\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise Poisson's ratio to see the overshoot shrink (Cryer's solution gives about 1.31 $p_0$ for\n",
    "$\\nu=0.25$); make the constituents more compressible to weaken the effect; or change the radius\n",
    "in `mandel_cryer_consolidation_geometry.py`, write the STEP file again and see the consolidation\n",
    "time grow with $a^2$."
   ]
  }
 ]
}
