{
 "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 line contact: a rigid cylinder pressed into an elastic block\n",
    "\n",
    "A long rigid cylinder of radius $R$ is pressed into a linear-elastic block\n",
    "(Young's modulus $E$, Poisson's ratio $\\nu$) in plane strain. Hertz's theory\n",
    "for the elastic half-space predicts that a force per unit length $F$ is\n",
    "transmitted through a strip of half-width $b$ with a semi-elliptical\n",
    "pressure distribution,\n",
    "\n",
    "$$b=\\sqrt{\\frac{4FR}{\\pi E^*}},\\qquad\n",
    "  p(x)=p_0\\sqrt{1-\\frac{x^2}{b^2}},\\qquad\n",
    "  p_0=\\frac{2F}{\\pi b},\\qquad E^*=\\frac{E}{1-\\nu^2}.$$\n",
    "\n",
    "The block comes from the CAD file `hertz_line_contact.step`, written by\n",
    "`hertz_line_contact_geometry.py` with the CAD objects of OneSimulation. The plane-strain model\n",
    "lives on its cross-section, which keeps the face names `x_min`, `x_max`, `y_min` and `y_max`.\n",
    "\n",
    "In plane strain the force-approach relation depends on the depth of the block, but the pressure\n",
    "distribution is set by the local geometry alone. The comparison therefore takes the force $F$\n",
    "transmitted in the simulation and checks the half-width, the peak pressure and the elliptical\n",
    "profile that Hertz predicts for that force.\n",
    "\n",
    "OneSimulation treats the contact with its **mortar formulation**: Lagrange multipliers on the\n",
    "contact trace enforce non-penetration weakly against the rigid cylinder profile."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Circle\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import cartesian\n",
    "from onesim.physics.solid_mechanics import (\n",
    "    MortarBody,\n",
    "    MortarContact,\n",
    "    SmallStrainSolid,\n",
    "    rigid_gap,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry\n",
    "\n",
    "`load` returns the solid; `section` cuts it at half thickness and returns the planar region."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "solid = load(\"hertz_line_contact.step\")\n",
    "block = solid.section((0, 0, 1), origin=(0, 0, 0.5))\n",
    "faces = block.boundaries\n",
    "width, depth = block.size[:2]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 4.5))\n",
    "plots.geometry(\n",
    "    solid,\n",
    "    selection={\n",
    "        \"contact face\": solid.boundaries.y_max,\n",
    "        \"clamped face\": solid.boundaries.y_min,\n",
    "    },\n",
    "    labels=False,\n",
    "    title=\"Elastic block\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.geometry(block, title=\"Cross-section with its named sides\", ax=fig[1])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "A soft block in dimensionless units. The bottom is clamped, the side walls are traction free and\n",
    "the top is the mortar contact trace against the rigid cylinder; the approach is imposed through\n",
    "the normal offset of the rigid profile. Two meshes of bilinear quadrilaterals are solved."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "youngs_modulus, poisson_ratio, radius, indentation = 2600.0, 0.27, 8.0, 0.032\n",
    "contact_modulus = youngs_modulus / (1 - poisson_ratio**2)\n",
    "cylinder = rigid_gap(\n",
    "    Circle(radius=radius, origin=(width / 2, depth + radius, 0.0)), (0.0, 1.0)\n",
    ")\n",
    "steel = SmallStrainSolid(\n",
    "    youngs_modulus=youngs_modulus,\n",
    "    poisson_ratio=poisson_ratio,\n",
    "    kinematics=\"plane_strain\",\n",
    ")\n",
    "\n",
    "\n",
    "def solve(cells):\n",
    "    \"\"\"Contact pressure on a mesh with `cells` quadrilaterals across the block.\"\"\"\n",
    "    mesh = cartesian(\n",
    "        geometry=block, shape=(cells, cells // 3), extents=(width, depth)\n",
    "    ).build()\n",
    "    body = MortarBody(\n",
    "        solid=steel,\n",
    "        mesh=mesh,\n",
    "        boundary=faces.y_max,\n",
    "        displacements=((faces.y_min, \"x\", 0.0), (faces.y_min, \"y\", 0.0)),\n",
    "        tractions=((faces.x_min, (0.0, 0.0)), (faces.x_max, (0.0, 0.0))),\n",
    "    )\n",
    "    return MortarContact(slave=body, normal=(0.0, -1.0), rigid_gap=cylinder).solve(\n",
    "        times=(0.0,), normal_offset=-indentation\n",
    "    )\n",
    "\n",
    "\n",
    "runs = {cells: solve(cells) for cells in (96, 192)}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with Hertz\n",
    "\n",
    "For the force transmitted on each mesh: Hertz half-width and peak pressure, and the deviation of\n",
    "the computed peak, of the half-width (from the second moment of the pressure) and of the profile."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "profiles = {}\n",
    "for cells, result in runs.items():\n",
    "    pressure, measure = result.normal_pressure[-1], result.multiplier_measures\n",
    "    x = result.multiplier_coordinates[:, 0] - width / 2\n",
    "    force = measure @ pressure\n",
    "    half_width = np.sqrt(4 * force * radius / (np.pi * contact_modulus))\n",
    "    peak = 2 * force / (np.pi * half_width)\n",
    "    hertz = peak * np.sqrt(np.maximum(0.0, 1 - (x / half_width) ** 2))\n",
    "    profiles[cells] = (x, pressure, half_width, peak)\n",
    "    print(\n",
    "        f\"{cells} x {cells // 3} cells: force {force:.3f}, Hertz half-width {half_width:.4f}, peak pressure {peak:.3f}; \"\n",
    "        f\"peak {100 * (pressure.max() / peak - 1):+.1f} %, \"\n",
    "        f\"half-width {100 * (2 * np.sqrt(measure @ (pressure * x**2) / force) / half_width - 1):+.1f} %, \"\n",
    "        f\"profile (RMS) {100 * np.sqrt(measure @ (pressure - hertz) ** 2 / (measure @ hertz**2)):.1f} %\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x, pressure, half_width, peak = profiles[192]\n",
    "ellipse = np.linspace(-1.3 * half_width, 1.3 * half_width, 400)\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"simulation, {cells} x {cells // 3} cells\": (\n",
    "            p[0][np.abs(p[0]) < 1.3 * half_width],\n",
    "            p[1][np.abs(p[0]) < 1.3 * half_width],\n",
    "        )\n",
    "        for cells, p in profiles.items()\n",
    "    },\n",
    "    reference={\n",
    "        \"Hertz ellipse for the transmitted force\": (\n",
    "            ellipse,\n",
    "            peak * np.sqrt(np.maximum(0.0, 1 - (ellipse / half_width) ** 2)),\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"position along the surface x\",\n",
    "    ylabel=\"contact pressure p\",\n",
    "    title=\"Contact pressure under the cylinder\",\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the block in `hertz_line_contact_geometry.py` and write the STEP file again: a shallower\n",
    "block changes the approach but not the pressure ellipse. Replace the rigid profile by a second\n",
    "elastic body (`master=`), or add a tangential load with `friction_coefficient` to study Coulomb\n",
    "stick-slip under the Hertz pressure."
   ]
  }
 ]
}
