{
 "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": [
    "# Thermally loaded beam with 3D beam elements\n",
    "\n",
    "A straight steel beam of length $L=3$ m with a square $40\\times40$ mm cross-section is heated\n",
    "unevenly. Across its height the bottom face is $\\Delta T_z=50$ K warmer than the top face, across its\n",
    "width the face at $+y$ is $\\Delta T_y=50$ K warmer than the face at $-y$, and the mean temperature lies\n",
    "50 K above the stress-free reference. The temperature therefore varies linearly over the section,\n",
    "\n",
    "$$T(y,z)-T_\\text{ref}=\\Delta T_m+g_y\\,y+g_z\\,z,\\qquad g_y=\\frac{\\Delta T_y}{b}=1250\\ \\text{K/m},\\quad\n",
    "  g_z=-\\frac{\\Delta T_z}{h}=-1250\\ \\text{K/m}.$$\n",
    "\n",
    "A linear temperature over the section is exactly what a beam element can carry: the mean value\n",
    "stretches the axis, the two gradients impose the free thermal curvatures $\\kappa_y=\\alpha g_y$ and\n",
    "$\\kappa_z=\\alpha g_z$. OneSimulation models the beam as a `SpatialFrame` of 3D Euler-Bernoulli beam\n",
    "elements (six degrees of freedom per joint) and applies the temperature field with\n",
    "`ThermalFrameMemberLoads.linear_temperature`; no temperature is computed, it is prescribed.\n",
    "\n",
    "| case | supports | beam theory |\n",
    "|---|---|---|\n",
    "| simply supported | $x=0$: displacements and twist held; $x=L$: transverse displacements held | statically determinate: free bending, $v(x)=\\kappa_y\\,x(L-x)/2$, $w(x)=\\kappa_z\\,x(L-x)/2$, $u(L)=\\alpha\\Delta T_mL$, no reactions |\n",
    "| clamped | both ends fully held | no displacement; axial force $N=-EA\\,\\alpha\\Delta T_m$, end moments $EI\\,\\alpha g$ about both axes |\n",
    "\n",
    "Steel: $E=210$ GPa, $G=E/2.6$, $\\alpha=11\\times10^{-6}$ 1/K.\n",
    "\n",
    "**Reference** (B. A. Boley and J. H. Weiner, *Theory of Thermal Stresses*, Wiley 1960, §9.2;\n",
    "W. C. Young and R. G. Budynas, *Roark's Formulas for Stress and Strain*, 7th ed., McGraw-Hill 2002,\n",
    "§8.1, thermal loading of beams). The midspan deflection of the simply supported beam is\n",
    "\n",
    "$$|v(L/2)|=|w(L/2)|=\\frac{\\alpha\\,g\\,L^2}{8}=15.47\\ \\text{mm},\\qquad\n",
    "  \\sqrt{v^2+w^2}=21.88\\ \\text{mm}.$$"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.meshing import BeamSection\n",
    "from onesim.physics.solid_mechanics import (\n",
    "    FrameMember,\n",
    "    SpatialFrame,\n",
    "    ThermalFrameMemberLoads,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Beam model\n",
    "\n",
    "The beam is divided into $n$ equal elements; three subdivisions are compared. The section supplies\n",
    "area and second moments."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "length, youngs_modulus, alpha = 3.0, 210e9, 11e-6\n",
    "section = BeamSection(\"rectangle\", (0.04, 0.04))\n",
    "inertia_y, inertia_z = section.inertia\n",
    "beam = lambda n: SpatialFrame(\n",
    "    joints=np.column_stack(\n",
    "        (np.linspace(0, length, n + 1), np.zeros(n + 1), np.zeros(n + 1))\n",
    "    ),\n",
    "    members=tuple(\n",
    "        FrameMember(\n",
    "            name=f\"element {i}\",\n",
    "            start=i,\n",
    "            end=i + 1,\n",
    "            youngs_modulus=youngs_modulus,\n",
    "            area=section.area,\n",
    "            bending_inertia_y=inertia_y,\n",
    "            bending_inertia_z=inertia_z,\n",
    "            shear_modulus=youngs_modulus / 2.6,\n",
    "            torsion_constant=0.1406 * 0.04**4,\n",
    "        )\n",
    "        for i in range(n)\n",
    "    ),\n",
    ")\n",
    "temperature = ThermalFrameMemberLoads.linear_temperature(\n",
    "    temperature=343.15,\n",
    "    reference_temperature=293.15,\n",
    "    expansion_coefficient=alpha,\n",
    "    gradient=(1250.0, -1250.0),\n",
    ")\n",
    "simply_supported = lambda n: (\n",
    "    *((0, dof, 0.0) for dof in (\"x\", \"y\", \"z\", \"rx\")),\n",
    "    (n, \"y\", 0.0),\n",
    "    (n, \"z\", 0.0),\n",
    ")\n",
    "clamped = lambda n: tuple(\n",
    "    (joint, dof, 0.0) for joint in (0, n) for dof in (\"x\", \"y\", \"z\", \"rx\", \"ry\", \"rz\")\n",
    ")\n",
    "runs = {\n",
    "    n: beam(n).solve(supports=simply_supported(n), member_loads=temperature)\n",
    "    for n in (2, 4, 12)\n",
    "}\n",
    "held = beam(12).solve(supports=clamped(12), member_loads=temperature)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with beam theory"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "camber = lambda x, gradient: alpha * gradient * x * (length - x) / 2\n",
    "print(\n",
    "    \"elements   v(L/2) [mm]   w(L/2) [mm]   total [mm]   u(L) [mm]   largest deviation from beam theory at the joints\"\n",
    ")\n",
    "for n, result in runs.items():\n",
    "    x = np.linspace(0, length, n + 1)\n",
    "    exact = np.column_stack((alpha * 50.0 * x, camber(x, 1250.0), camber(x, -1250.0)))\n",
    "    mid = result.displacement[n // 2]\n",
    "    print(\n",
    "        f\"{n:8d} {1e3 * mid[1]:13.4f} {1e3 * mid[2]:13.4f} {1e3 * np.hypot(mid[1], mid[2]):12.4f} {1e3 * result.displacement[-1, 0]:11.4f}\"\n",
    "        f\" {np.abs(result.displacement - exact).max():14.1e} m\"\n",
    "    )\n",
    "print(\n",
    "    f\"beam theory {1e3 * camber(length / 2, 1250.0):11.4f} {1e3 * camber(length / 2, -1250.0):13.4f} \"\n",
    "    f\"{1e3 * np.sqrt(2) * camber(length / 2, 1250.0):12.4f} {1e3 * alpha * 50.0 * length:11.4f}\"\n",
    ")\n",
    "print(\n",
    "    f\"simply supported: largest reaction force {np.abs(runs[12].reaction_force).max():.1e} N, \"\n",
    "    f\"largest reaction moment {np.abs(runs[12].reaction_moment).max():.1e} N m (statically determinate, free bending)\"\n",
    ")\n",
    "\n",
    "axial = youngs_modulus * section.area * alpha * 50.0\n",
    "moment = youngs_modulus * inertia_y * alpha * 1250.0\n",
    "reactions = {\n",
    "    \"axial force [kN]\": (abs(held.reaction_force[0, 0]) / 1e3, axial / 1e3),\n",
    "    \"moment about y [N m]\": (abs(held.reaction_moment[0, 1]), moment),\n",
    "    \"moment about z [N m]\": (abs(held.reaction_moment[0, 2]), moment),\n",
    "}\n",
    "print(\"clamped beam, reactions at x = 0 (magnitudes)   simulation    beam theory\")\n",
    "for name, (value, exact) in reactions.items():\n",
    "    print(f\"{name:44s} {value:12.3f} {exact:14.3f}\")\n",
    "print(f\"clamped beam: largest displacement {np.abs(held.displacement).max():.1e} m\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: the deflection of the simply supported beam towards the warm side ($+y$) and towards the warm\n",
    "underside ($-z$), at the joints of the 12-element model, against the beam-theory parabola. Right:\n",
    "the reactions of the clamped beam that hold back the thermal elongation and curvatures."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = np.linspace(0, length, 200)\n",
    "joints = np.linspace(0, length, 13)\n",
    "fig = plots.figure(1, 2, size=(14, 4.8))\n",
    "plots.line(\n",
    "    points={\n",
    "        \"v (towards +y)\": (joints, 1e3 * runs[12].displacement[:, 1]),\n",
    "        \"w (along z)\": (joints, 1e3 * runs[12].displacement[:, 2]),\n",
    "    },\n",
    "    reference={\n",
    "        \"v (towards +y)\": (fine, 1e3 * camber(fine, 1250.0)),\n",
    "        \"w (along z)\": (fine, 1e3 * camber(fine, -1250.0)),\n",
    "    },\n",
    "    xlabel=\"position along the beam x [m]\",\n",
    "    ylabel=\"deflection [mm]\",\n",
    "    title=\"Simply supported beam (markers) and beam theory (dashed)\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.bars(\n",
    "    [\n",
    "        \"axial force / 10 [kN]\",\n",
    "        \"moment about y [N m] / 100\",\n",
    "        \"moment about z [N m] / 100\",\n",
    "    ],\n",
    "    {\n",
    "        \"simulation\": [\n",
    "            abs(held.reaction_force[0, 0]) / 1e4,\n",
    "            abs(held.reaction_moment[0, 1]) / 100,\n",
    "            abs(held.reaction_moment[0, 2]) / 100,\n",
    "        ]\n",
    "    },\n",
    "    reference={\"beam theory\": [axial / 1e4, moment / 100, moment / 100]},\n",
    "    ylabel=\"magnitude (scaled)\",\n",
    "    title=\"Clamped beam: reactions at x = 0\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Give the gradients different values, or let the temperature vary in time with the `time` argument of\n",
    "`linear_temperature`: the beam follows quasi-statically. Holding only one end against rotation turns\n",
    "the free curvature into a cantilever deflection $\\kappa L^2/2$ at the tip."
   ]
  }
 ]
}
