{
 "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": [
    "# Isotropic compression of clay with the Modified Cam-Clay model\n",
    "\n",
    "Clay compresses along two straight lines in a plot of void ratio $e$ against $\\ln p'$, the\n",
    "logarithm of the mean effective stress: the steep *normal compression line* when the clay is\n",
    "loaded beyond any stress it has felt before, and the flatter *swelling line* when it is unloaded\n",
    "or reloaded below that stress. The largest past stress, the preconsolidation pressure $p_c$,\n",
    "separates the two. The Modified Cam-Clay model of Roscoe and Burland (1968) builds on exactly\n",
    "this behaviour:\n",
    "\n",
    "$$\\mathrm de=-\\lambda\\,\\mathrm d\\ln p'\\ \\text{(normal compression)},\\qquad\n",
    "  \\mathrm de=-\\kappa\\,\\mathrm d\\ln p'\\ \\text{(swelling)},\\qquad\n",
    "  f=\\frac{q^2}{M^2}+p'(p'-p_c)\\le0 ,$$\n",
    "\n",
    "where plastic volume change moves the preconsolidation pressure along the normal compression line,\n",
    "and the elastic shear modulus follows from the current bulk modulus $K=(1+e_0)p'/\\kappa$ and a\n",
    "constant Poisson ratio.\n",
    "\n",
    "**Setup.** A cylindrical sample of 38 mm diameter and 76 mm height with $\\lambda=0.25$,\n",
    "$\\kappa=0.05$, $M=1.0$, $\\nu=0.3$ and initial void ratio $e_0=1.2$. It starts at $p'_0=100$ kPa\n",
    "with a preconsolidation pressure of 150 kPa (overconsolidation ratio 1.5). The cell pressure rises\n",
    "to 400 kPa, falls back to 100 kPa and rises again to 800 kPa. The sample comes from the CAD file\n",
    "`isotropic_compression_cam_clay.step`, written by `isotropic_compression_cam_clay_geometry.py` with\n",
    "the CAD objects of OneSimulation; the computation uses its meridian section.\n",
    "\n",
    "| edge of the section | condition |\n",
    "|---|---|\n",
    "| `mantle` | cell pressure $\\sigma_c(t)$ |\n",
    "| `top` | cell pressure $\\sigma_c(t)$ |\n",
    "| `bottom` | axial displacement 0 |\n",
    "| axis | symmetry |\n",
    "\n",
    "**Reference.** Under isotropic stress the sample deforms uniformly. Starting from $e_0$ the void\n",
    "ratio follows the swelling line up to $p_c$, then the normal compression line; unloading and\n",
    "reloading below the largest past pressure return along a swelling line, and loading beyond it\n",
    "continues the normal compression line (Wood, *Soil Behaviour and Critical State Soil Mechanics*,\n",
    "Cambridge 1990, Ch. 4):\n",
    "\n",
    "$$e(p')=e_0-\\kappa\\ln\\frac{p'}{p'_0}-(\\lambda-\\kappa)\\ln\\frac{\\max(p_c,\\ p'_{\\max})}{p_{c,0}} .$$"
   ]
  },
  {
   "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,\n",
    "whose $x$ coordinate is the radius. Quadratic triangles of 8 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sample = load(\"isotropic_compression_cam_clay.step\")\n",
    "faces = sample.boundaries\n",
    "meridian = sample.section((0, 1, 0), origin=(0, 0, 0))\n",
    "edges = meridian.boundaries\n",
    "mesh = TriangularMesher(target_size=0.008).generate(meridian)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(12, 6.5))\n",
    "plots.geometry(\n",
    "    sample,\n",
    "    selection={\"cell pressure\": faces.mantle | faces.top, \"pedestal\": faces.bottom},\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",
    "`SmallStrainSolid` with axisymmetric kinematics carries a `ModifiedCamClay` material point; the\n",
    "stresses are effective stresses (drained test). The material starts from its initial effective\n",
    "stress, so the first load step applies the same 100 kPa as boundary pressure. The cell pressure\n",
    "path is followed in 41 steps."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "compression, swelling, initial_void, start, cap = 0.25, 0.05, 1.2, 100e3, 150e3\n",
    "clay = ModifiedCamClay(\n",
    "    compression_index=compression,\n",
    "    swelling_index=swelling,\n",
    "    critical_slope=1.0,\n",
    "    poisson_ratio=0.3,\n",
    "    initial_void_ratio=initial_void,\n",
    "    preconsolidation_pressure=cap,\n",
    "    initial_pressure=start,\n",
    ")\n",
    "cell = np.r_[\n",
    "    np.geomspace(100e3, 400e3, 15),\n",
    "    np.geomspace(400e3, 100e3, 11)[1:],\n",
    "    np.geomspace(100e3, 800e3, 16)[1:],\n",
    "]\n",
    "pressure_at = lambda x, y, t: cell[int(round(t))]\n",
    "result = SmallStrainSolid(\n",
    "    youngs_modulus=1.0,\n",
    "    poisson_ratio=0.3,\n",
    "    kinematics=\"axisymmetric\",\n",
    "    material_point=clay,\n",
    ").solve(\n",
    "    mesh=mesh,\n",
    "    times=np.arange(len(cell), dtype=float),\n",
    "    order=2,\n",
    "    displacements=((edges.bottom, \"z\", 0.0),),\n",
    "    tractions=(\n",
    "        (edges.mantle, lambda x, y, t: (-pressure_at(x, y, t), 0.0)),\n",
    "        (edges.top, lambda x, y, t: (0.0, -pressure_at(x, y, t))),\n",
    "    ),\n",
    "    nonlinear=DampedNewton(\n",
    "        linear_solver=SparseDirect(),\n",
    "        relative_tolerance=1e-10,\n",
    "        absolute_tolerance=1e-8,\n",
    "        maximum_iterations=40,\n",
    "    ),\n",
    ")\n",
    "states = [step[0][0] for step in result.material_history]\n",
    "mean = np.array([state.mean_pressure for state in states])\n",
    "void = initial_void - (1 + initial_void) * np.array(\n",
    "    [-sum(state.strain[:3]) for state in states]\n",
    ")\n",
    "spread = max(\n",
    "    np.ptp([point.mean_pressure for cell_points in step for point in cell_points])\n",
    "    for step in result.material_history\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the compression lines\n",
    "\n",
    "The void ratio at every step against the closed form, the preconsolidation pressure carried by the\n",
    "material, and the slopes of the computed curve on the three branches."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "reference = (\n",
    "    lambda p, largest: initial_void\n",
    "    - swelling * np.log(p / start)\n",
    "    - (compression - swelling) * np.log(np.maximum(cap, largest) / cap)\n",
    ")\n",
    "largest = np.maximum.accumulate(cell)\n",
    "slope = lambda i, j: -(void[j] - void[i]) / np.log(mean[j] / mean[i])\n",
    "print(\n",
    "    f\"mean effective stress follows the cell pressure within {np.abs(mean / cell - 1).max():.1e}; spread over the sample {spread:.1e} Pa\"\n",
    ")\n",
    "print(\n",
    "    f\"largest deviation of the void ratio from the compression lines: {np.abs(void - reference(cell, largest)).max():.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"preconsolidation pressure after loading to 400 kPa: {states[14].preconsolidation_pressure / 1e3:.2f} kPa, after unloading \"\n",
    "    f\"{states[24].preconsolidation_pressure / 1e3:.2f} kPa, at the end {states[-1].preconsolidation_pressure / 1e3:.2f} kPa (largest cell pressure 800 kPa)\"\n",
    ")\n",
    "print(\n",
    "    f\"slopes of e over ln p': first loading above p_c {slope(10, 14):.4f} (λ = {compression}), unloading {slope(14, 24):.4f} (κ = {swelling}), \"\n",
    "    f\"reloading below 400 kPa {slope(24, 30):.4f}, beyond 400 kPa {slope(36, len(cell) - 1):.4f}\"\n",
    ")\n",
    "print(\n",
    "    f\"void ratio: start {void[0]:.4f}, at 400 kPa {void[14]:.4f}, after unloading {void[24]:.4f}, at 800 kPa {void[-1]:.4f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left the computed path in the $e$–$\\ln p'$ plane with the normal compression line and the swelling\n",
    "lines through the start and through 400 kPa; right the preconsolidation pressure and the cell\n",
    "pressure over the load steps."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "line = np.geomspace(80e3, 900e3, 200)\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.line(\n",
    "    points={\"simulation\": (mean / 1e3, void)},\n",
    "    reference={\n",
    "        \"normal compression line\": (line / 1e3, reference(line, line)),\n",
    "        \"swelling line through the start\": (\n",
    "            line / 1e3,\n",
    "            reference(line, np.full_like(line, cap)),\n",
    "        ),\n",
    "        \"swelling line through 400 kPa\": (\n",
    "            line / 1e3,\n",
    "            reference(line, np.full_like(line, 400e3)),\n",
    "        ),\n",
    "    },\n",
    "    scale=\"logx\",\n",
    "    ylimits=(0.65, 1.25),\n",
    "    xlabel=\"mean effective stress p' [kPa]\",\n",
    "    ylabel=\"void ratio e\",\n",
    "    title=\"Isotropic compression, unloading and reloading\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"preconsolidation pressure p_c\": (\n",
    "            np.arange(len(cell)),\n",
    "            np.array([state.preconsolidation_pressure for state in states]) / 1e3,\n",
    "        ),\n",
    "        \"cell pressure\": (np.arange(len(cell)), cell / 1e3),\n",
    "    },\n",
    "    xlabel=\"load step\",\n",
    "    ylabel=\"pressure [kPa]\",\n",
    "    title=\"Hardening only beyond the past maximum\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Start from a much higher preconsolidation pressure to model a heavily overconsolidated clay, or\n",
    "shear the sample after the isotropic stage: the triaxial and oedometer tests of the companion\n",
    "example use the same material."
   ]
  }
 ]
}
