{
 "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": [
    "# Elastic constants from a tensile test\n",
    "\n",
    "In a tensile test the machine records the force $F$ and an extensometer the contraction of the\n",
    "width of the reduced section. Both depend on Young's modulus $E$ and Poisson's ratio $\\nu$; in a\n",
    "specimen with fillets and wide grip ends the relation is not a simple formula, so the constants\n",
    "are found by fitting a simulation of the whole specimen to the measurements.\n",
    "\n",
    "The two kinds of data have very different sizes: forces of about $10^4$ N, displacements of\n",
    "about $10^{-6}$ m. A plain least-squares fit adds their squares and simply ignores the\n",
    "contraction. If the measurement errors are independent and Gaussian with standard deviations\n",
    "$s_F$ and $s_u$, the **maximum-likelihood** estimate minimises instead\n",
    "\n",
    "$$\\chi^2(E,\\nu)=\\sum_k\\Big(\\frac{F_k^\\mathrm{sim}-F_k}{s_F}\\Big)^2+\\sum_k\\Big(\\frac{u_k^\\mathrm{sim}-u_k}{s_u}\\Big)^2 ,$$\n",
    "\n",
    "which weights every measurement by its accuracy and makes the result independent of units.\n",
    "\n",
    "**Setup.** A flat steel specimen of the sheet type of ISO 6892-1 and ASTM E8: reduced section\n",
    "12.5 mm wide, 3 mm thick and 60 mm long, fillets of 12.5 mm radius, grip ends 20 mm wide; the\n",
    "grips pull the ends apart by up to $2\\times0.06$ mm in four steps. The specimen is symmetric\n",
    "about its mid-length, mid-width and mid-thickness planes, so one eighth is modelled. It comes\n",
    "from the CAD file `tensile_test_parameter_estimation.step`, written by\n",
    "`tensile_test_parameter_estimation_geometry.py` with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `symmetry_x` (mid-width) | $u_x=0$ |\n",
    "| `symmetry_y` (mid-length) | $u_y=0$ |\n",
    "| `symmetry_z` (mid-thickness) | $u_z=0$ |\n",
    "| `grip` (pulled end) | $u_y$ prescribed |\n",
    "| all other faces | traction free |\n",
    "\n",
    "**The measurements.** There is no laboratory record here. The \"measured\" force and the\n",
    "contraction of the half width at mid-length on the side face `gauge_side` are the simulation\n",
    "with $E=200$ GPa and $\\nu=0.29$, plus Gaussian noise of 1 % of the largest force and 2 % of the\n",
    "largest contraction. **Reference:** these known constants, which a correct estimate recovers\n",
    "within the standard errors that the noise leaves."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import TetrahedralMesher\n",
    "from onesim.physics.solid_mechanics import SmallStrainSolid\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": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the eighth specimen with its named faces; the mesh has tetrahedra of 1.5 mm,\n",
    "1 mm in the fillet region."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "specimen = load(\"tensile_test_parameter_estimation.step\")\n",
    "faces = specimen.boundaries\n",
    "half_width, end = 0.0125 / 2, specimen.size[1]\n",
    "mesh = TetrahedralMesher(\n",
    "    target_size=0.0015,\n",
    "    size_field=lambda p: np.where(np.abs(p[:, 1] - 0.036) < 0.008, 0.001, 0.0015),\n",
    ").generate(specimen)\n",
    "\n",
    "view = plots.Camera(elevation=35, azimuth=-55)\n",
    "fig = plots.figure(1, 2, size=(14, 6.5))\n",
    "plots.geometry(\n",
    "    specimen,\n",
    "    selection={\n",
    "        \"grip\": faces.grip,\n",
    "        \"mid-length plane\": faces.symmetry_y,\n",
    "        \"extensometer side\": faces.gauge_side,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"One eighth of the flat tensile specimen\",\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} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model and synthetic measurements\n",
    "\n",
    "One simulation per parameter set: 3D small-strain elasticity with quadratic tetrahedra, the grip\n",
    "pulled in four steps. The force of the whole specimen is four times the reaction at the grip of\n",
    "the eighth, the contraction the displacement $u_x$ of the side face at mid-length and\n",
    "mid-thickness."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "pull = np.linspace(0.0, 0.06e-3, 5)\n",
    "tensile_test = lambda modulus, poisson: SmallStrainSolid(\n",
    "    youngs_modulus=modulus, poisson_ratio=poisson, kinematics=\"volume\"\n",
    ").solve(\n",
    "    mesh=mesh,\n",
    "    times=pull,\n",
    "    order=2,\n",
    "    displacements=(\n",
    "        (faces.symmetry_x, \"x\", 0.0),\n",
    "        (faces.symmetry_y, \"y\", 0.0),\n",
    "        (faces.symmetry_z, \"z\", 0.0),\n",
    "        (faces.grip, \"y\", lambda t: t),\n",
    "    ),\n",
    ")\n",
    "grip = lambda result: np.isclose(result.coordinates[:, 1], end)\n",
    "readings = lambda result: (\n",
    "    4 * result.reactions[1:, grip(result), 1].sum(axis=1),\n",
    "    result.displacement[1:, probe, 0],\n",
    ")\n",
    "true = tensile_test(200e9, 0.29)\n",
    "probe = int(\n",
    "    np.argmin(np.linalg.norm(true.coordinates - (half_width, 0.0, 0.0), axis=1))\n",
    ")\n",
    "force_exact, contraction_exact = readings(true)\n",
    "noise = np.random.default_rng(2024)\n",
    "force_error, contraction_error = (\n",
    "    0.01 * force_exact.max(),\n",
    "    0.02 * np.abs(contraction_exact).max(),\n",
    ")\n",
    "force_data = force_exact + force_error * noise.standard_normal(4)\n",
    "contraction_data = contraction_exact + contraction_error * noise.standard_normal(4)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Maximum-likelihood estimate\n",
    "\n",
    "The optimizer works on the stiffness factor $E/200$ GPa and on $\\nu$, which change the readings\n",
    "by similar relative amounts. Every evaluation is a real 3D simulation; the gradient comes from\n",
    "one extra run per parameter. The misfit handed to it is $\\chi^2/(1.5\\cdot10^5)$, which keeps one\n",
    "gradient step below the curvature of the misfit."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "likelihood = lambda result: {\n",
    "    \"misfit\": (\n",
    "        np.sum(((readings(result)[0] - force_data) / force_error) ** 2)\n",
    "        + np.sum(((readings(result)[1] - contraction_data) / contraction_error) ** 2)\n",
    "    )\n",
    "    / 1.5e5\n",
    "}\n",
    "study = SimulationStudyService(\n",
    "    (StudyParameter(\"stiffness\", 0.75, 1.25), StudyParameter(\"poisson\", 0.2, 0.4)),\n",
    "    lambda values: tensile_test(200e9 * values[\"stiffness\"], values[\"poisson\"]),\n",
    "    likelihood,\n",
    "    solve=lambda result: result,\n",
    ")\n",
    "start = {\"stiffness\": 0.9, \"poisson\": 0.35}\n",
    "estimate = study.optimize(\n",
    "    (\"misfit\",),\n",
    "    start=start,\n",
    "    step=1e-3,\n",
    "    maximum_iterations=15,\n",
    "    maximum_runs=300,\n",
    "    tolerance=1e-5,\n",
    ")\n",
    "modulus, poisson = (\n",
    "    200 * estimate.parameters[\"stiffness\"],\n",
    "    estimate.parameters[\"poisson\"],\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "The recovered constants against the values used to make the data, with standard errors from the\n",
    "Gauss-Newton covariance of the weighted residuals (sensitivities from one more run per\n",
    "parameter), and $\\chi^2$ at the estimate, which should be close to the number of measurements\n",
    "(8) when the fit is as good as the noise. The last line shows why a plain sum of squares in SI\n",
    "units cannot find $\\nu$: at the start the contraction contributes a vanishing share to it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fitted = readings(tensile_test(1e9 * modulus, poisson))\n",
    "weighted = lambda r: np.concatenate((r[0] / force_error, r[1] / contraction_error))\n",
    "sensitivity = np.column_stack(\n",
    "    [\n",
    "        (\n",
    "            weighted(readings(tensile_test(1e9 * (modulus + dE), poisson + dnu)))\n",
    "            - weighted(fitted)\n",
    "        )\n",
    "        / max(dE, dnu)\n",
    "        for dE, dnu in ((0.2, 0.0), (0.0, 1e-4))\n",
    "    ]\n",
    ")\n",
    "sigma = np.sqrt(np.diag(np.linalg.inv(sensitivity.T @ sensitivity)))\n",
    "begin = readings(tensile_test(200e9 * start[\"stiffness\"], start[\"poisson\"]))\n",
    "print(f\"{'':22s} {'E [GPa]':>8s} {'ν':>7s}\")\n",
    "print(f\"{'values behind the data':22s} {200.0:8.2f} {0.29:7.4f}\")\n",
    "print(f\"{'maximum likelihood':22s} {modulus:8.2f} {poisson:7.4f}\")\n",
    "print(\n",
    "    f\"{'standard error':22s} {sigma[0]:8.2f} {sigma[1]:7.4f}   deviation {(modulus - 200) / sigma[0]:+.2f} σ and {(poisson - 0.29) / sigma[1]:+.2f} σ \"\n",
    "    f\"({100 * (modulus / 200 - 1):+.2f} % and {100 * (poisson / 0.29 - 1):+.2f} %)\"\n",
    ")\n",
    "print(\n",
    "    f\"χ² at the estimate: {1.5e5 * estimate.objectives['misfit']:.1f} for 8 measurements; {estimate.run_count} simulation runs, \"\n",
    "    f\"{estimate.iterations} iterations, converged: {estimate.converged}\"\n",
    ")\n",
    "print(\n",
    "    f\"largest force {force_exact.max() / 1e3:.3f} kN, largest contraction of the half width {-1e6 * contraction_exact.min():.3f} µm\"\n",
    ")\n",
    "print(\n",
    "    f\"share of the contraction in a plain sum of squares at the start: \"\n",
    "    f\"{np.sum((begin[1] - contraction_data) ** 2) / (np.sum((begin[0] - force_data) ** 2) + np.sum((begin[1] - contraction_data) ** 2)):.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The measured and fitted force and contraction, and the path of the optimisation in the\n",
    "parameter plane."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "millimetres = 2e3 * pull[1:]\n",
    "fig = plots.figure(1, 3, size=(18, 5.5))\n",
    "plots.line(\n",
    "    y={\"maximum-likelihood fit\": (millimetres, fitted[0] / 1e3)},\n",
    "    points={\"measured\": (millimetres, force_data / 1e3)},\n",
    "    xlabel=\"elongation between the grips [mm]\",\n",
    "    ylabel=\"force [kN]\",\n",
    "    title=\"Force\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\"maximum-likelihood fit\": (millimetres, -1e6 * fitted[1])},\n",
    "    points={\"measured\": (millimetres, -1e6 * contraction_data)},\n",
    "    xlabel=\"elongation between the grips [mm]\",\n",
    "    ylabel=\"contraction of the half width [µm]\",\n",
    "    title=\"Contraction of the reduced section\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        \"simulation runs\": (\n",
    "            [200 * run.parameters[\"stiffness\"] for run in study.executed_runs],\n",
    "            [run.parameters[\"poisson\"] for run in study.executed_runs],\n",
    "        )\n",
    "    },\n",
    "    points={\n",
    "        \"start\": ([200 * start[\"stiffness\"]], [start[\"poisson\"]]),\n",
    "        \"values behind the data\": ([200.0], [0.29]),\n",
    "    },\n",
    "    markers=True,\n",
    "    xlabel=\"Young's modulus E [GPa]\",\n",
    "    ylabel=\"Poisson's ratio ν\",\n",
    "    title=\"Path of the optimisation\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the noise of the contraction and watch the uncertainty of $\\nu$ grow while $E$ stays;\n",
    "measure the contraction of the thickness as well, or move the extensometer into the fillet,\n",
    "where the simple bar formula no longer holds."
   ]
  }
 ]
}
