{
 "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": [
    "# Drained triaxial test on a soil sample\n",
    "\n",
    "The triaxial test is the most common laboratory test for the strength of soils. A cylindrical\n",
    "sample in a rubber membrane is first brought to a cell pressure $\\sigma_3$ and then compressed\n",
    "axially by a moving platen while the cell pressure is kept. The axial stress rises until the\n",
    "sample fails; repeating the test at several cell pressures gives the friction angle and the\n",
    "cohesion of the soil.\n",
    "\n",
    "The soil is modelled as an elastic-perfectly plastic **Mohr-Coulomb** material with the yield\n",
    "function and the plastic potential\n",
    "\n",
    "$$f=\\sigma_1-\\sigma_3+(\\sigma_1+\\sigma_3)\\sin\\varphi-2c\\cos\\varphi ,\\qquad\n",
    "  g=\\sigma_1-\\sigma_3+(\\sigma_1+\\sigma_3)\\sin\\psi$$\n",
    "\n",
    "(principal stresses, tension positive, $\\sigma_1\\ge\\sigma_2\\ge\\sigma_3$), friction angle\n",
    "$\\varphi$, cohesion $c$ and dilatancy angle $\\psi$.\n",
    "\n",
    "**Setup.** A sample of 38 mm diameter and 76 mm height, $E=20$ MPa, $\\nu=0.3$, $c=5$ kPa,\n",
    "$\\varphi=30°$, $\\psi=5°$; cell pressures 50, 100 and 200 kPa; axial compression to 5 % strain.\n",
    "The sample comes from the CAD file `triaxial_test_mohr_coulomb.step`, written by\n",
    "`triaxial_test_mohr_coulomb_geometry.py` with the CAD objects of OneSimulation; the model lives\n",
    "on its meridian, $r\\ge0$.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `axis.x_min` ($r=0$) | $u_r=0$ |\n",
    "| `bottom` | $u_z=0$ (smooth platen) |\n",
    "| `top` | $u_z$ prescribed (smooth platen) |\n",
    "| `outer_wall` (membrane) | normal stress $-\\sigma_3$ |\n",
    "\n",
    "**Reference.** For smooth platens the sample stays uniform, and the Mohr-Coulomb solution is\n",
    "closed-form (e.g. D.M. Wood, *Soil Behaviour and Critical State Soil Mechanics*, Cambridge 1990;\n",
    "D.M. Potts and L. Zdravković, *Finite Element Analysis in Geotechnical Engineering: Theory*,\n",
    "Telford 1999). The deviator rises elastically as $q=E\\,\\varepsilon_a$ with the volume change\n",
    "$(1-2\\nu)\\,\\varepsilon_a$, up to the failure deviator\n",
    "\n",
    "$$q_f=\\frac{2\\,(c\\cos\\varphi+\\sigma_3\\sin\\varphi)}{1-\\sin\\varphi} ;$$\n",
    "\n",
    "afterwards the sample flows at constant $q$ and dilates at the rate\n",
    "$-\\mathrm d\\varepsilon_v/\\mathrm d\\varepsilon_a=2\\sin\\psi/(1-\\sin\\psi)$ (volumetric strain counted positive in compression)."
   ]
  },
  {
   "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.physics.geotechnics import FrictionalSolid, MohrCoulombRock\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",
    "`load` returns the half sample, `section` its meridian in the plane $y=0$: the first planar\n",
    "coordinate is the radius, the second the height."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sample = load(\"triaxial_test_mohr_coulomb.step\")\n",
    "radius, _, height = sample.size\n",
    "meridian = sample.section((0, 1, 0))\n",
    "faces = meridian.boundaries\n",
    "mesh = TriangularMesher(target_size=0.006).generate(meridian)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(11, 6))\n",
    "plots.geometry(\n",
    "    sample,\n",
    "    selection={\n",
    "        \"platens\": sample.boundaries.top | sample.boundaries.bottom,\n",
    "        \"membrane\": sample.boundaries.outer_wall,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=22, azimuth=-60),\n",
    "    title=\"Half of the soil sample\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian: {mesh.cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The first step applies the cell pressure on all sides (the top platen moves by the elastic\n",
    "isotropic compression), then the top platen moves down in 20 steps to 5 % axial strain."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "youngs_modulus, poisson_ratio, cohesion, friction, dilatancy = (\n",
    "    20e6,\n",
    "    0.3,\n",
    "    5e3,\n",
    "    np.radians(30),\n",
    "    np.radians(5),\n",
    ")\n",
    "soil = FrictionalSolid(\n",
    "    material=MohrCoulombRock(\n",
    "        youngs_modulus=youngs_modulus,\n",
    "        poisson_ratio=poisson_ratio,\n",
    "        cohesion=cohesion,\n",
    "        friction_angle=friction,\n",
    "        dilation_angle=dilatancy,\n",
    "    ),\n",
    "    kinematics=\"axisymmetric\",\n",
    ")\n",
    "pressures = (50e3, 100e3, 200e3)\n",
    "compression = np.linspace(0.0, 0.05, 21)\n",
    "results = {\n",
    "    cell: soil.solve(\n",
    "        mesh=mesh,\n",
    "        times=compression * height,\n",
    "        normal_tractions=((faces.outer_wall, -cell),),\n",
    "        displacements=(\n",
    "            (faces[\"axis.x_min\"], \"r\", 0.0),\n",
    "            (faces.bottom, \"z\", 0.0),\n",
    "            (\n",
    "                faces.top,\n",
    "                \"z\",\n",
    "                (lambda start: lambda t: start - t)(\n",
    "                    -cell * (1 - 2 * poisson_ratio) / youngs_modulus * height\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "    )\n",
    "    for cell in pressures\n",
    "}\n",
    "top = np.isclose(results[pressures[0]].coordinates[:, 1], height)\n",
    "rim = np.isclose(results[pressures[0]].coordinates[:, 0], radius) & np.isclose(\n",
    "    results[pressures[0]].coordinates[:, 1], height\n",
    ")\n",
    "deviator = {\n",
    "    cell: -result.reactions[:, top, 1].sum(axis=1) / (np.pi * radius**2) - cell\n",
    "    for cell, result in results.items()\n",
    "}\n",
    "volume = {\n",
    "    cell: compression\n",
    "    - 2\n",
    "    * (result.displacement[:, rim, 0][:, 0] - result.displacement[0, rim, 0][0])\n",
    "    / radius\n",
    "    for cell, result in results.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "Failure deviator, elastic stiffness and dilatancy rate for the three cell pressures."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "failure = (\n",
    "    lambda cell: 2\n",
    "    * (cohesion * np.cos(friction) + cell * np.sin(friction))\n",
    "    / (1 - np.sin(friction))\n",
    ")\n",
    "rate = 2 * np.sin(dilatancy) / (1 - np.sin(dilatancy))\n",
    "print(\n",
    "    f\"{'cell pressure':>13s} {'q_f [kPa]':>10s} {'closed form':>12s} {'deviation':>10s} {'E from q-ε [MPa]':>17s}\"\n",
    "    f\" {'-dε_v/dε_a':>11s} {'closed form':>12s}\"\n",
    ")\n",
    "for cell in pressures:\n",
    "    q, v = deviator[cell], volume[cell]\n",
    "    print(\n",
    "        f\"{cell / 1e3:9.0f} kPa {q[-1] / 1e3:10.3f} {failure(cell) / 1e3:12.3f} {100 * (q[-1] / failure(cell) - 1):+9.1e} %\"\n",
    "        f\" {q[1] / compression[1] / 1e6:17.4f} {(v[-2] - v[-1]) / (compression[-1] - compression[-2]):11.4f} {rate:12.4f}\"\n",
    "    )\n",
    "print(\n",
    "    \"stress spread over the quadrature points at the end (uniform sample): \"\n",
    "    f\"{max(np.ptp(result.stress[-1, :, 1, 1]) for result in results.values()):.1e} Pa\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Deviator and volume change against axial strain with the closed-form curves, the stress paths\n",
    "in the $p$-$q$ plane with the failure line, and the Mohr circles at failure with the\n",
    "Mohr-Coulomb envelope $\\tau=c+\\sigma\\tan\\varphi$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "strain = np.linspace(0, 0.05, 401)\n",
    "angle = np.linspace(0, np.pi, 181)\n",
    "mean = np.linspace(0, 350e3, 50)\n",
    "slope = 6 * np.sin(friction) / (3 - np.sin(friction))\n",
    "fig = plots.figure(2, 2, size=(14, 11))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"σ3 = {cell / 1e3:.0f} kPa\": (100 * compression, deviator[cell] / 1e3)\n",
    "        for cell in pressures\n",
    "    },\n",
    "    reference={\n",
    "        f\"σ3 = {cell / 1e3:.0f} kPa\": (\n",
    "            100 * strain,\n",
    "            np.minimum(youngs_modulus * strain, failure(cell)) / 1e3,\n",
    "        )\n",
    "        for cell in pressures\n",
    "    },\n",
    "    xlabel=\"axial strain ε_a [%]\",\n",
    "    ylabel=\"deviator q = σ_a - σ3 [kPa]\",\n",
    "    title=\"Deviator: simulation (markers), closed form (dashed)\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"σ3 = {cell / 1e3:.0f} kPa\": (100 * compression, 100 * volume[cell])\n",
    "        for cell in pressures\n",
    "    },\n",
    "    reference={\n",
    "        f\"σ3 = {cell / 1e3:.0f} kPa\": (\n",
    "            100 * strain,\n",
    "            100\n",
    "            * np.where(\n",
    "                strain < failure(cell) / youngs_modulus,\n",
    "                (1 - 2 * poisson_ratio) * strain,\n",
    "                (1 - 2 * poisson_ratio) * failure(cell) / youngs_modulus\n",
    "                - rate * (strain - failure(cell) / youngs_modulus),\n",
    "            ),\n",
    "        )\n",
    "        for cell in pressures\n",
    "    },\n",
    "    xlabel=\"axial strain ε_a [%]\",\n",
    "    ylabel=\"volumetric strain ε_v [%] (compression positive)\",\n",
    "    title=\"Volume change: compression, then dilatancy\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"σ3 = {cell / 1e3:.0f} kPa\": (\n",
    "            (cell + deviator[cell] / 3) / 1e3,\n",
    "            deviator[cell] / 1e3,\n",
    "        )\n",
    "        for cell in pressures\n",
    "    },\n",
    "    reference={\n",
    "        \"failure line in compression\": (\n",
    "            mean / 1e3,\n",
    "            (slope * mean + 6 * cohesion * np.cos(friction) / (3 - np.sin(friction)))\n",
    "            / 1e3,\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"mean stress p [kPa]\",\n",
    "    ylabel=\"deviator q [kPa]\",\n",
    "    title=\"Stress paths\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"σ3 = {cell / 1e3:.0f} kPa\": (\n",
    "            (cell + deviator[cell][-1] / 2 * (1 + np.cos(angle))) / 1e3,\n",
    "            deviator[cell][-1] / 2 * np.sin(angle) / 1e3,\n",
    "        )\n",
    "        for cell in pressures\n",
    "    },\n",
    "    reference={\n",
    "        \"envelope τ = c + σ tan φ\": (\n",
    "            np.r_[0.0, 800.0],\n",
    "            (cohesion + np.r_[0.0, 800e3] * np.tan(friction)) / 1e3,\n",
    "        )\n",
    "    },\n",
    "    xlimits=(0, 720),\n",
    "    ylimits=(0, 540),\n",
    "    xlabel=\"normal stress σ [kPa] (compression positive)\",\n",
    "    ylabel=\"shear stress τ [kPa]\",\n",
    "    title=\"Mohr circles of the simulation at failure\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Set the dilatancy angle to zero to see the volume stay constant during flow, or equal to the\n",
    "friction angle (associated flow) to see the strong dilatancy that makes associated models stiff\n",
    "in confined problems. Replace `MohrCoulombRock` by `DruckerPragerSoil` with the same parameters:\n",
    "its compression cone gives the same failure deviator here, but a different dilatancy."
   ]
  }
 ]
}
