{
 "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": [
    "# Cross-section properties of standard steel beams\n",
    "\n",
    "Beam and frame models need a handful of numbers per cross-section: the area $A$, the second\n",
    "moments $I$, the torsion constant $J$, the position of the shear centre and, for open sections,\n",
    "the warping constant $\\Gamma$. Area and second moments are plain integrals over the section.\n",
    "Torsion and shear centre need the Saint-Venant warping function $\\omega$, the solution of\n",
    "\n",
    "$$\\nabla^2\\omega=0\\ \\text{in the section},\\qquad \\frac{\\partial\\omega}{\\partial n}=y\\,n_x-x\\,n_y\\ \\text{on its boundary},$$\n",
    "\n",
    "with $J=\\int\\big|\\nabla\\omega+(-y,x)\\big|^2\\,dA$. The shear centre is the point about which the\n",
    "warping function is orthogonal to $x$ and $y$; the warping constant is $\\Gamma=\\int\\omega_s^2\\,dA$\n",
    "of the warping function about it. All of them follow from one 2D finite-element solution.\n",
    "\n",
    "**Setup.** Three sections: an IPE 200 ($h=200$ mm, $b=100$ mm, $t_w=5.6$ mm, $t_f=8.5$ mm, root\n",
    "radius 12 mm), a welded box 120 × 60 × 5 mm with sharp corners and a lipless channel 140 × 60 mm\n",
    "with 4 mm walls. Each comes as a short prism from its own CAD file,\n",
    "`beam_section_properties_<name>.step`, written by `beam_section_properties_geometry.py` with the\n",
    "CAD objects of OneSimulation; the computation uses the mid-plane section. A combined load on the\n",
    "IPE 200: normal force $N=100$ kN, bending moments $M_x=30$ kN m (strong axis) and $M_y=3$ kN m,\n",
    "torque $T=50$ N m.\n",
    "\n",
    "**Reference.** IPE 200: the section table of EN 10365 / the producer's catalogue,\n",
    "$A=28.48$ cm², $I_y=1943$ cm⁴, $I_z=142.4$ cm⁴, $I_t=6.98$ cm⁴, $I_w=12\\,990$ cm⁶. Box: exact\n",
    "$A$ and $I$ of two rectangles; Bredt's thin-walled torsion constant $J=4A_m^2t/s$ with the area\n",
    "$A_m$ and perimeter $s$ of the wall centre line. Channel: thin-walled theory with centre-line\n",
    "dimensions $b$, $h$ (Timoshenko and Gere, *Theory of Elastic Stability*; Pilkey, *Formulas for\n",
    "Stress, Strain, and Structural Matrices*): $e=3b^2/(6b+h)$ from the web, $J=(2b+h)t^3/3$ and\n",
    "$\\Gamma=t\\,b^3h^2(3b+2h)/\\big(12(6b+h)\\big)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.physics.solid_mechanics import section_properties\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 each prism; `section` cuts its mid-plane. Quadratic triangles of 1.5 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "names = [\"ipe\", \"box\", \"channel\"]\n",
    "parts = {name: load(f\"beam_section_properties_{name}.step\") for name in names}\n",
    "sections = {\n",
    "    name: part.section((0, 0, 1), origin=(0, 0, part.size[2] / 2))\n",
    "    for name, part in parts.items()\n",
    "}\n",
    "meshes = {\n",
    "    name: TriangularMesher(target_size=0.0015).generate(section)\n",
    "    for name, section in sections.items()\n",
    "}\n",
    "\n",
    "titles = {\n",
    "    \"ipe\": \"IPE 200\",\n",
    "    \"box\": \"Box 120 × 60 × 5\",\n",
    "    \"channel\": \"Channel 140 × 60 × 4\",\n",
    "}\n",
    "fig = plots.figure(2, 3, size=(17, 10))\n",
    "for k, name in enumerate(names):\n",
    "    plots.geometry(\n",
    "        parts[name],\n",
    "        labels=False,\n",
    "        camera=plots.Camera(elevation=60, azimuth=-70),\n",
    "        title=f\"{titles[name]} (short prism)\",\n",
    "        ax=fig[k],\n",
    "    )\n",
    "    plots.mesh(\n",
    "        meshes[name],\n",
    "        groups=(\"all\",),\n",
    "        legend=False,\n",
    "        title=f\"Section: {meshes[name].cell_count} quadratic triangles\",\n",
    "        ax=fig[3 + k],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Section properties\n",
    "\n",
    "`section_properties` integrates area and second moments on the mesh and solves the warping\n",
    "function on the quadratic space."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "props = {name: section_properties(mesh) for name, mesh in meshes.items()}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with tables and thin-walled theory\n",
    "\n",
    "For each section the computed values next to the reference; for the channel the shear centre is\n",
    "measured from the centre line of the web."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "t, b, h = 0.004, 0.058, 0.136\n",
    "references = {\n",
    "    \"ipe\": {\n",
    "        \"A [cm²]\": 28.48,\n",
    "        \"I_x [cm⁴]\": 1943.0,\n",
    "        \"I_y [cm⁴]\": 142.4,\n",
    "        \"J [cm⁴]\": 6.98,\n",
    "        \"Γ [cm⁶]\": 12990.0,\n",
    "    },\n",
    "    \"box\": {\n",
    "        \"A [cm²]\": 17.0,\n",
    "        \"I_x [cm⁴]\": (0.120 * 0.060**3 - 0.110 * 0.050**3) / 12 * 1e8,\n",
    "        \"I_y [cm⁴]\": (0.060 * 0.120**3 - 0.050 * 0.110**3) / 12 * 1e8,\n",
    "        \"J [cm⁴]\": 4 * (0.115 * 0.055) ** 2 * 0.005 / (2 * (0.115 + 0.055)) * 1e8,\n",
    "    },\n",
    "    \"channel\": {\n",
    "        \"J [cm⁴]\": (2 * b + h) * t**3 / 3 * 1e8,\n",
    "        \"Γ [cm⁶]\": t * b**3 * h**2 * (3 * b + 2 * h) / (12 * (6 * b + h)) * 1e12,\n",
    "        \"e [mm]\": 3 * b**2 / (6 * b + h) * 1e3,\n",
    "    },\n",
    "}\n",
    "computed = {\n",
    "    name: {\n",
    "        \"A [cm²]\": p.area * 1e4,\n",
    "        \"I_x [cm⁴]\": p.second_moments[0] * 1e8,\n",
    "        \"I_y [cm⁴]\": p.second_moments[1] * 1e8,\n",
    "        \"J [cm⁴]\": p.torsion_constant * 1e8,\n",
    "        \"Γ [cm⁶]\": p.warping_constant * 1e12,\n",
    "        \"e [mm]\": (0.002 - p.shear_centre[0]) * 1e3,\n",
    "    }\n",
    "    for name, p in props.items()\n",
    "}\n",
    "for name in names:\n",
    "    print(\n",
    "        f\"{titles[name]}: centroid ({1e3 * props[name].centroid[0]:.2f}, {1e3 * props[name].centroid[1]:.2f}) mm, \"\n",
    "        f\"shear centre ({1e3 * props[name].shear_centre[0]:.2f}, {1e3 * props[name].shear_centre[1]:.2f}) mm\"\n",
    "    )\n",
    "    for quantity, reference in references[name].items():\n",
    "        print(\n",
    "            f\"   {quantity:10s} computed {computed[name][quantity]:12.4g}   reference {reference:12.4g}   {100 * (computed[name][quantity] / reference - 1):+7.2f} %\"\n",
    "        )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Stresses in the IPE 200\n",
    "\n",
    "The normal stress of the combined load over the section and its extreme value, and the largest\n",
    "torsional shear stress from the warping solution against the thin-walled estimate\n",
    "$\\tau=T\\,t_f/J$ in the flange."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "ipe = props[\"ipe\"]\n",
    "nodes = meshes[\"ipe\"].coordinates\n",
    "sigma = ipe.normal_stress(nodes, normal_force=100e3, bending_moments=(30e3, 3e3))\n",
    "corner = ipe.normal_stress(\n",
    "    [[-0.050, 0.100]], normal_force=100e3, bending_moments=(30e3, 3e3)\n",
    ")[0]\n",
    "shear = np.linalg.norm(ipe.torsion_shear(50.0), axis=1)\n",
    "print(\n",
    "    f\"normal stress: {sigma.min() / 1e6:.1f} to {sigma.max() / 1e6:.1f} MPa; at the flange tip (-50, 100) mm {corner / 1e6:.1f} MPa \"\n",
    "    f\"(N/A + M_x h/2I_x + M_y b/2I_y with the table values: {(100e3 / 28.48e-4 + 30e3 * 0.1 / 1943e-8 + 3e3 * 0.05 / 142.4e-8) / 1e6:.1f} MPa)\"\n",
    ")\n",
    "flange = (np.abs(ipe.points[:, 0]) > 0.030) & (np.abs(ipe.points[:, 0]) < 0.040)\n",
    "print(\n",
    "    f\"torsional shear in the flanges 30-40 mm from the web: up to {shear[flange].max() / 1e6:.2f} MPa, thin-walled estimate \"\n",
    "    f\"{50.0 * 0.0085 / ipe.torsion_constant / 1e6:.2f} MPa; largest {shear.max() / 1e6:.2f} MPa at ({1e3 * ipe.points[np.argmax(shear), 0]:.1f}, \"\n",
    "    f\"{1e3 * ipe.points[np.argmax(shear), 1]:.1f}) mm, where web, fillet and flange meet\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left the normal stress over the IPE 200 for the combined load; the neutral axis is inclined\n",
    "because of the weak-axis moment. Right the deviation of the computed properties of all three\n",
    "sections from their references; the larger deviations are those of the thin-walled formulas."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "ratios = {\n",
    "    f\"{titles[name]}: {quantity.split()[0]}\": computed[name][quantity] / reference\n",
    "    for name in names\n",
    "    for quantity, reference in references[name].items()\n",
    "}\n",
    "fig = plots.figure(1, 2, size=(17, 7))\n",
    "plots.heatmap(\n",
    "    nodes[:, 0] * 1e3,\n",
    "    nodes[:, 1] * 1e3,\n",
    "    sigma / 1e6,\n",
    "    triangles=np.asarray(meshes[\"ipe\"].cells),\n",
    "    contours=12,\n",
    "    centre=0.0,\n",
    "    label=\"normal stress [MPa]\",\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"y [mm]\",\n",
    "    title=\"IPE 200 under N, M_x and M_y\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.bars(\n",
    "    list(ratios),\n",
    "    {\"deviation from the reference\": [100 * (value - 1) for value in ratios.values()]},\n",
    "    horizontal=True,\n",
    "    ylabel=\"deviation [%]\",\n",
    "    title=\"Section properties against tables and thin-walled theory\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Feed the computed values into `FrameMember(area=..., bending_inertia_y=..., torsion_constant=...,\n",
    "shear_centre=...)` for a frame model, add a second material as a separate region for a composite\n",
    "section, or cut the section from any imported beam profile."
   ]
  }
 ]
}
