{
 "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": [
    "# Mooney-Rivlin fit to Treloar's data\n",
    "\n",
    "Rubber is nearly incompressible and stays elastic up to stretches of 5 to 7. Its behaviour is\n",
    "described by a strain energy density of the isochoric invariants $\\bar I_1,\\bar I_2$; the\n",
    "Mooney-Rivlin model is the polynomial of first order,\n",
    "\n",
    "$$W=c_1(\\bar I_1-3)+c_2(\\bar I_2-3).$$\n",
    "\n",
    "For the incompressible material the nominal stress (force per original area) in the stretched\n",
    "direction of the three classical tests is\n",
    "\n",
    "$$P_\\mathrm{uni}=2\\Big(\\lambda-\\frac1{\\lambda^2}\\Big)\\Big(c_1+\\frac{c_2}{\\lambda}\\Big),\\quad\n",
    "  P_\\mathrm{bi}=2\\Big(\\lambda-\\frac1{\\lambda^5}\\Big)\\big(c_1+\\lambda^2c_2\\big),\\quad\n",
    "  P_\\mathrm{shear}=2\\Big(\\lambda-\\frac1{\\lambda^3}\\Big)\\big(c_1+c_2\\big).$$\n",
    "\n",
    "**Data.** L.R.G. Treloar, *Stress-strain data for vulcanised rubber under various types of\n",
    "deformation*, Trans. Faraday Soc. 40, 1944, 59-70: 23 points in uniaxial tension, 16 in\n",
    "equibiaxial tension and 13 in pure shear, from a widely used digitisation of the original\n",
    "figures (nominal stress converted from kgf/cm² to Pa). All 52 points enter the fit with their\n",
    "relative deviation, so that small and large stresses count alike.\n",
    "\n",
    "**Reference.** The model is linear in $c_1,c_2$, so the best fit also follows from a direct linear\n",
    "least-squares solution of the formulas above: the fit through the material tests must arrive\n",
    "there."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.materials.solids import (\n",
    "    IncompressibleVolumeLaw,\n",
    "    IsochoricInvariantPolynomial,\n",
    ")\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import DampedNewton, centered_array_jacobian\n",
    "from onesim.physics.solid_mechanics import HomogeneousFiniteStrainTest\n",
    "from onesim.simulation.studies import SimulationStudyService, StudyParameter\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The measurements\n",
    "\n",
    "Stretch and nominal stress of the three tests."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "treloar = {\n",
    "    \"uniaxial\": (\n",
    "        np.array(\n",
    "            [\n",
    "                1.1338,\n",
    "                1.2675,\n",
    "                1.3567,\n",
    "                1.6242,\n",
    "                1.8917,\n",
    "                2.1592,\n",
    "                2.4268,\n",
    "                3.051,\n",
    "                3.586,\n",
    "                4.0318,\n",
    "                4.7898,\n",
    "                5.3694,\n",
    "                5.8153,\n",
    "                6.172,\n",
    "                6.4395,\n",
    "                6.707,\n",
    "                6.9299,\n",
    "                7.0637,\n",
    "                7.1975,\n",
    "                7.3312,\n",
    "                7.465,\n",
    "                7.5541,\n",
    "                7.6433,\n",
    "            ]\n",
    "        ),\n",
    "        98066.5\n",
    "        * np.array(\n",
    "            [\n",
    "                1.5506,\n",
    "                2.4367,\n",
    "                3.1013,\n",
    "                4.2089,\n",
    "                5.3165,\n",
    "                5.981,\n",
    "                6.8671,\n",
    "                8.8608,\n",
    "                10.6329,\n",
    "                12.4051,\n",
    "                16.1709,\n",
    "                19.9367,\n",
    "                23.481,\n",
    "                27.4684,\n",
    "                31.0127,\n",
    "                34.557,\n",
    "                38.3228,\n",
    "                42.0886,\n",
    "                45.6329,\n",
    "                49.3987,\n",
    "                53.1646,\n",
    "                56.9304,\n",
    "                64.2405,\n",
    "            ]\n",
    "        ),\n",
    "    ),\n",
    "    \"equibiaxial\": (\n",
    "        np.array(\n",
    "            [\n",
    "                1.02,\n",
    "                1.06,\n",
    "                1.11,\n",
    "                1.14,\n",
    "                1.2,\n",
    "                1.31,\n",
    "                1.42,\n",
    "                1.68,\n",
    "                1.94,\n",
    "                2.49,\n",
    "                3.03,\n",
    "                3.43,\n",
    "                3.75,\n",
    "                4.07,\n",
    "                4.26,\n",
    "                4.45,\n",
    "            ]\n",
    "        ),\n",
    "        np.array(\n",
    "            [\n",
    "                92026,\n",
    "                155926,\n",
    "                236213,\n",
    "                257130,\n",
    "                325973,\n",
    "                434219,\n",
    "                508279,\n",
    "                647474,\n",
    "                762899,\n",
    "                959649,\n",
    "                1239080,\n",
    "                1439655,\n",
    "                1706357,\n",
    "                1971705,\n",
    "                2201613,\n",
    "                2417633,\n",
    "            ],\n",
    "            dtype=float,\n",
    "        ),\n",
    "    ),\n",
    "    \"pure_shear\": (\n",
    "        np.array(\n",
    "            [\n",
    "                1.069,\n",
    "                1.1034,\n",
    "                1.1724,\n",
    "                1.2828,\n",
    "                1.4276,\n",
    "                1.8483,\n",
    "                2.3862,\n",
    "                3.0,\n",
    "                3.4897,\n",
    "                4.0345,\n",
    "                4.4483,\n",
    "                4.7793,\n",
    "                5.0621,\n",
    "            ]\n",
    "        ),\n",
    "        np.array(\n",
    "            [\n",
    "                58840,\n",
    "                156906,\n",
    "                235360,\n",
    "                329503,\n",
    "                411879,\n",
    "                588399,\n",
    "                764919,\n",
    "                941438,\n",
    "                1090499,\n",
    "                1270942,\n",
    "                1459230,\n",
    "                1625943,\n",
    "                1784810,\n",
    "            ],\n",
    "            dtype=float,\n",
    "        ),\n",
    "    ),\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The material tests\n",
    "\n",
    "`HomogeneousFiniteStrainTest` is a single material point under the homogeneous stretch of the\n",
    "chosen mode, with zero traction on the free directions and the incompressibility constraint;\n",
    "a damped Newton method finds the free stretch and the pressure at every point of the curve."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "newton = DampedNewton(\n",
    "    linear_solver=SparseDirect(),\n",
    "    relative_tolerance=0.0,\n",
    "    absolute_tolerance=2e-12,\n",
    "    maximum_iterations=80,\n",
    ").bind()\n",
    "tests = lambda c1, c2: {\n",
    "    mode: HomogeneousFiniteStrainTest(\n",
    "        material=IsochoricInvariantPolynomial.mooney_rivlin(c1, c2),\n",
    "        volume_law=IncompressibleVolumeLaw(),\n",
    "    ).solve(\n",
    "        mode=mode,\n",
    "        stretches=stretch,\n",
    "        solver=newton,\n",
    "        linearize=centered_array_jacobian,\n",
    "        stress_scale=1e6,\n",
    "    )\n",
    "    for mode, (stretch, _) in treloar.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The fit\n",
    "\n",
    "The study service evaluates the three tests for every trial pair and minimises the relative\n",
    "residuals with the Levenberg-Marquardt method. The standard errors come from the covariance of\n",
    "the linearised problem, with the noise level estimated from the residuals."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "study = SimulationStudyService(\n",
    "    (StudyParameter(\"c1\", 1e3, 1e6), StudyParameter(\"c2\", 0.0, 3e5)),\n",
    "    build=lambda values: tests(values[\"c1\"], values[\"c2\"]),\n",
    "    solve=lambda results: results,\n",
    "    measure=lambda results: {\n",
    "        f\"{mode}_{k}\": float(value)\n",
    "        for mode, result in results.items()\n",
    "        for k, value in enumerate(result.nominal_stress[:, 0, 0])\n",
    "    },\n",
    ")\n",
    "fit = study.fit(\n",
    "    residuals=lambda values: np.concatenate(\n",
    "        [\n",
    "            np.array([values[f\"{mode}_{k}\"] for k in range(len(stress))]) / stress - 1\n",
    "            for mode, (_, stress) in treloar.items()\n",
    "        ]\n",
    "    ),\n",
    "    start={\"c1\": 1.7e5, \"c2\": 2e4},\n",
    "    method=\"levenberg_marquardt\",\n",
    "    maximum_runs=400,\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "The fitted moduli against the direct linear least-squares solution of the same relative\n",
    "problem, and the misfit of the fitted model in each load mode."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "shapes = {\n",
    "    \"uniaxial\": lambda l: 2\n",
    "    * (l - l**-2)[:, None]\n",
    "    * np.column_stack((np.ones_like(l), 1 / l)),\n",
    "    \"equibiaxial\": lambda l: 2\n",
    "    * (l - l**-5)[:, None]\n",
    "    * np.column_stack((np.ones_like(l), l**2)),\n",
    "    \"pure_shear\": lambda l: 2\n",
    "    * (l - l**-3)[:, None]\n",
    "    * np.column_stack((np.ones_like(l), np.ones_like(l))),\n",
    "}\n",
    "direct = np.linalg.lstsq(\n",
    "    np.vstack(\n",
    "        [\n",
    "            shapes[mode](stretch) / stress[:, None]\n",
    "            for mode, (stretch, stress) in treloar.items()\n",
    "        ]\n",
    "    ),\n",
    "    np.ones(52),\n",
    "    rcond=None,\n",
    ")[0]\n",
    "best = tests(fit.parameters[\"c1\"], fit.parameters[\"c2\"])\n",
    "print(f\"{'':30s} {'c1 [kPa]':>10s} {'c2 [kPa]':>10s}\")\n",
    "print(\n",
    "    f\"{'fit of the material tests':30s} {fit.parameters['c1'] / 1e3:10.3f} {fit.parameters['c2'] / 1e3:10.3f}\"\n",
    ")\n",
    "print(\n",
    "    f\"{'standard error':30s} {fit.standard_errors['c1'] / 1e3:10.3f} {fit.standard_errors['c2'] / 1e3:10.3f}\"\n",
    ")\n",
    "print(\n",
    "    f\"{'direct linear least squares':30s} {direct[0] / 1e3:10.3f} {direct[1] / 1e3:10.3f}\"\n",
    ")\n",
    "print(\n",
    "    f\"largest relative difference to the direct solution: {np.max(np.abs(np.array([fit.parameters['c1'], fit.parameters['c2']]) / direct - 1)):.1e}; \"\n",
    "    f\"converged: {fit.converged}, {fit.run_count} parameter evaluations\"\n",
    ")\n",
    "print(\n",
    "    f\"initial shear modulus μ0 = 2(c1 + c2) = {2 * (fit.parameters['c1'] + fit.parameters['c2']) / 1e3:.1f} kPa\"\n",
    ")\n",
    "for mode, (stretch, stress) in treloar.items():\n",
    "    deviation = best[mode].nominal_stress[:, 0, 0] / stress - 1\n",
    "    print(\n",
    "        f\"{mode:12s} relative RMS deviation {100 * np.sqrt(np.mean(deviation**2)):5.1f} %, largest {100 * np.abs(deviation).max():5.1f} %\"\n",
    "        f\" (at λ = {stretch[np.abs(deviation).argmax()]:.2f})\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The three tests with the fitted model, evaluated on fine stretch grids, and the relative\n",
    "deviation of the model from every measured point."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = {\n",
    "    mode: np.linspace(1.0 + 1e-3, stretch[-1], 80)\n",
    "    for mode, (stretch, _) in treloar.items()\n",
    "}\n",
    "curves = {\n",
    "    mode: HomogeneousFiniteStrainTest(\n",
    "        material=IsochoricInvariantPolynomial.mooney_rivlin(\n",
    "            fit.parameters[\"c1\"], fit.parameters[\"c2\"]\n",
    "        ),\n",
    "        volume_law=IncompressibleVolumeLaw(),\n",
    "    )\n",
    "    .solve(\n",
    "        mode=mode,\n",
    "        stretches=fine[mode],\n",
    "        solver=newton,\n",
    "        linearize=centered_array_jacobian,\n",
    "        stress_scale=1e6,\n",
    "    )\n",
    "    .nominal_stress[:, 0, 0]\n",
    "    for mode in treloar\n",
    "}\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.line(\n",
    "    y={mode.replace(\"_\", \" \"): (fine[mode], curves[mode] / 1e6) for mode in treloar},\n",
    "    points={\n",
    "        mode.replace(\"_\", \" \"): (stretch, stress / 1e6)\n",
    "        for mode, (stretch, stress) in treloar.items()\n",
    "    },\n",
    "    xlabel=\"stretch λ\",\n",
    "    ylabel=\"nominal stress P [MPa]\",\n",
    "    title=\"Treloar (markers) and the Mooney-Rivlin fit (lines)\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        mode.replace(\"_\", \" \"): (\n",
    "            stretch,\n",
    "            100 * (best[mode].nominal_stress[:, 0, 0] / stress - 1),\n",
    "        )\n",
    "        for mode, (stretch, stress) in treloar.items()\n",
    "    },\n",
    "    hlines=0.0,\n",
    "    markers=True,\n",
    "    xlabel=\"stretch λ\",\n",
    "    ylabel=\"(P_model - P_Treloar) / P_Treloar [%]\",\n",
    "    title=\"Relative deviation of the fit\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "The two-term model misses the stiffening at large stretch in uniaxial tension and overshoots\n",
    "in equibiaxial tension: fit the Ogden model to the same data (the Ogden example), or a\n",
    "higher-order polynomial `IsochoricInvariantPolynomial(((i, j, c_ij), ...))`."
   ]
  }
 ]
}
