{
 "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": [
    "# Ogden parameters from Treloar's tests\n",
    "\n",
    "The Ogden model writes the strain energy of rubber directly in the principal stretches,\n",
    "\n",
    "$$W=\\sum_{p=1}^{N}\\frac{2\\mu_p}{\\alpha_p^2}\\big(\\lambda_1^{\\alpha_p}+\\lambda_2^{\\alpha_p}+\\lambda_3^{\\alpha_p}-3\\big),\\qquad\n",
    "  \\lambda_1\\lambda_2\\lambda_3=1 ,$$\n",
    "\n",
    "with the initial shear modulus $\\mu_0=\\sum\\mu_p$. With three terms it reproduces natural rubber\n",
    "over the whole range of the tests: a soft term with $\\alpha\\approx1.3$, a stiffening term with a\n",
    "large exponent and a term with a negative exponent for biaxial states. Six parameters cannot be\n",
    "found from one test; uniaxial tension, equibiaxial tension and pure shear together separate them.\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 with their relative\n",
    "deviation.\n",
    "\n",
    "**Reference.** R.W. Ogden, *Large deformation isotropic elasticity - on the correlation of theory\n",
    "and experiment for incompressible rubberlike solids*, Proc. R. Soc. Lond. A 326, 1972, 565-584,\n",
    "fitted the same tests with $\\alpha=(1.3,\\,5.0,\\,-2.0)$ and, in the convention above,\n",
    "$\\mu\\approx(402,\\,3.0,\\,9.8)$ kPa (his coefficients $6.3$, $0.012$, $-0.1$ kgf/cm² times $\\alpha_p/2$).\n",
    "The fit must find a set of the same character with a misfit no larger than his."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.materials.solids import IncompressibleVolumeLaw, IsochoricOgden\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 mu, alpha, stretches: {\n",
    "    mode: HomogeneousFiniteStrainTest(\n",
    "        material=IsochoricOgden(mu=mu, alpha=alpha),\n",
    "        volume_law=IncompressibleVolumeLaw(),\n",
    "    ).solve(\n",
    "        mode=mode,\n",
    "        stretches=stretches[mode],\n",
    "        solver=newton,\n",
    "        linearize=centered_array_jacobian,\n",
    "        stress_scale=1e6,\n",
    "    )\n",
    "    for mode in treloar\n",
    "}\n",
    "measured_stretch = {mode: stretch for mode, (stretch, _) in treloar.items()}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The fit\n",
    "\n",
    "Six parameters, each inside physical bounds; the third term keeps a negative exponent. The\n",
    "study service runs the three tests for every trial set and minimises the relative residuals\n",
    "with the Levenberg-Marquardt method, starting from rounded values."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "names = (\"mu1\", \"mu2\", \"mu3\", \"alpha1\", \"alpha2\", \"alpha3\")\n",
    "study = SimulationStudyService(\n",
    "    tuple(\n",
    "        StudyParameter(name, low, high)\n",
    "        for name, low, high in zip(\n",
    "            names, (1e5, 1.0, 1.0, 0.5, 3.0, -5.0), (1e6, 2e4, 8e4, 3.0, 9.0, -1.0)\n",
    "        )\n",
    "    ),\n",
    "    build=lambda v: tests(\n",
    "        (v[\"mu1\"], v[\"mu2\"], v[\"mu3\"]),\n",
    "        (v[\"alpha1\"], v[\"alpha2\"], v[\"alpha3\"]),\n",
    "        measured_stretch,\n",
    "    ),\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={\n",
    "        \"mu1\": 4e5,\n",
    "        \"mu2\": 2e3,\n",
    "        \"mu3\": 1e4,\n",
    "        \"alpha1\": 1.5,\n",
    "        \"alpha2\": 5.0,\n",
    "        \"alpha3\": -2.0,\n",
    "    },\n",
    "    method=\"levenberg_marquardt\",\n",
    "    maximum_runs=2000,\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "The fitted parameters with their standard errors beside Ogden's, and the misfit of both\n",
    "parameter sets in each load mode."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fitted = (\n",
    "    tuple(fit.parameters[n] for n in names[:3]),\n",
    "    tuple(fit.parameters[n] for n in names[3:]),\n",
    ")\n",
    "ogden_1972 = (\n",
    "    (0.618e6 * 1.3 / 2, 1.18e3 * 5.0 / 2, -9.8e3 * -2.0 / 2),\n",
    "    (1.3, 5.0, -2.0),\n",
    ")\n",
    "print(f\"{'':16s}\" + \"\".join(f\"{name:>11s}\" for name in names))\n",
    "print(\n",
    "    f\"{'fit':16s}\"\n",
    "    + \"\".join(\n",
    "        f\"{fit.parameters[n] / (1e3 if n.startswith('mu') else 1):11.3f}\" for n in names\n",
    "    )\n",
    "    + \"   (μ in kPa)\"\n",
    ")\n",
    "print(\n",
    "    f\"{'standard error':16s}\"\n",
    "    + \"\".join(\n",
    "        f\"{fit.standard_errors[n] / (1e3 if n.startswith('mu') else 1):11.3f}\"\n",
    "        for n in names\n",
    "    )\n",
    ")\n",
    "print(\n",
    "    f\"{'Ogden (1972)':16s}\"\n",
    "    + \"\".join(\n",
    "        f\"{value / (1e3 if k < 3 else 1):11.3f}\"\n",
    "        for k, value in enumerate(ogden_1972[0] + ogden_1972[1])\n",
    "    )\n",
    ")\n",
    "print(\n",
    "    f\"initial shear modulus: fit {sum(fitted[0]) / 1e3:.1f} kPa, Ogden (1972) {sum(ogden_1972[0]) / 1e3:.1f} kPa; \"\n",
    "    f\"converged: {fit.converged}, rank {fit.rank}, {fit.run_count} parameter evaluations\"\n",
    ")\n",
    "results = {\n",
    "    \"fit\": tests(*fitted, measured_stretch),\n",
    "    \"Ogden (1972)\": tests(*ogden_1972, measured_stretch),\n",
    "}\n",
    "print(\n",
    "    f\"{'relative RMS deviation':24s}\"\n",
    "    + \"\".join(f\"{mode:>14s}\" for mode in treloar)\n",
    "    + f\"{'all 52 points':>15s}\"\n",
    ")\n",
    "for label, result in results.items():\n",
    "    deviation = {\n",
    "        mode: result[mode].nominal_stress[:, 0, 0] / stress - 1\n",
    "        for mode, (_, stress) in treloar.items()\n",
    "    }\n",
    "    print(\n",
    "        f\"{label:24s}\"\n",
    "        + \"\".join(\n",
    "            f\"{100 * np.sqrt(np.mean(values**2)):13.1f}%\"\n",
    "            for values in deviation.values()\n",
    "        )\n",
    "        + f\"{100 * np.sqrt(np.mean(np.concatenate(list(deviation.values())) ** 2)):14.1f}%\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The three tests with the fitted model and with Ogden's parameters, evaluated on fine stretch\n",
    "grids, and the relative deviation of the fit 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",
    "    label: tests(*parameters, fine)\n",
    "    for label, parameters in ((\"fit\", fitted), (\"Ogden (1972)\", ogden_1972))\n",
    "}\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.line(\n",
    "    y={\n",
    "        mode.replace(\"_\", \" \"): (\n",
    "            fine[mode],\n",
    "            curves[\"fit\"][mode].nominal_stress[:, 0, 0] / 1e6,\n",
    "        )\n",
    "        for mode in treloar\n",
    "    },\n",
    "    reference={\n",
    "        mode.replace(\"_\", \" \"): (\n",
    "            fine[mode],\n",
    "            curves[\"Ogden (1972)\"][mode].nominal_stress[:, 0, 0] / 1e6,\n",
    "        )\n",
    "        for mode in treloar\n",
    "    },\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), fit (lines), Ogden 1972 (dashed)\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        mode.replace(\"_\", \" \"): (\n",
    "            stretch,\n",
    "            100 * (results[\"fit\"][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 right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Fit only the uniaxial test and watch the equibiaxial prediction drift: the parameters are then\n",
    "poorly determined, which the standard errors show at once. Drop the third term for a two-term\n",
    "Ogden model, or compare with the Mooney-Rivlin fit of the same data."
   ]
  }
 ]
}
