{
 "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": [
    "# Pratt truss bridge\n",
    "\n",
    "A Pratt truss is recognised by its diagonals: apart from the inclined end posts they all slant\n",
    "down towards the middle of the span. Under gravity loads this puts the long diagonals in\n",
    "**tension** and the short verticals in **compression**, which suits steel, whose slender members\n",
    "buckle in compression long before they yield in tension.\n",
    "\n",
    "The bridge has two Pratt trusses 5 m apart, six panels of 4 m and a height of 4 m. The deck\n",
    "rests on floor beams at the bottom panel points; top struts, top and bottom lateral braces and\n",
    "two portal braces in the plane of the end posts make the structure stiff across the span. In\n",
    "the usual bridge notation the bottom panel points are $L_0\\dots L_6$ and the top panel points\n",
    "$U_1\\dots U_5$:\n",
    "\n",
    "| joint | x [m] | z [m] | |\n",
    "|---|---|---|---|\n",
    "| $L_k$, $k=0\\dots6$ | $4k$ | 0 | $L_0$, $L_6$ on bearings |\n",
    "| $U_k$, $k=1\\dots5$ | $4k$ | 4 | |\n",
    "\n",
    "each at $y=+2.5$ m (north truss) and $y=-2.5$ m (south truss).\n",
    "\n",
    "| members | steel section |\n",
    "|---|---|\n",
    "| chords, end posts | tube 323.9 × 12.5 mm |\n",
    "| diagonals, verticals | tube 219.1 × 10 mm |\n",
    "| top struts, lateral and portal braces | tube 114.3 × 6 mm |\n",
    "| floor beams | I-section 600 × 300 mm, web 12 mm, flanges 20 mm |\n",
    "\n",
    "Deck and traffic load $P=150$ kN on each interior bottom panel point of each truss; steel with\n",
    "$E=210$ GPa and $G=81$ GPa.\n",
    "\n",
    "**Reference.** For a pin-jointed plane Pratt truss under panel loads the **method of sections**\n",
    "(Hibbeler, *Structural Analysis*, ch. 3) gives every member force from the bending moment\n",
    "$M(x)$ and the shear force $V$ of the equivalent simply supported beam: the chords carry\n",
    "$\\pm M/h$ about the opposite panel point, a diagonal carries $V/\\sin\\theta$, a vertical the shear\n",
    "of the neighbouring panel. The **unit-load method** gives the mid-span deflection\n",
    "$\\delta=\\sum_i N_i\\,n_i\\,L_i/(E A_i)$ with the member forces $n_i$ of a unit load at $L_3$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.meshing import BeamSection\n",
    "from onesim.physics.solid_mechanics import FrameMember, SpatialFrame\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Joints and members\n",
    "\n",
    "The joints are a table of coordinates; each member names its two end joints and its kind. The\n",
    "Pratt pattern is written once for a truss and repeated for both sides. `BeamSection` supplies\n",
    "area and second moments of the sections; the torsion constant of a thin tube is twice its\n",
    "second moment."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "panel, height, width, load, youngs_modulus, shear_modulus = (\n",
    "    4.0,\n",
    "    4.0,\n",
    "    5.0,\n",
    "    150e3,\n",
    "    210e9,\n",
    "    81e9,\n",
    ")\n",
    "sides = {\"N\": width / 2, \"S\": -width / 2}\n",
    "joints = {\n",
    "    **{f\"{s}L{k}\": (panel * k, y, 0.0) for s, y in sides.items() for k in range(7)},\n",
    "    **{\n",
    "        f\"{s}U{k}\": (panel * k, y, height)\n",
    "        for s, y in sides.items()\n",
    "        for k in range(1, 6)\n",
    "    },\n",
    "}\n",
    "pratt = {\n",
    "    \"chord\": [(f\"L{k}\", f\"L{k + 1}\") for k in range(6)]\n",
    "    + [(f\"U{k}\", f\"U{k + 1}\") for k in range(1, 5)]\n",
    "    + [(\"L0\", \"U1\"), (\"L6\", \"U5\")],\n",
    "    \"web\": [(\"U1\", \"L2\"), (\"U2\", \"L3\"), (\"U5\", \"L4\"), (\"U4\", \"L3\")]\n",
    "    + [(f\"L{k}\", f\"U{k}\") for k in range(1, 6)],\n",
    "}\n",
    "members = {\n",
    "    f\"{s}{p}{q}\": (kind, s + p, s + q)\n",
    "    for s in sides\n",
    "    for kind, pairs in pratt.items()\n",
    "    for p, q in pairs\n",
    "}\n",
    "members |= {f\"floor beam {k}\": (\"floor beam\", f\"NL{k}\", f\"SL{k}\") for k in range(7)}\n",
    "members |= {f\"strut {k}\": (\"brace\", f\"NU{k}\", f\"SU{k}\") for k in range(1, 6)}\n",
    "members |= {f\"top brace {k}\": (\"brace\", f\"NU{k}\", f\"SU{k + 1}\") for k in range(1, 5)}\n",
    "members |= {f\"bottom brace {k}\": (\"brace\", f\"NL{k}\", f\"SL{k + 1}\") for k in range(6)}\n",
    "members |= {\n",
    "    \"portal west\": (\"brace\", \"NL0\", \"SU1\"),\n",
    "    \"portal east\": (\"brace\", \"NL6\", \"SU5\"),\n",
    "}\n",
    "sections = {\n",
    "    \"chord\": BeamSection(\"pipe\", (0.16195, 0.0125)),\n",
    "    \"web\": BeamSection(\"pipe\", (0.10955, 0.010)),\n",
    "    \"brace\": BeamSection(\"pipe\", (0.05715, 0.006)),\n",
    "    \"floor beam\": BeamSection(\"I\", (0.600, 0.300, 0.012, 0.020)),\n",
    "}\n",
    "index = {name: number for number, name in enumerate(joints)}\n",
    "coordinates = np.array(list(joints.values()))\n",
    "\n",
    "drawing = np.concatenate(\n",
    "    (\n",
    "        coordinates[[[index[p], index[q]] for _, p, q in members.values()]],\n",
    "        np.full((len(members), 1, 3), np.nan),\n",
    "    ),\n",
    "    axis=1,\n",
    ").reshape(-1, 3)\n",
    "fig = plots.figure(1, 3, size=(17, 4.2))\n",
    "plots.line(\n",
    "    None,\n",
    "    {\"members\": (drawing[:, 0], drawing[:, 2])},\n",
    "    points={\"joints\": (coordinates[:, 0], coordinates[:, 2])},\n",
    "    legend=False,\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    ylimits=(-1, 5),\n",
    "    title=\"Elevation: Pratt truss\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    None,\n",
    "    {\"members\": (drawing[:, 0], drawing[:, 1])},\n",
    "    points={\"joints\": (coordinates[:, 0], coordinates[:, 1])},\n",
    "    legend=False,\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    ylimits=(-4, 4),\n",
    "    title=\"Plan: floor beams and lateral braces\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    None,\n",
    "    {\"members\": (drawing[:, 1], drawing[:, 2])},\n",
    "    points={\"joints\": (coordinates[:, 1], coordinates[:, 2])},\n",
    "    legend=False,\n",
    "    xlabel=\"y [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    xlimits=(-4, 4),\n",
    "    ylimits=(-1, 5),\n",
    "    title=\"Cross-section\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Models\n",
    "\n",
    "1. **One truss, pin-jointed**: the members of the north truss as axial bars, held in their plane.\n",
    "2. **The whole bridge, rigid-jointed**: all 66 members as Euler-Bernoulli beams joined rigidly,\n",
    "   the floor beams upright, the tubes with their full bending and torsion stiffness.\n",
    "\n",
    "Both rest on bearings at $L_0$ and $L_6$; the panel loads act at $L_1\\dots L_5$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "north = [name for name in joints if name.startswith(\"N\")]\n",
    "truss = SpatialFrame(\n",
    "    joints=coordinates[[index[name] for name in north]],\n",
    "    members=tuple(\n",
    "        FrameMember(\n",
    "            name=name,\n",
    "            start=north.index(p),\n",
    "            end=north.index(q),\n",
    "            youngs_modulus=youngs_modulus,\n",
    "            area=sections[kind].area,\n",
    "        )\n",
    "        for name, (kind, p, q) in members.items()\n",
    "        if name[0] == \"N\"\n",
    "    ),\n",
    ")\n",
    "bridge = SpatialFrame(\n",
    "    joints=coordinates,\n",
    "    members=tuple(\n",
    "        FrameMember(\n",
    "            name=name,\n",
    "            start=index[p],\n",
    "            end=index[q],\n",
    "            youngs_modulus=youngs_modulus,\n",
    "            area=sections[kind].area,\n",
    "            bending_inertia_z=sections[kind].inertia[0],\n",
    "            bending_inertia_y=sections[kind].inertia[1],\n",
    "            torsion_constant=(\n",
    "                2 * sections[kind].inertia[0]\n",
    "                if kind != \"floor beam\"\n",
    "                else (2 * 0.3 * 0.02**3 + 0.56 * 0.012**3) / 3\n",
    "            ),\n",
    "            shear_modulus=shear_modulus,\n",
    "            local_y=(\n",
    "                (0, 0, 1)\n",
    "                if joints[p][0] != joints[q][0] or kind == \"floor beam\"\n",
    "                else (1, 0, 0)\n",
    "            ),\n",
    "        )\n",
    "        for name, (kind, p, q) in members.items()\n",
    "    ),\n",
    ")\n",
    "truss_result = truss.solve(\n",
    "    supports=[\n",
    "        (north.index(\"NL0\"), \"x\", 0),\n",
    "        (north.index(\"NL0\"), \"z\", 0),\n",
    "        (north.index(\"NL6\"), \"z\", 0),\n",
    "    ]\n",
    "    + [(number, \"y\", 0) for number in range(len(north))],\n",
    "    forces={north.index(f\"NL{k}\"): (0, 0, -load) for k in range(1, 6)},\n",
    ")\n",
    "bridge_result = bridge.solve(\n",
    "    supports=[(index[\"NL0\"], c, 0) for c in \"xyz\"]\n",
    "    + [\n",
    "        (index[\"SL0\"], \"x\", 0),\n",
    "        (index[\"SL0\"], \"z\", 0),\n",
    "        (index[\"NL6\"], \"z\", 0),\n",
    "        (index[\"SL6\"], \"z\", 0),\n",
    "    ],\n",
    "    forces={index[f\"{s}L{k}\"]: (0, 0, -load) for s in sides for k in range(1, 6)},\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The method of sections for the left half of the truss (the right half mirrors it), with the\n",
    "bending moment and the shear of the equivalent beam under the given bottom-panel loads."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def method_of_sections(panel_loads):\n",
    "    \"\"\"Member forces of the left half of a symmetric Pratt truss under bottom-panel loads (tension positive).\"\"\"\n",
    "    x, reaction = panel * np.arange(7), panel_loads.sum() / 2\n",
    "    moment = [reaction * xk - panel_loads[:k] @ (xk - x[:k]) for k, xk in enumerate(x)]\n",
    "    shear, sine = reaction - np.cumsum(panel_loads)[:3], height / np.hypot(\n",
    "        panel, height\n",
    "    )\n",
    "    return {\n",
    "        \"L0L1\": moment[1] / height,\n",
    "        \"L1L2\": moment[1] / height,\n",
    "        \"L2L3\": moment[2] / height,\n",
    "        \"U1U2\": -moment[2] / height,\n",
    "        \"U2U3\": -moment[3] / height,\n",
    "        \"L0U1\": -shear[0] / sine,\n",
    "        \"U1L2\": shear[1] / sine,\n",
    "        \"U2L3\": shear[2] / sine,\n",
    "        \"L1U1\": panel_loads[1],\n",
    "        \"L2U2\": -shear[2],\n",
    "        \"L3U3\": 0.0,\n",
    "    }\n",
    "\n",
    "\n",
    "reference = method_of_sections(np.array([0, 1, 1, 1, 1, 1, 0]) * load)\n",
    "unit = method_of_sections(np.array([0, 0, 0, 1, 0, 0, 0.0]))\n",
    "area = {m: sections[members[\"N\" + m][0]].area for m in reference}\n",
    "length = {\n",
    "    m: np.linalg.norm(np.subtract(joints[\"N\" + m[2:]], joints[\"N\" + m[:2]]))\n",
    "    for m in reference\n",
    "}\n",
    "unit_load = sum(\n",
    "    (1 if m == \"L3U3\" else 2)\n",
    "    * reference[m]\n",
    "    * unit[m]\n",
    "    * length[m]\n",
    "    / (youngs_modulus * area[m])\n",
    "    for m in reference\n",
    ")\n",
    "pinned = {m: truss_result.members[\"N\" + m].local_end_actions[1] for m in reference}\n",
    "rigid = {m: bridge_result.members[\"N\" + m].local_end_actions[6] for m in reference}\n",
    "\n",
    "print(\n",
    "    \"member   method of sections [kN]   pin-jointed truss [kN]   rigid-jointed bridge [kN]   difference\"\n",
    ")\n",
    "for m in reference:\n",
    "    print(\n",
    "        f\"{m:8s} {reference[m] / 1e3:22.1f} {pinned[m] / 1e3:24.1f} {rigid[m] / 1e3:26.1f} {(rigid[m] - reference[m]) / load:+10.3f} P\"\n",
    "    )\n",
    "print(\n",
    "    f\"mid-span deflection: unit-load method {1e3 * unit_load:.3f} mm, pin-jointed truss \"\n",
    "    f\"{-1e3 * truss_result.displacement[north.index('NL3'), 2]:.3f} mm, rigid-jointed bridge \"\n",
    "    f\"{-1e3 * bridge_result.displacement[index['NL3'], 2]:.3f} mm\"\n",
    ")\n",
    "print(\n",
    "    f\"bearing reactions of the bridge: {bridge_result.reaction_force[[index[j] for j in ('NL0', 'SL0', 'NL6', 'SL6')], 2] / 1e3} kN, \"\n",
    "    f\"total load {10 * load / 1e3:.0f} kN\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Secondary bending\n",
    "\n",
    "The rigid joints make the members bend a little as the truss deflects. For a tube the largest\n",
    "bending stress follows from the resultant end moment, $\\sigma_b=M\\,r/I$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "axial_stress = {m: rigid[m] / area[m] for m in reference}\n",
    "bending_stress = {\n",
    "    m: max(\n",
    "        np.hypot(*bridge_result.members[\"N\" + m].local_end_actions[[4, 5]]),\n",
    "        np.hypot(*bridge_result.members[\"N\" + m].local_end_actions[[10, 11]]),\n",
    "    )\n",
    "    * sections[members[\"N\" + m][0]].dimensions[0]\n",
    "    / sections[members[\"N\" + m][0]].inertia[0]\n",
    "    for m in reference\n",
    "}\n",
    "for m in reference:\n",
    "    print(\n",
    "        f\"{m:8s} axial stress {axial_stress[m] / 1e6:7.1f} MPa   largest secondary bending stress {bending_stress[m] / 1e6:6.1f} MPa\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The deflected bridge (displacements magnified 100 times), the member forces of the half truss\n",
    "from the three approaches, and the axial against the secondary bending stress in the\n",
    "rigid-jointed bridge."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "deformed = np.concatenate(\n",
    "    (\n",
    "        (coordinates + 100 * bridge_result.displacement)[\n",
    "            [[index[p], index[q]] for _, p, q in members.values()]\n",
    "        ],\n",
    "        np.full((len(members), 1, 3), np.nan),\n",
    "    ),\n",
    "    axis=1,\n",
    ").reshape(-1, 3)\n",
    "fig = plots.figure(1, 3, size=(18, 5.2))\n",
    "plots.line(\n",
    "    None,\n",
    "    {\"deflected (×100)\": (deformed[:, 0], deformed[:, 2])},\n",
    "    reference={\"unloaded\": (drawing[:, 0], drawing[:, 2])},\n",
    "    ylimits=(-2.6, 5),\n",
    "    legend=\"lower center\",\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=\"Rigid-jointed bridge, elevation\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.bars(\n",
    "    list(reference),\n",
    "    {\n",
    "        \"pin-jointed truss\": [pinned[m] / 1e3 for m in reference],\n",
    "        \"rigid-jointed bridge\": [rigid[m] / 1e3 for m in reference],\n",
    "    },\n",
    "    reference={\"method of sections\": [reference[m] / 1e3 for m in reference]},\n",
    "    ylabel=\"axial force [kN]\",\n",
    "    title=\"Member forces of the left half truss\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.bars(\n",
    "    list(reference),\n",
    "    {\n",
    "        \"axial\": [axial_stress[m] / 1e6 for m in reference],\n",
    "        \"secondary bending\": [bending_stress[m] / 1e6 for m in reference],\n",
    "    },\n",
    "    ylabel=\"stress [MPa]\",\n",
    "    title=\"Rigid-jointed bridge: member stresses\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the joint table, for example eight panels or a curved top chord (a Parker truss), and the\n",
    "solver follows. Flip the diagonals to obtain a Howe truss and watch tension and compression\n",
    "swap between diagonals and verticals."
   ]
  }
 ]
}
