{
 "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": [
    "# Hertz contact of an elastic sphere on an elastic block\n",
    "\n",
    "A sphere of radius $R$ is pressed onto a flat block. Both are made of the same linear-elastic\n",
    "steel (Young's modulus $E$, Poisson's ratio $\\nu$). Hertz's theory for two elastic half-spaces\n",
    "(K. L. Johnson, *Contact Mechanics*, Cambridge University Press 1985, Sec. 4.2 and 3.4) predicts\n",
    "for a transmitted force $F$\n",
    "\n",
    "$$\\frac{1}{E^*}=\\frac{1-\\nu_1^2}{E_1}+\\frac{1-\\nu_2^2}{E_2},\\qquad\n",
    "  a=\\left(\\frac{3FR}{4E^*}\\right)^{1/3},\\qquad\n",
    "  p_0=\\frac{3F}{2\\pi a^2},\\qquad\n",
    "  \\delta=\\left(\\frac{9F^2}{16RE^{*2}}\\right)^{1/3},$$\n",
    "\n",
    "a circular contact patch of radius $a$ with the pressure $p(r)=p_0\\sqrt{1-r^2/a^2}$ and an\n",
    "approach $\\delta$ of distant points. Below the centre of the contact (Johnson, eq. 3.45)\n",
    "\n",
    "$$\\frac{\\sigma_z}{p_0}=-\\frac{1}{1+z^2/a^2},\\qquad\n",
    "  \\frac{\\sigma_r}{p_0}=-(1+\\nu)\\Bigl(1-\\frac{z}{a}\\arctan\\frac{a}{z}\\Bigr)+\\frac{1}{2}\\,\\frac{1}{1+z^2/a^2}.$$\n",
    "\n",
    "The largest shear stress $\\tau_1=|\\sigma_r-\\sigma_z|/2$ occurs **below** the surface: for\n",
    "$\\nu=0.3$ it reaches $0.31\\,p_0$ at the depth $z\\approx0.48\\,a$, where rolling-contact fatigue\n",
    "starts.\n",
    "\n",
    "One quarter of the assembly is computed. The block comes from the CAD file\n",
    "`hertz_sphere_on_flat_3d.step` (faces `x_min` to `z_max`), the quarter of the lower half sphere\n",
    "from `hertz_sphere_on_flat_3d_sphere.step` (faces `plane_x`, `plane_y`, `equator`, `surface`). The\n",
    "script `hertz_sphere_on_flat_3d_geometry.py` builds both with the CAD objects of OneSimulation.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| block `x_min`, `y_min`; sphere `plane_x`, `plane_y` | symmetry |\n",
    "| block `z_min` | frictionless support |\n",
    "| sphere `equator` | frictionless rigid platen, pressed down by the approach |\n",
    "| block `z_max` against sphere `surface` | frictionless mortar contact |"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import (\n",
    "    Geometric,\n",
    "    Piecewise,\n",
    "    StructuredHexahedralMesher,\n",
    "    TetrahedralMesher,\n",
    "    Uniform,\n",
    ")\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.physics.solid_mechanics import MortarBody, MortarContact, SmallStrainSolid\n",
    "from onesim.results.comparisons import convergence\n",
    "from onesim.results.derived import max_shear, strain_from_gradient, voigt\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and meshes\n",
    "\n",
    "The expected contact radius is 0.5 mm. The block gets `n` uniform hexahedra per contact radius\n",
    "under the contact and graded cells away from it; the cells of the sphere grow with the distance\n",
    "from the contact point. Three levels are meshed."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "block, sphere = load(\"hertz_sphere_on_flat_3d.step\"), load(\n",
    "    \"hertz_sphere_on_flat_3d_sphere.step\"\n",
    ")\n",
    "lower, upper = block.boundaries, sphere.boundaries\n",
    "radius, width, patch, levels = sphere.size[2], block.size[0], 0.5e-3, (7, 9, 12)\n",
    "block_meshes = [\n",
    "    StructuredHexahedralMesher(\n",
    "        cells=(round(1.2 * n) + 7, round(1.2 * n) + 7, n + 7),\n",
    "        grading=(\n",
    "            *2\n",
    "            * (\n",
    "                Piecewise(\n",
    "                    (\n",
    "                        (1.2 * patch / width, Uniform(round(1.2 * n))),\n",
    "                        (1 - 1.2 * patch / width, Geometric(7, first=patch / n)),\n",
    "                    )\n",
    "                ),\n",
    "            ),\n",
    "            Piecewise(\n",
    "                (\n",
    "                    (1 - patch / width, Geometric(7, first=patch / n, toward=\"end\")),\n",
    "                    (patch / width, Uniform(n)),\n",
    "                )\n",
    "            ),\n",
    "        ),\n",
    "    ).generate(block)\n",
    "    for n in levels\n",
    "]\n",
    "sphere_meshes = [\n",
    "    TetrahedralMesher(\n",
    "        target_size=radius / 4,\n",
    "        size_field=lambda points: np.clip(\n",
    "            patch / (1.08 * n) + 0.35 * (np.linalg.norm(points, axis=1) - 1.15 * patch),\n",
    "            patch / (1.08 * n),\n",
    "            radius / 4,\n",
    "        ),\n",
    "    ).generate(sphere)\n",
    "    for n in levels\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=18, azimuth=225)\n",
    "fig = plots.figure(1, 3, size=(18, 6))\n",
    "plots.geometry(\n",
    "    [block.named(\"block\"), sphere.named(\"sphere\")],\n",
    "    camera=view,\n",
    "    title=\"Quarter of the block and of the lower half sphere\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    block_meshes[0],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Block: {block_meshes[0].cell_count} hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.mesh(\n",
    "    sphere_meshes[0],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Sphere: {sphere_meshes[0].cell_count} tetrahedra\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Both bodies are steel. The platen on the equator of the sphere is moved towards the block in five\n",
    "steps up to the approach $a^2/R$; the contact conditions are solved on each of the three levels."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "youngs_modulus, poisson_ratio = 210e9, 0.30\n",
    "contact_modulus = youngs_modulus / (2 * (1 - poisson_ratio**2))\n",
    "approaches = patch**2 / radius * np.linspace(0.4, 1.0, 5)\n",
    "steel = SmallStrainSolid(\n",
    "    youngs_modulus=youngs_modulus, poisson_ratio=poisson_ratio, kinematics=\"volume\"\n",
    ")\n",
    "results = [\n",
    "    MortarContact(\n",
    "        slave=MortarBody(\n",
    "            solid=steel,\n",
    "            mesh=block_mesh,\n",
    "            boundary=lower.z_max,\n",
    "            displacements=(\n",
    "                (lower.x_min, \"x\", 0.0),\n",
    "                (lower.y_min, \"y\", 0.0),\n",
    "                (lower.z_min, \"z\", 0.0),\n",
    "            ),\n",
    "            tractions=((lower.x_max, (0.0, 0.0, 0.0)), (lower.y_max, (0.0, 0.0, 0.0))),\n",
    "        ),\n",
    "        master=MortarBody(\n",
    "            solid=steel,\n",
    "            mesh=sphere_mesh,\n",
    "            boundary=upper.surface,\n",
    "            displacements=(\n",
    "                (upper.plane_x, \"x\", 0.0),\n",
    "                (upper.plane_y, \"y\", 0.0),\n",
    "                (upper.equator, \"z\", 0.0),\n",
    "            ),\n",
    "        ),\n",
    "        normal=(0.0, 0.0, -1.0),\n",
    "    ).solve(\n",
    "        times=tuple(range(1, len(approaches) + 1)),\n",
    "        normal_offset=lambda t: -approaches[int(round(t)) - 1],\n",
    "    )\n",
    "    for block_mesh, sphere_mesh in zip(block_meshes, sphere_meshes)\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Contact patch and pressure\n",
    "\n",
    "The transmitted force follows from the contact pressures; the factor 4 completes the quarter\n",
    "model. Hertz's contact radius and peak pressure are taken for the force of each level, and the\n",
    "contact radius of the simulation from the second moment of the pressure."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "forces = [4 * result.normal_pressure @ result.multiplier_measures for result in results]\n",
    "hertz_radius = [\n",
    "    (3 * force[-1] * radius / (4 * contact_modulus)) ** (1 / 3) for force in forces\n",
    "]\n",
    "hertz_peak = [\n",
    "    3 * force[-1] / (2 * np.pi * a**2) for force, a in zip(forces, hertz_radius)\n",
    "]\n",
    "distance = [\n",
    "    np.hypot(result.multiplier_coordinates[:, 0], result.multiplier_coordinates[:, 1])\n",
    "    for result in results\n",
    "]\n",
    "pressure = [result.normal_pressure[-1] for result in results]\n",
    "contact_radius = [\n",
    "    np.sqrt(\n",
    "        2.5\n",
    "        * (result.multiplier_measures @ (p * r**2))\n",
    "        / (result.multiplier_measures @ p)\n",
    "    )\n",
    "    for result, p, r in zip(results, pressure, distance)\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Stresses below the contact\n",
    "\n",
    "The displacement of the block is differentiated in its finite-element space at the centres of\n",
    "the cells next to the axis; `strain_from_gradient` gives the strain, Hooke's law the stress and\n",
    "`max_shear` the largest shear stress. A parabola through the three samples around the maximum\n",
    "gives its size and depth."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "lame = youngs_modulus * poisson_ratio / ((1 + poisson_ratio) * (1 - 2 * poisson_ratio))\n",
    "shear_modulus = youngs_modulus / (2 * (1 + poisson_ratio))\n",
    "hooke = lambda strain: 2 * shear_modulus * strain + lame * np.trace(\n",
    "    strain, axis1=1, axis2=2\n",
    ")[:, None, None] * np.eye(3)\n",
    "spaces = [\n",
    "    FiniteElement(element=Lagrange(order=1)).bind_space(mesh) for mesh in block_meshes\n",
    "]\n",
    "across = [\n",
    "    np.unique(np.round(np.asarray(mesh.coordinates)[:, 0], 12)) for mesh in block_meshes\n",
    "]\n",
    "down = [\n",
    "    -np.unique(np.round(np.asarray(mesh.coordinates)[:, 2], 12))[::-1]\n",
    "    for mesh in block_meshes\n",
    "]\n",
    "depths = [\n",
    "    ((nodes[1:] + nodes[:-1]) / 2)[(nodes[1:] + nodes[:-1]) / 2 < 3 * a]\n",
    "    for nodes, a in zip(down, hertz_radius)\n",
    "]\n",
    "axis_stress = [\n",
    "    hooke(\n",
    "        strain_from_gradient(\n",
    "            space.gradient(\n",
    "                result.slave_displacement[-1],\n",
    "                np.column_stack(\n",
    "                    (\n",
    "                        np.full_like(depth, nodes[1] / 2),\n",
    "                        np.full_like(depth, nodes[1] / 2),\n",
    "                        -depth,\n",
    "                    )\n",
    "                ),\n",
    "            )\n",
    "        )\n",
    "    )\n",
    "    for space, result, depth, nodes in zip(spaces, results, depths, across)\n",
    "]\n",
    "axis_shear = [\n",
    "    max_shear(voigt(stress)) / peak for stress, peak in zip(axis_stress, hertz_peak)\n",
    "]\n",
    "parabolas = [\n",
    "    np.polyfit(depth[k - 1 : k + 2] / a, shear[k - 1 : k + 2], 2)\n",
    "    for depth, shear, a in zip(depths, axis_shear, hertz_radius)\n",
    "    for k in [shear.argmax()]\n",
    "]\n",
    "largest_shear = [c[2] - c[1] ** 2 / (4 * c[0]) for c in parabolas]\n",
    "hertz_axial = lambda s: -1 / (1 + s**2)\n",
    "hertz_radial = lambda s: -(1 + poisson_ratio) * (1 - s * np.arctan2(1.0, s)) + 0.5 / (\n",
    "    1 + s**2\n",
    ")\n",
    "scale = np.linspace(0.01, 3.0, 600)\n",
    "hertz_shear = (hertz_radial(scale) - hertz_axial(scale)) / 2\n",
    "\n",
    "print(\n",
    "    f\"finest level: transmitted force {forces[-1][-1]:.1f} N, Hertz contact radius {1e3 * hertz_radius[-1]:.4f} mm, \"\n",
    "    f\"peak pressure {hertz_peak[-1] / 1e9:.3f} GPa\"\n",
    ")\n",
    "print(\n",
    "    \"cells per contact radius   hexahedra   tetrahedra   a / a_Hertz   largest shear / p0   at the depth z / a\"\n",
    ")\n",
    "for n, block_mesh, sphere_mesh, a, a_hertz, shear, c in zip(\n",
    "    levels,\n",
    "    block_meshes,\n",
    "    sphere_meshes,\n",
    "    contact_radius,\n",
    "    hertz_radius,\n",
    "    largest_shear,\n",
    "    parabolas,\n",
    "):\n",
    "    print(\n",
    "        f\"{n:24d} {block_mesh.cell_count:11d} {sphere_mesh.cell_count:12d} {a / a_hertz:13.4f} {shear:20.4f} {-c[1] / (2 * c[0]):19.3f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"Hertz: largest shear {hertz_shear.max():.4f} p0 at the depth {scale[hertz_shear.argmax()]:.3f} a\"\n",
    ")\n",
    "study = convergence(\n",
    "    [a / a_hertz for a, a_hertz in zip(contact_radius, hertz_radius)],\n",
    "    [patch / n for n in levels],\n",
    ")\n",
    "print(\n",
    "    f\"contact radius: change between the two finest levels {100 * study.change:.2f} %\"\n",
    ")\n",
    "relative_depth = depths[-1] / hertz_radius[-1]\n",
    "print(\n",
    "    f\"axis stresses on the finest level, largest deviation from Hertz for z < 3a: \"\n",
    "    f\"axial {np.abs(axis_stress[-1][:, 2, 2] / hertz_peak[-1] - hertz_axial(relative_depth)).max():.3f} p0, \"\n",
    "    f\"radial {np.abs(axis_stress[-1][:, 0, 0] / hertz_peak[-1] - hertz_radial(relative_depth)).max():.3f} p0\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Force-approach law\n",
    "\n",
    "Besides the Hertz term $\\propto F^{2/3}$ the approach of the platen contains a part that is\n",
    "linear in $F$ and belongs to the finite bodies. A fit $\\delta=c_1F^{2/3}+c_2F$ over the five\n",
    "load steps separates the two; $c_1$ is compared with Hertz."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "coefficients = np.linalg.lstsq(\n",
    "    np.column_stack((forces[-1] ** (2 / 3), forces[-1])), approaches, rcond=None\n",
    ")[0]\n",
    "hertz_coefficient = (9 / (16 * radius * contact_modulus**2)) ** (1 / 3)\n",
    "print(\n",
    "    f\"Hertz coefficient of the approach: fitted {coefficients[0]:.4e}, Hertz {hertz_coefficient:.4e} \"\n",
    "    f\"({100 * (coefficients[0] / hertz_coefficient - 1):+.2f} %); linear part at the largest load \"\n",
    "    f\"{100 * coefficients[1] * forces[-1][-1] / approaches[-1]:+.1f} % of the approach\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The largest shear stress in the block in a section through the axis, the contact pressure at\n",
    "every contact node, the stresses on the axis, the force-approach law and the mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "centres = [(nodes[1:] + nodes[:-1]) / 2 for nodes in (across[-1], down[-1])]\n",
    "x, z = (centre[centre < 2.5 * hertz_radius[-1]] for centre in centres)\n",
    "section_points = np.column_stack(\n",
    "    (\n",
    "        np.repeat(x, len(z)),\n",
    "        np.full(len(x) * len(z), across[-1][1] / 2),\n",
    "        -np.tile(z, len(x)),\n",
    "    )\n",
    ")\n",
    "section_shear = max_shear(\n",
    "    voigt(\n",
    "        hooke(\n",
    "            strain_from_gradient(\n",
    "                spaces[-1].gradient(results[-1].slave_displacement[-1], section_points)\n",
    "            )\n",
    "        )\n",
    "    )\n",
    ")\n",
    "section_shear = section_shear.reshape(len(x), len(z)) / hertz_peak[-1]\n",
    "ellipse, load_line = np.linspace(0, 1.3, 300), np.linspace(\n",
    "    0, 1.05 * forces[-1][-1], 200\n",
    ")\n",
    "fig = plots.figure(\n",
    "    layout=[[\"map\", \"map\", \"pressure\"], [\"axis\", \"law\", \"study\"]], size=(18, 11)\n",
    ")\n",
    "plots.heatmap(\n",
    "    np.concatenate((-x[::-1], x)) / hertz_radius[-1],\n",
    "    -z[::-1] / hertz_radius[-1],\n",
    "    np.concatenate((section_shear[::-1, ::-1], section_shear[:, ::-1])),\n",
    "    limits=(0, 0.32),\n",
    "    contours=[0.31],\n",
    "    label=\"largest shear stress / p0\",\n",
    "    xlabel=\"x / a\",\n",
    "    ylabel=\"z / a\",\n",
    "    title=\"Block below the contact (line: 0.31)\",\n",
    "    ax=fig[\"map\"],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"simulation, {n} cells per a\": (r / a, p / peak)\n",
    "        for n, r, p, a, peak in zip(\n",
    "            levels, distance, pressure, hertz_radius, hertz_peak\n",
    "        )\n",
    "    },\n",
    "    reference={\"Hertz\": (ellipse, np.sqrt(np.clip(1 - ellipse**2, 0, None)))},\n",
    "    xlimits=(0, 1.3),\n",
    "    xlabel=\"r / a\",\n",
    "    ylabel=\"p / p0\",\n",
    "    title=\"Contact pressure at every contact node\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[\"pressure\"],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"axial\": (-axis_stress[-1][:, 2, 2] / hertz_peak[-1], relative_depth),\n",
    "        \"radial\": (-axis_stress[-1][:, 0, 0] / hertz_peak[-1], relative_depth),\n",
    "        \"largest shear\": (axis_shear[-1], relative_depth),\n",
    "    },\n",
    "    reference={\n",
    "        \"axial\": (-hertz_axial(scale), scale),\n",
    "        \"radial\": (-hertz_radial(scale), scale),\n",
    "        \"largest shear\": (hertz_shear, scale),\n",
    "    },\n",
    "    ylimits=(3, 0),\n",
    "    xlabel=\"stress / p0 (compression positive)\",\n",
    "    ylabel=\"depth below the contact centre z / a\",\n",
    "    title=\"Stresses on the axis: simulation (markers), Hertz (dashed)\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[\"axis\"],\n",
    ")\n",
    "plots.line(\n",
    "    load_line,\n",
    "    {\n",
    "        \"fit\": 1e6\n",
    "        * (coefficients[0] * load_line ** (2 / 3) + coefficients[1] * load_line)\n",
    "    },\n",
    "    points={\"simulation\": (forces[-1], 1e6 * approaches)},\n",
    "    reference={\"Hertz term\": 1e6 * hertz_coefficient * load_line ** (2 / 3)},\n",
    "    xlabel=\"force on the full sphere [N]\",\n",
    "    ylabel=\"approach [µm]\",\n",
    "    title=\"Force-approach law\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[\"law\"],\n",
    ")\n",
    "plots.line(\n",
    "    levels,\n",
    "    {\n",
    "        \"contact radius\": [\n",
    "            100 * (a / a_hertz - 1) for a, a_hertz in zip(contact_radius, hertz_radius)\n",
    "        ],\n",
    "        \"largest shear stress\": [\n",
    "            100 * (shear / hertz_shear.max() - 1) for shear in largest_shear\n",
    "        ],\n",
    "        \"largest nodal pressure\": [\n",
    "            100 * (p.max() / peak - 1) for p, peak in zip(pressure, hertz_peak)\n",
    "        ],\n",
    "    },\n",
    "    hlines=0.0,\n",
    "    markers=True,\n",
    "    xlabel=\"cells per contact radius\",\n",
    "    ylabel=\"deviation from Hertz [%]\",\n",
    "    title=\"Mesh study\",\n",
    "    ax=fig[\"study\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the radius of the sphere in `hertz_sphere_on_flat_3d_geometry.py`, write the STEP files\n",
    "again and follow the contact radius; give the two bodies different materials, where\n",
    "$1/E^*=(1-\\nu_1^2)/E_1+(1-\\nu_2^2)/E_2$; or add a friction coefficient and a tangential load."
   ]
  }
 ]
}
