{
 "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 and oedometer tests with Modified Cam-Clay\n",
    "\n",
    "In a drained triaxial test the cell pressure stays constant while the sample is shortened, so the\n",
    "effective stress path rises with slope 3 in the $p'$–$q$ plane, $q=3(p'-p'_0)$. Where it meets the\n",
    "Modified Cam-Clay yield ellipse\n",
    "\n",
    "$$f=\\frac{q^2}{M^2}+p'(p'-p_c)=0$$\n",
    "\n",
    "depends on the stress history. A normally consolidated clay ($p_c=p'_0$) yields at once, hardens and\n",
    "contracts until it reaches the critical state $q=Mp'$. A heavily overconsolidated clay meets the\n",
    "ellipse on its \"dry\" side above the critical state line: it peaks, dilates, softens and falls back\n",
    "along the same stress path to the critical state. In the oedometer the sample cannot expand\n",
    "sideways; it compresses one-dimensionally along a normal compression line of the same slope\n",
    "$\\lambda$ in the $e$–$\\ln p'$ plane.\n",
    "\n",
    "**Setup.** A cylindrical sample of 38 mm diameter and 76 mm height, $\\lambda=0.25$, $\\kappa=0.05$,\n",
    "$M=1.0$, $\\nu=0.3$, $e_0=1.2$, all starting at $p'_0=100$ kPa. Triaxial tests: $p_c=100$ kPa\n",
    "(normally consolidated) and $p_c=600$ kPa (overconsolidation ratio 6), sheared to 40 % and 8 % axial strain.\n",
    "Oedometer: $p_c=100$ kPa, compressed to 30 % axial strain and unloaded to 28.5 %. The sample comes\n",
    "from the CAD file `triaxial_oedometer_cam_clay.step`, written by\n",
    "`triaxial_oedometer_cam_clay_geometry.py` with the CAD objects of OneSimulation; the computation\n",
    "uses its meridian section.\n",
    "\n",
    "| edge of the section | triaxial | oedometer |\n",
    "|---|---|---|\n",
    "| `mantle` | cell pressure 100 kPa | radial displacement 0 |\n",
    "| `top` | axial displacement | axial displacement |\n",
    "| `bottom` | axial displacement 0 | axial displacement 0 |\n",
    "\n",
    "**Reference.** (1) Stress path $q=3(p'-p'_0)$. (2) Critical state of the drained test:\n",
    "$p'_f=3p'_0/(3-M)=150$ kPa, $q_f=Mp'_f$. (3) Peak of the overconsolidated sample where the path meets\n",
    "the initial ellipse: $(9/M^2+1)p'^2-(18p'_0+p_c)p'+9p'^2_0=0$, larger root. (4) State of the clay:\n",
    "with plastic volume change only through the cap and elastic change along the swelling line, the\n",
    "void ratio at any yielding state is $e=e_0-(\\lambda-\\kappa)\\ln(p_c/p_{c,0})-\\kappa\\ln(p'/p'_0)$ with\n",
    "$p_c=p'(1+\\eta^2/M^2)$, $\\eta=q/p'$ (Wood, *Soil Behaviour and Critical State Soil Mechanics*,\n",
    "Cambridge 1990, Ch. 6-7)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials.solids import ModifiedCamClay\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import DampedNewton\n",
    "from onesim.physics.solid_mechanics import SmallStrainSolid\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 sector of the sample with its named faces; `section` cuts the meridian plane."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sample = load(\"triaxial_oedometer_cam_clay.step\")\n",
    "faces = sample.boundaries\n",
    "meridian = sample.section((0, 1, 0), origin=(0, 0, 0))\n",
    "edges = meridian.boundaries\n",
    "height = sample.size[2]\n",
    "mesh = TriangularMesher(target_size=0.08).generate(meridian)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(12, 6.5))\n",
    "plots.geometry(\n",
    "    sample,\n",
    "    selection={\n",
    "        \"mantle\": faces.mantle,\n",
    "        \"top platen\": faces.top,\n",
    "        \"pedestal\": faces.bottom,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=25, azimuth=-60),\n",
    "    title=\"Sector of the soil sample\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian section: {mesh.cell_count} quadratic triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Three runs of `SmallStrainSolid` with axisymmetric kinematics and a `ModifiedCamClay` material\n",
    "point, driven by the top platen. Axial strain grows in logarithmic steps; the oedometer is\n",
    "unloaded afterwards."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "compression, swelling, slope, initial_void, start = 0.25, 0.05, 1.0, 1.2, 100e3\n",
    "clay = lambda cap: ModifiedCamClay(\n",
    "    compression_index=compression,\n",
    "    swelling_index=swelling,\n",
    "    critical_slope=slope,\n",
    "    poisson_ratio=0.3,\n",
    "    initial_void_ratio=initial_void,\n",
    "    preconsolidation_pressure=cap,\n",
    "    initial_pressure=start,\n",
    ")\n",
    "newton = DampedNewton(\n",
    "    linear_solver=SparseDirect(),\n",
    "    relative_tolerance=1e-7,\n",
    "    absolute_tolerance=1e-5,\n",
    "    maximum_iterations=40,\n",
    ")\n",
    "shear = {\n",
    "    \"triaxial, OCR 1\": np.r_[0.0, np.geomspace(2e-4, 0.4, 40)],\n",
    "    \"triaxial, OCR 6\": np.r_[0.0, np.geomspace(2e-4, 0.08, 36)],\n",
    "}\n",
    "oedometer = np.r_[0.0, np.geomspace(2e-4, 0.3, 30), np.linspace(0.297, 0.285, 5)]\n",
    "platen = lambda path: (lambda x, y, t: -height * path[int(round(t))])\n",
    "tests = {\n",
    "    \"triaxial, OCR 1\": (100e3, shear[\"triaxial, OCR 1\"], (edges.mantle, (-start, 0.0))),\n",
    "    \"triaxial, OCR 6\": (600e3, shear[\"triaxial, OCR 6\"], (edges.mantle, (-start, 0.0))),\n",
    "    \"oedometer\": (100e3, oedometer, None),\n",
    "}\n",
    "results = {\n",
    "    name: SmallStrainSolid(\n",
    "        youngs_modulus=1.0,\n",
    "        poisson_ratio=0.3,\n",
    "        kinematics=\"axisymmetric\",\n",
    "        material_point=clay(cap),\n",
    "    ).solve(\n",
    "        mesh=mesh,\n",
    "        times=np.arange(len(path), dtype=float),\n",
    "        order=2,\n",
    "        nonlinear=newton,\n",
    "        displacements=((edges.bottom, \"z\", 0.0), (edges.top, \"z\", platen(path)))\n",
    "        + (((edges.mantle, \"r\", 0.0),) if cell is None else ()),\n",
    "        tractions=() if cell is None else (cell,),\n",
    "    )\n",
    "    for name, (cap, path, cell) in tests.items()\n",
    "}\n",
    "states = {\n",
    "    name: [step[0][0] for step in result.material_history]\n",
    "    for name, result in results.items()\n",
    "}\n",
    "p = {\n",
    "    name: np.array([state.mean_pressure for state in history])\n",
    "    for name, history in states.items()\n",
    "}\n",
    "q = {\n",
    "    name: np.array([state.deviatoric_stress for state in history])\n",
    "    for name, history in states.items()\n",
    "}\n",
    "void = {\n",
    "    name: initial_void\n",
    "    - (1 + initial_void) * np.array([-sum(state.strain[:3]) for state in history])\n",
    "    for name, history in states.items()\n",
    "}\n",
    "caps = {\n",
    "    name: np.array([state.preconsolidation_pressure for state in history])\n",
    "    for name, history in states.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed forms\n",
    "\n",
    "Stress path, peak and critical state of the triaxial tests, the state relation in every yielding\n",
    "step of all three tests, and the slopes and lateral stress ratio of the oedometer. The normally\n",
    "consolidated sample approaches the critical state asymptotically. The overconsolidated sample\n",
    "softens after its peak; the softening does not stay uniform in the sample (the strain starts to\n",
    "localise), so beyond the peak the closed forms for a uniform sample only describe the state\n",
    "relation, not the stress path."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "failure = 3 * start / (3 - slope)\n",
    "peak = (\n",
    "    (18 * start + 600e3)\n",
    "    + np.sqrt((18 * start + 600e3) ** 2 - 4 * (9 / slope**2 + 1) * 9 * start**2)\n",
    ") / (2 * (9 / slope**2 + 1))\n",
    "state_line = (\n",
    "    lambda name: initial_void\n",
    "    - (compression - swelling) * np.log(caps[name] / caps[name][0])\n",
    "    - swelling * np.log(p[name] / start)\n",
    ")\n",
    "for name in (\"triaxial, OCR 1\", \"triaxial, OCR 6\"):\n",
    "    print(\n",
    "        f\"{name}: stress path off q = 3(p' - p'_0) by at most {np.abs(q[name] - 3 * (p[name] - start)).max():.2e} Pa; at {100 * shear[name][-1]:.0f} % axial strain \"\n",
    "        f\"p' = {p[name][-1] / 1e3:.2f} kPa, q/p' = {q[name][-1] / p[name][-1]:.4f} (critical state: {failure / 1e3:.0f} kPa, M = {slope})\"\n",
    "    )\n",
    "print(\n",
    "    f\"peak of the overconsolidated sample: q = {q['triaxial, OCR 6'].max() / 1e3:.1f} kPa at p' = {p['triaxial, OCR 6'][np.argmax(q['triaxial, OCR 6'])] / 1e3:.1f} kPa \"\n",
    "    f\"(closed form q = {3 * (peak - start) / 1e3:.1f} kPa at p' = {peak / 1e3:.1f} kPa)\"\n",
    ")\n",
    "for name in tests:\n",
    "    yielding = np.r_[False, np.abs(np.diff(caps[name])) > 1e-9 * caps[name][0]]\n",
    "    pressure_cap = p[name] * (1 + (q[name] / p[name]) ** 2 / slope**2)\n",
    "    print(\n",
    "        f\"{name}: state relation e(p', p_c) holds within {np.abs(void[name] - state_line(name)).max():.1e}; \"\n",
    "        f\"p_c on the yield ellipse within {np.abs(caps[name][yielding] / pressure_cap[yielding] - 1).max() if yielding.any() else 0:.1e}\"\n",
    "    )\n",
    "oed = \"oedometer\"\n",
    "radial = np.array([-state.stress[0] for state in states[oed]])\n",
    "axial = np.array([-state.stress[1] for state in states[oed]])\n",
    "top = int(np.argmax(oedometer))\n",
    "print(\n",
    "    f\"oedometer: slope of e over ln p' in the last loading steps {-(void[oed][top] - void[oed][top - 5]) / np.log(p[oed][top] / p[oed][top - 5]):.4f} (λ = {compression}), \"\n",
    "    f\"on unloading {-(void[oed][-1] - void[oed][top]) / np.log(p[oed][-1] / p[oed][top]):.4f} (κ = {swelling})\"\n",
    ")\n",
    "print(\n",
    "    f\"oedometer: lateral stress ratio K0 = σ'_r/σ'_a = {radial[top] / axial[top]:.3f} in normal compression \"\n",
    "    f\"(Jaky's estimate 1 - sin φ' = {1 - 3 * slope / (6 + slope):.3f} with sin φ' = 3M/(6+M)), {radial[-1] / axial[-1]:.3f} after unloading\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left the stress paths of all three tests with the critical state line and the initial yield\n",
    "ellipses; middle the deviator stress against the axial strain of the triaxial tests; right the\n",
    "compression curves in the $e$–$\\ln p'$ plane with the normal compression and critical state lines.\n",
    "The normally consolidated clay contracts and hardens towards the critical state; the\n",
    "overconsolidated clay peaks on the dry side of its yield surface and softens."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "ellipse = lambda cap: (\n",
    "    lambda pressure: slope * np.sqrt(np.maximum(pressure * (cap - pressure), 0.0))\n",
    ")\n",
    "pressures = np.linspace(0.0, 620e3, 400)\n",
    "line = np.geomspace(60e3, 3e6, 200)\n",
    "normal = lambda pressure: initial_void - compression * np.log(pressure / start)\n",
    "fig = plots.figure(1, 3, size=(20, 6))\n",
    "plots.line(\n",
    "    points={name: (p[name] / 1e3, q[name] / 1e3) for name in tests},\n",
    "    reference={\n",
    "        \"critical state line\": (pressures / 1e3, slope * pressures / 1e3),\n",
    "        \"initial yield surface, p_c = 100 kPa\": (\n",
    "            pressures / 1e3,\n",
    "            ellipse(100e3)(pressures) / 1e3,\n",
    "        ),\n",
    "        \"initial yield surface, p_c = 600 kPa\": (\n",
    "            pressures / 1e3,\n",
    "            ellipse(600e3)(pressures) / 1e3,\n",
    "        ),\n",
    "    },\n",
    "    xlimits=(0, 620),\n",
    "    ylimits=(0, 400),\n",
    "    xlabel=\"p' [kPa]\",\n",
    "    ylabel=\"q [kPa]\",\n",
    "    title=\"Effective stress paths\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        name: (100 * shear[name], q[name] / 1e3)\n",
    "        for name in (\"triaxial, OCR 1\", \"triaxial, OCR 6\")\n",
    "    },\n",
    "    hlines={\n",
    "        \"critical state\": slope * failure / 1e3,\n",
    "        \"peak, closed form\": 3 * (peak - start) / 1e3,\n",
    "    },\n",
    "    xlabel=\"axial strain [%]\",\n",
    "    ylabel=\"deviator stress q [kPa]\",\n",
    "    title=\"Drained triaxial compression\",\n",
    "    legend=\"right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    points={name: (p[name] / 1e3, void[name]) for name in tests},\n",
    "    reference={\n",
    "        \"normal compression line\": (line / 1e3, normal(line)),\n",
    "        \"critical state line\": (\n",
    "            line / 1e3,\n",
    "            normal(line) - (compression - swelling) * np.log(2),\n",
    "        ),\n",
    "    },\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"p' [kPa]\",\n",
    "    ylabel=\"void ratio e\",\n",
    "    title=\"Compression curves\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Run the tests undrained by coupling the clay to pore-water pressure, vary the overconsolidation\n",
    "ratio to find where contraction turns into dilation, or replace the oedometer ring by a soft\n",
    "lateral support."
   ]
  }
 ]
}
