{
 "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": [
    "# Bearing capacity of a strip footing on clay\n",
    "\n",
    "How much load can a shallow foundation carry before the soil under it fails? For a long\n",
    "(strip) footing on saturated clay loaded quickly, the clay behaves undrained: it deforms at\n",
    "constant volume and fails when the shear stress reaches the undrained shear strength $s_u$.\n",
    "Prandtl's solution of 1920 for a rigid-plastic half-space gives the collapse pressure of a\n",
    "smooth footing\n",
    "\n",
    "$$q_f=(2+\\pi)\\,s_u\\approx5.14\\,s_u ,$$\n",
    "\n",
    "independent of the footing width and of the stiffness of the soil (L. Prandtl, Z. Angew. Math.\n",
    "Mech. 1, 1921, 15-20; e.g. D.M. Potts and L. Zdravković, *Finite Element Analysis in\n",
    "Geotechnical Engineering: Application*, Telford 2001, where this case is a standard benchmark).\n",
    "\n",
    "**Model.** The clay is elastic-perfectly plastic with the Drucker-Prager criterion at zero\n",
    "friction angle, which is the von Mises criterion; in plane strain its cohesion\n",
    "$c=\\tfrac{\\sqrt3}{2}s_u$ gives the shear strength $s_u$.\n",
    "\n",
    "**Setup.** A footing of width $B=1$ m on a clay stratum 3 m deep; one half is modelled, 5 m\n",
    "wide. $E=10$ MPa, $\\nu=0.3$, $s_u=50$ kPa. The footing is smooth and is pushed down by 0.15 m.\n",
    "The stratum comes from the CAD file `strip_footing_bearing_capacity.step`, written by\n",
    "`strip_footing_bearing_capacity_geometry.py` with the CAD objects of OneSimulation; the soil under\n",
    "the footing is its own block, so the ground surface is split at the edge of the footing.\n",
    "\n",
    "| side | condition |\n",
    "|---|---|\n",
    "| `footing.y_max` (under the footing) | $u_y=-\\delta$, smooth |\n",
    "| `soil.y_max` (ground surface) | free |\n",
    "| `footing.x_min` (symmetry), `soil.x_max` | $u_x=0$ |\n",
    "| `footing.y_min`, `soil.y_min` (rigid base) | $u_y=0$, smooth |\n",
    "\n",
    "**Reference.** Prandtl's collapse pressure $(2+\\pi)\\,s_u=257.1$ kPa."
   ]
  },
  {
   "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.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import DampedNewton\n",
    "from onesim.physics.geotechnics import DruckerPragerSoil, FrictionalSolid\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 stratum at mid-thickness; the cut faces keep their names. The triangles are\n",
    "graded towards the edge of the footing, where the stresses change fastest: three meshes with\n",
    "6, 3 and 1.5 cm at the edge."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "stratum = load(\"strip_footing_bearing_capacity.step\")\n",
    "plane = stratum.section((0, 0, 1), origin=(0, 0, stratum.size[2] / 2))\n",
    "faces = plane.boundaries\n",
    "edge_sizes = [0.06, 0.03, 0.015]\n",
    "meshes = [\n",
    "    TriangularMesher(\n",
    "        target_size=0.3,\n",
    "        size_field=lambda p, h=h: np.minimum(\n",
    "            h + 0.15 * np.hypot(p[:, 0] - 0.5, p[:, 1]), 0.3\n",
    "        ),\n",
    "    ).generate(plane)\n",
    "    for h in edge_sizes\n",
    "]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(15, 5))\n",
    "plots.geometry(\n",
    "    plane,\n",
    "    selection={\n",
    "        \"footing\": faces[\"footing.y_max\"],\n",
    "        \"ground surface\": faces[\"soil.y_max\"],\n",
    "        \"rollers\": faces[\"footing.x_min\"]\n",
    "        | faces[\"soil.x_max\"]\n",
    "        | faces[\"footing.y_min\"]\n",
    "        | faces[\"soil.y_min\"],\n",
    "    },\n",
    "    labels=False,\n",
    "    title=\"Half section of the clay stratum\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[-1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Finer 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",
    "Plane strain with quadratic triangles; the footing goes down in twelve steps to 0.15 m."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "undrained_strength = 50e3\n",
    "clay = FrictionalSolid(\n",
    "    material=DruckerPragerSoil(\n",
    "        youngs_modulus=10e6,\n",
    "        poisson_ratio=0.3,\n",
    "        cohesion=np.sqrt(3) / 2 * undrained_strength,\n",
    "        friction_angle=0.0,\n",
    "    ),\n",
    "    kinematics=\"plane_strain\",\n",
    ")\n",
    "settlement = np.r_[np.arange(0.0, 0.06, 0.01), np.arange(0.06, 0.151, 0.015)]\n",
    "results = [\n",
    "    clay.solve(\n",
    "        mesh=mesh,\n",
    "        times=settlement,\n",
    "        spatial=FiniteElement(element=Lagrange(2)),\n",
    "        nonlinear=DampedNewton(\n",
    "            relative_tolerance=1e-8,\n",
    "            absolute_tolerance=1e-6,\n",
    "            maximum_iterations=60,\n",
    "            linear_solver=SparseDirect(),\n",
    "        ),\n",
    "        displacements=(\n",
    "            (faces[\"footing.x_min\"], \"x\", 0.0),\n",
    "            (faces[\"soil.x_max\"], \"x\", 0.0),\n",
    "            (faces[\"footing.y_min\"] | faces[\"soil.y_min\"], \"y\", 0.0),\n",
    "            (faces[\"footing.y_max\"], \"y\", lambda t: -t),\n",
    "        ),\n",
    "    )\n",
    "    for mesh in meshes\n",
    "]\n",
    "pressure = [\n",
    "    -result.reactions[\n",
    "        :,\n",
    "        (result.coordinates[:, 0] <= 0.5 + 1e-9)\n",
    "        & (np.abs(result.coordinates[:, 1]) < 1e-9),\n",
    "        1,\n",
    "    ].sum(axis=1)\n",
    "    / 0.5\n",
    "    for result in results\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "The mean footing pressure at the largest settlement against Prandtl's value, and its last\n",
    "increase, which shows how close the soil is to collapse."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "prandtl = (2 + np.pi) * undrained_strength\n",
    "print(f\"Prandtl: q_f = (2 + π) s_u = {prandtl / 1e3:.1f} kPa\")\n",
    "print(\n",
    "    f\"{'size at the edge':>16s} {'triangles':>9s} {'q at δ = 0.15 m [kPa]':>22s} {'q / s_u':>8s} {'deviation':>10s} {'increase over the last step':>28s}\"\n",
    ")\n",
    "for size, mesh, values in zip(edge_sizes, meshes, pressure):\n",
    "    print(\n",
    "        f\"{100 * size:13.1f} cm {mesh.cell_count:9d} {values[-1] / 1e3:22.1f} {values[-1] / undrained_strength:8.3f}\"\n",
    "        f\" {100 * (values[-1] / prandtl - 1):+9.1f} % {100 * (values[-1] / values[-2] - 1):27.2f} %\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Load-settlement curves of the three meshes with Prandtl's value, and how far the soil moves in the\n",
    "last step per unit footing movement: near collapse this outlines the failure mechanism, the\n",
    "rigid wedge under the footing, the fan and the passive wedge beside it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "result, mesh = results[-1], meshes[-1]\n",
    "nodes = len(mesh.coordinates)\n",
    "increment = np.hypot(\n",
    "    *(result.displacement[-1, :nodes] - result.displacement[-2, :nodes]).T\n",
    ")\n",
    "fig = plots.figure(1, 2, size=(16, 5.5))\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"{mesh.cell_count} triangles\": (100 * settlement, values / undrained_strength)\n",
    "        for mesh, values in zip(meshes, pressure)\n",
    "    },\n",
    "    hlines={\"Prandtl, 2 + π\": 2 + np.pi},\n",
    "    markers=True,\n",
    "    ylimits=(0, 6),\n",
    "    xlabel=\"settlement δ [cm]\",\n",
    "    ylabel=\"mean footing pressure q / s_u\",\n",
    "    title=\"Load-settlement curve\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.heatmap(\n",
    "    result.coordinates[:nodes, 0],\n",
    "    result.coordinates[:nodes, 1],\n",
    "    100 * increment / (settlement[-1] - settlement[-2]),\n",
    "    triangles=np.asarray(mesh.cells),\n",
    "    limits=(0, 100),\n",
    "    contours=10,\n",
    "    label=\"displacement increment / footing increment [%]\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    xlimits=(0, 2.5),\n",
    "    ylimits=(-1.5, 0),\n",
    "    title=\"Collapse mechanism in the last step\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Give the clay a friction angle and compare with the bearing capacity factor\n",
    "$N_c=(N_q-1)\\cot\\varphi$; make the footing rough by fixing $u_x$ under it; or move the base of\n",
    "the stratum up in `strip_footing_bearing_capacity_geometry.py` until the shallow layer raises\n",
    "the collapse load."
   ]
  }
 ]
}
