{
 "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": [
    "# Pressure vessel with hemispherical heads\n",
    "\n",
    "A steel cylinder (inner radius 0.5 m, wall 25 mm, 2 m long) is closed by two hemispherical heads\n",
    "of the same wall thickness and loaded by an internal pressure of 2 MPa. Under pressure the\n",
    "cylinder wants to grow more than the head, so the junction bends the wall locally.\n",
    "\n",
    "One octant of the wall comes from the CAD file `pressure_vessel_hemispherical_heads.step` with\n",
    "the named faces `inside`, `outside`, `symmetry_x`, `symmetry_y` and `symmetry_z`; the script\n",
    "`pressure_vessel_hemispherical_heads_geometry.py` builds it as a solid of revolution with the CAD\n",
    "objects of OneSimulation.\n",
    "\n",
    "**Reference.** Far from the junction Lamé's solution holds: hoop stress\n",
    "$A+B/r^2$ and axial stress $A$ in the cylinder with $A=pa^2/(b^2-a^2)$, $B=Ab^2$, and the\n",
    "tangential stress $C\\,(1+b^3/2r^3)$ in the sphere with $C=pa^3/(b^3-a^3)$. At the junction,\n",
    "thin-shell theory adds a bending moment that decays over the length $1/\\beta$,\n",
    "\n",
    "$$M(s)=\\pm\\frac{p}{8\\beta^2}\\,e^{-\\beta|s|}\\sin\\beta|s|,\\qquad \\beta=\\frac{[3(1-\\nu^2)]^{1/4}}{\\sqrt{Rt}},$$\n",
    "\n",
    "which changes the meridional surface stresses by $\\pm6M/t^2$ (Timoshenko and\n",
    "Woinowsky-Krieger, *Theory of Plates and Shells*)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import Geometric, VolumeBlock, merge_volume_blocks\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.solid_mechanics import (\n",
    "    FixedDisplacementComponents,\n",
    "    LinearElasticity,\n",
    "    Pressure,\n",
    "    TractionFree,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\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 octant with its named faces. Four blocks of quadratic hexahedra cover it: the\n",
    "cylinder and three patches of the head. Their maps place every node on the exact cylinder and\n",
    "sphere, graded towards the junction; `merge_volume_blocks` binds them to the faces of the loaded\n",
    "part."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "vessel = load(\"pressure_vessel_hemispherical_heads.step\")\n",
    "faces = vessel.boundaries\n",
    "inner, wall, length, pressure = 0.5, 0.025, 1.0, 2.0e6\n",
    "outer, middle = inner + wall, inner + wall / 2\n",
    "\n",
    "\n",
    "def vessel_mesh(layers):\n",
    "    \"\"\"Curved hexahedral mesh with the given number of cells through the wall.\"\"\"\n",
    "\n",
    "    def head_patch(axes):\n",
    "        def patch(u, v, r):\n",
    "            direction = np.stack((np.ones_like(u), np.tan(u), np.tan(v)))[list(axes)]\n",
    "            x, y, z = r * direction / np.linalg.norm(direction, axis=0)\n",
    "            return x, y, z + length\n",
    "\n",
    "        return patch\n",
    "\n",
    "    radii, quarter = np.linspace(inner, outer, layers + 1), np.linspace(0, np.pi / 4, 5)\n",
    "    towards_pole = (\n",
    "        np.pi / 4 * Geometric(10, first=wall / 2 / middle).reference(np.pi / 4)\n",
    "    )\n",
    "    blocks = [\n",
    "        VolumeBlock(\n",
    "            lambda angle, z, r: (r * np.cos(angle), r * np.sin(angle), z),\n",
    "            np.linspace(0, np.pi / 2, 9),\n",
    "            length * Geometric(16, first=wall / 2, toward=\"end\").reference(length),\n",
    "            radii,\n",
    "        ),\n",
    "        VolumeBlock(head_patch((0, 1, 2)), quarter, towards_pole, radii),\n",
    "        VolumeBlock(head_patch((1, 0, 2)), quarter, towards_pole, radii),\n",
    "        VolumeBlock(head_patch((1, 2, 0)), quarter, quarter, radii),\n",
    "    ]\n",
    "    return merge_volume_blocks(\n",
    "        blocks,\n",
    "        vessel,\n",
    "        order=2,\n",
    "        boundary=lambda points, normal: vessel.boundary_at(\n",
    "            tuple(points.mean(axis=0)), tuple(normal), wall / 4\n",
    "        ),\n",
    "    )\n",
    "\n",
    "\n",
    "meshes = {layers: vessel_mesh(layers) for layers in (1, 2, 4)}\n",
    "from_inside = plots.Camera(elevation=25, azimuth=-135)\n",
    "fig = plots.figure(1, 2, size=(13, 7))\n",
    "plots.geometry(\n",
    "    vessel,\n",
    "    selection={\n",
    "        \"inside\": faces.inside,\n",
    "        \"symmetry_x\": faces.symmetry_x,\n",
    "        \"symmetry_z\": faces.symmetry_z,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=from_inside,\n",
    "    title=\"Octant of the vessel wall with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[2],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=from_inside,\n",
    "    title=f\"{meshes[2].cell_count} hexahedra, two through the wall\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "steel = IsotropicSolid(\n",
    "    density=7850.0,\n",
    "    specific_heat_capacity=475.0,\n",
    "    thermal_conductivity=44.5,\n",
    "    youngs_modulus=200e9,\n",
    "    poisson_ratio=0.3,\n",
    "    thermal_expansion_coefficient=12e-6,\n",
    ")\n",
    "model = LinearElasticity(domain=vessel.volume, material=steel)\n",
    "problem = Problem(\n",
    "    name=\"Pressure vessel\",\n",
    "    geometry=vessel,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        Pressure(boundary=faces.inside, physics=model, value=pressure),\n",
    "        TractionFree(boundary=faces.outside, physics=model),\n",
    "        FixedDisplacementComponents(\n",
    "            boundary=faces.symmetry_x, physics=model, components=(\"x\",)\n",
    "        ),\n",
    "        FixedDisplacementComponents(\n",
    "            boundary=faces.symmetry_y, physics=model, components=(\"y\",)\n",
    "        ),\n",
    "        FixedDisplacementComponents(\n",
    "            boundary=faces.symmetry_z, physics=model, components=(\"z\",)\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "results = {\n",
    "    layers: Simulation(problem=problem, mesh=mesh, numerics=numerics).solve_stationary()\n",
    "    for layers, mesh in meshes.items()\n",
    "}\n",
    "stress, mises = results[4].field(model.stress), results[4].field(model.von_mises_stress)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The stresses are read along the wall just inside the symmetry plane $y=0$. There the hoop\n",
    "stress is $\\sigma_{yy}$, and the meridional stress follows from rotating the tensor by the\n",
    "latitude $\\psi=s/R$ of the head."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "membrane = pressure * middle / wall\n",
    "s = np.linspace(-0.45, 0.35, 321)\n",
    "latitude = np.where(s > 0, s / middle, 0.0)\n",
    "\n",
    "\n",
    "def reference(r):\n",
    "    \"\"\"Meridional stress at the radius r along the wall: Lamé plus the thin-shell junction bending.\"\"\"\n",
    "    beta = (3 * (1 - steel.poisson_ratio**2)) ** 0.25 / np.sqrt(middle * wall)\n",
    "    lame = np.where(\n",
    "        s > 0,\n",
    "        pressure * inner**3 / (outer**3 - inner**3) * (1 + outer**3 / (2 * r**3)),\n",
    "        pressure * inner**2 / (outer**2 - inner**2),\n",
    "    )\n",
    "    moment = (\n",
    "        np.where(s > 0, -1, 1)\n",
    "        * pressure\n",
    "        / (8 * beta**2)\n",
    "        * np.exp(-beta * np.abs(s))\n",
    "        * np.sin(beta * np.abs(s))\n",
    "    )\n",
    "    return lame + np.sign(r - middle) * 6 * moment / wall**2\n",
    "\n",
    "\n",
    "def along_wall(field, r):\n",
    "    \"\"\"Meridional and hoop stress of a stress field along the wall at the radius r.\"\"\"\n",
    "    points = np.column_stack(\n",
    "        (\n",
    "            r * np.cos(latitude),\n",
    "            np.full_like(s, 1e-6),\n",
    "            length + np.where(s > 0, r * np.sin(latitude), s),\n",
    "        )\n",
    "    )\n",
    "    xx, yy, zz, _, _, xz = field.evaluate(points).T\n",
    "    return (\n",
    "        xx * np.sin(latitude) ** 2\n",
    "        + zz * np.cos(latitude) ** 2\n",
    "        - 2 * xz * np.sin(latitude) * np.cos(latitude),\n",
    "        yy,\n",
    "    )\n",
    "\n",
    "\n",
    "surfaces = {\"outer surface\": outer - 2e-5, \"inner surface\": inner + 2e-5}\n",
    "meridional = {label: along_wall(stress, r)[0] for label, r in surfaces.items()}\n",
    "hoop_far = along_wall(stress, inner + 2e-5)[1][0]\n",
    "lame_hoop = (\n",
    "    pressure * inner**2 / (outer**2 - inner**2) * (1 + outer**2 / (inner + 2e-5) ** 2)\n",
    ")\n",
    "\n",
    "print(\n",
    "    f\"hoop stress at the inner surface far from the junction: simulation {hoop_far / 1e6:.3f} MPa, Lamé {lame_hoop / 1e6:.3f} MPa\"\n",
    ")\n",
    "print(\n",
    "    f\"largest meridional stress on the outer surface of the cylinder, in units of pR/t: \"\n",
    "    f\"thin-shell theory {reference(outer)[s < 0].max() / membrane:.4f}\"\n",
    ")\n",
    "for layers, result in results.items():\n",
    "    print(\n",
    "        f\"   {layers} cell(s) through the wall: {along_wall(result.field(model.stress), outer - 2e-5)[0][s < 0].max() / membrane:.4f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The von Mises stress on the vessel with one half cut away, and the meridional stress on both\n",
    "wall surfaces along the junction: the bending flips sides between cylinder and head."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.surface(\n",
    "    mises,\n",
    "    boundary=faces.outside | faces.inside,\n",
    "    component=lambda value, position: value / 1e6,\n",
    "    subdivisions=3,\n",
    "    symmetry={\"planes\": [((0, 0, 1), (0, 0, 0)), ((1, 0, 0), (0, 0, 0))]},\n",
    "    limits=(12, 42),\n",
    "    camera=plots.Camera(elevation=22, azimuth=-58, up=\"y\"),\n",
    "    label=\"von Mises stress [MPa]\",\n",
    "    title=\"von Mises stress, half cut away\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    s / np.sqrt(middle * wall),\n",
    "    {label: values / membrane for label, values in meridional.items()},\n",
    "    reference={\n",
    "        \"outer surface\": reference(outer) / membrane,\n",
    "        \"inner surface\": reference(inner) / membrane,\n",
    "    },\n",
    "    vlines={\"junction\": 0.0},\n",
    "    xlabel=\"distance from the junction / √(R t)   (cylinder < 0 < head)\",\n",
    "    ylabel=\"meridional stress / (pR/t)\",\n",
    "    title=\"Simulation (solid) and Lamé with thin-shell bending (dashed)\",\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",
    "Give the head half the wall thickness of the cylinder in\n",
    "`pressure_vessel_hemispherical_heads_geometry.py`, as the membrane stresses suggest, and the\n",
    "junction bending grows; replace the hemisphere by a torispherical head to see the high stresses\n",
    "in its knuckle."
   ]
  }
 ]
}
