{
 "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": [
    "# Polynomial hyperelastic rubber in three load cases\n",
    "\n",
    "A hyperelastic material is defined completely by its strain energy density. For rubber the\n",
    "generalised Mooney-Rivlin form, a polynomial in the isochoric invariants $\\bar I_1,\\bar I_2$, is\n",
    "the most common choice:\n",
    "\n",
    "$$W=\\sum_{i+j\\ge1}c_{ij}\\,(\\bar I_1-3)^i(\\bar I_2-3)^j+\\frac K2(J-1)^2 .$$\n",
    "\n",
    "In OneSimulation such a material is declared by its list of terms $(i,j,c_{ij})$; stress and\n",
    "tangent follow from the energy. Here two models are compared:\n",
    "\n",
    "| model | $c_{10}$ | $c_{01}$ | $c_{20}$ | $c_{11}$ | $c_{02}$ |\n",
    "|---|---|---|---|---|---|\n",
    "| Mooney-Rivlin | 0.16 MPa | 0.01 MPa | | | |\n",
    "| five-term polynomial | 0.16 MPa | 0.01 MPa | 2 kPa | 0.5 kPa | 0.1 kPa |\n",
    "\n",
    "with a bulk modulus $K=10^4$ times the shear modulus, so the rubber is nearly incompressible.\n",
    "\n",
    "**Setup.** A cube of 20 mm side from the CAD file `polynomial_hyperelastic_block.step`, written\n",
    "by `polynomial_hyperelastic_block_geometry.py` with the CAD objects of OneSimulation. The faces\n",
    "`x_min`, `y_min`, `z_min` are smooth supports (rollers); the load cases move the opposite faces:\n",
    "\n",
    "| load case | `x_max` | `y_max` | `z_max` | stretches |\n",
    "|---|---|---|---|---|\n",
    "| uniaxial tension | $u_x=(\\lambda-1)L$ | free | free | 1 to 3 |\n",
    "| equibiaxial tension | $u_x=(\\lambda-1)L$ | $u_y=(\\lambda-1)L$ | free | 1 to 2 |\n",
    "| pure shear | $u_x=(\\lambda-1)L$ | $u_y=0$ | free | 1 to 2.5 |\n",
    "\n",
    "**Reference.** For the incompressible material with $W_1=\\partial W/\\partial\\bar I_1$,\n",
    "$W_2=\\partial W/\\partial\\bar I_2$ the nominal stress in the loaded direction is\n",
    "(e.g. R.W. Ogden, *Non-linear Elastic Deformations*, Dover 1997)\n",
    "\n",
    "$$P_\\mathrm{uni}=2\\Big(\\lambda-\\frac1{\\lambda^2}\\Big)\\Big(W_1+\\frac{W_2}{\\lambda}\\Big),\\quad\n",
    "  P_\\mathrm{bi}=2\\Big(\\lambda-\\frac1{\\lambda^5}\\Big)\\big(W_1+\\lambda^2W_2\\big),\\quad\n",
    "  P_\\mathrm{shear}=2\\Big(\\lambda-\\frac1{\\lambda^3}\\Big)\\big(W_1+W_2\\big).$$"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials.solids import IsochoricInvariantPolynomial, QuadraticVolumeLaw\n",
    "from onesim.meshing import CadHexahedralMesher\n",
    "from onesim.physics.solid_mechanics import FiniteStrainSolid\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 block with its named faces. With smooth supports every load case is a\n",
    "homogeneous deformation, which a coarse mesh of trilinear hexahedra represents exactly."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "block = load(\"polynomial_hyperelastic_block.step\")\n",
    "faces = block.boundaries\n",
    "side = block.size[0]\n",
    "mesh = CadHexahedralMesher(cells=(3, 3, 3)).generate(block)\n",
    "\n",
    "view = plots.Camera(elevation=25, azimuth=-55)\n",
    "fig = plots.figure(1, 2, size=(12, 5.5))\n",
    "plots.geometry(\n",
    "    block,\n",
    "    selection={\n",
    "        \"rollers\": faces.x_min | faces.y_min | faces.z_min,\n",
    "        \"pulled\": faces.x_max | faces.y_max,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Rubber block\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{mesh.cell_count} hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The two materials are lists of polynomial terms; each of the six runs ramps its stretch in\n",
    "twelve steps. The nominal stress is the reaction on `x_max` over the original face area."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "models = {\n",
    "    \"Mooney-Rivlin\": ((1, 0, 0.16e6), (0, 1, 0.01e6)),\n",
    "    \"five-term polynomial\": (\n",
    "        (1, 0, 0.16e6),\n",
    "        (0, 1, 0.01e6),\n",
    "        (2, 0, 2e3),\n",
    "        (1, 1, 0.5e3),\n",
    "        (0, 2, 0.1e3),\n",
    "    ),\n",
    "}\n",
    "cases = {\n",
    "    \"uniaxial tension\": (3.0, ()),\n",
    "    \"equibiaxial tension\": (2.0, ((faces.y_max, \"y\", lambda t: t),)),\n",
    "    \"pure shear\": (2.5, ((faces.y_max, \"y\", 0.0),)),\n",
    "}\n",
    "supports = (\n",
    "    (faces.x_min, \"x\", 0.0),\n",
    "    (faces.y_min, \"y\", 0.0),\n",
    "    (faces.z_min, \"z\", 0.0),\n",
    "    (faces.x_max, \"x\", lambda t: t),\n",
    ")\n",
    "stretch = {case: np.linspace(1.0, top, 13) for case, (top, _) in cases.items()}\n",
    "results = {\n",
    "    (model, case): FiniteStrainSolid(\n",
    "        shear_modulus=2 * (terms[0][2] + terms[1][2]),\n",
    "        bulk_modulus=2e4 * (terms[0][2] + terms[1][2]),\n",
    "    ).solve(\n",
    "        mesh=mesh,\n",
    "        times=(stretch[case] - 1) * side,\n",
    "        quadrature_order=3,\n",
    "        displacements=supports + extra,\n",
    "        elastic_response=IsochoricInvariantPolynomial(terms),\n",
    "        volume_law=QuadraticVolumeLaw(2e4 * (terms[0][2] + terms[1][2])),\n",
    "    )\n",
    "    for model, terms in models.items()\n",
    "    for case, (top, extra) in cases.items()\n",
    "}\n",
    "nominal = {\n",
    "    key: result.reactions[\n",
    "        :, np.isclose(result.displacement_space.dof_coordinates[:, 0], side), 0\n",
    "    ].sum(axis=1)\n",
    "    / side**2\n",
    "    for key, result in results.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reference\n",
    "\n",
    "The closed-form nominal stress from the derivatives of the polynomial, with the invariants of\n",
    "each load case."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def reference(terms, case, l):\n",
    "    \"\"\"Nominal stress of the incompressible polynomial material.\"\"\"\n",
    "    i1, i2 = {\n",
    "        \"uniaxial tension\": (l**2 + 2 / l, 2 * l + l**-2),\n",
    "        \"equibiaxial tension\": (2 * l**2 + l**-4, l**4 + 2 * l**-2),\n",
    "        \"pure shear\": (l**2 + 1 + l**-2, l**2 + 1 + l**-2),\n",
    "    }[case]\n",
    "    w1 = sum(c * i * (i1 - 3) ** max(i - 1, 0) * (i2 - 3) ** j for i, j, c in terms)\n",
    "    w2 = sum(c * j * (i1 - 3) ** i * (i2 - 3) ** max(j - 1, 0) for i, j, c in terms)\n",
    "    return {\n",
    "        \"uniaxial tension\": 2 * (l - l**-2) * (w1 + w2 / l),\n",
    "        \"equibiaxial tension\": 2 * (l - l**-5) * (w1 + l**2 * w2),\n",
    "        \"pure shear\": 2 * (l - l**-3) * (w1 + w2),\n",
    "    }[case]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "The largest deviation of the computed nominal stress from the closed form, relative to the\n",
    "stress at the largest stretch, and the volume change, which shows how close to incompressible\n",
    "the rubber stays."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\n",
    "    f\"{'model':22s} {'load case':20s} {'P at the end [MPa]':>19s} {'closed form':>12s} {'largest deviation':>18s} {'largest |J - 1|':>16s}\"\n",
    ")\n",
    "for (model, case), values in nominal.items():\n",
    "    exact = reference(models[model], case, stretch[case])\n",
    "    print(\n",
    "        f\"{model:22s} {case:20s} {values[-1] / 1e6:19.4f} {exact[-1] / 1e6:12.4f} {100 * np.abs(values - exact).max() / exact[-1]:17.3f} %\"\n",
    "        f\" {np.abs(results[model, case].jacobian - 1).max():16.1e}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Nominal stress over stretch for the three load cases and both models: simulation as markers,\n",
    "closed form dashed."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = {case: np.linspace(1.0, values[-1], 200) for case, values in stretch.items()}\n",
    "fig = plots.figure(1, 3, size=(18, 5.5))\n",
    "for k, case in enumerate(cases):\n",
    "    plots.line(\n",
    "        points={model: (stretch[case], nominal[model, case] / 1e6) for model in models},\n",
    "        reference={\n",
    "            model: (fine[case], reference(terms, case, fine[case]) / 1e6)\n",
    "            for model, terms in models.items()\n",
    "        },\n",
    "        xlabel=\"stretch λ\",\n",
    "        ylabel=\"nominal stress P [MPa]\",\n",
    "        title=case.capitalize(),\n",
    "        legend=\"upper left\",\n",
    "        ax=fig[k],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Fit the coefficients to measurements with the study service of OneSimulation, as in the\n",
    "Mooney-Rivlin example; check the Drucker stability of a fitted polynomial by running large\n",
    "stretches in all three load cases. Replace the block by a real part from a STEP file: the\n",
    "material declaration stays the same."
   ]
  }
 ]
}
