{
 "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": [
    "# Busbar assembly geometry\n",
    "\n",
    "Busbars carry large currents between the components of switchgear and power electronics; their\n",
    "temperature is set by Joule heating in the bar and by the contact resistance at the bolted\n",
    "joints. A model of a busbar therefore needs the bar, the bolts and washers as separate parts and\n",
    "the faces where they touch.\n",
    "\n",
    "| part | built from |\n",
    "|---|---|\n",
    "| `busbar` | `Sweep` of a 40 x 6 mm rectangle along a Z-shaped path with corners of 15 mm radius, less two holes of 9 mm |\n",
    "| `washer_1`, `washer_2` | `AnnularCylinder`, 16 / 8.4 mm diameter, 1.6 mm thick, on the bar |\n",
    "| `bolt_1`, `bolt_2` | `UnionFromObjects` of a head (13 mm, 5.5 mm high) and a shank (8 mm, 30 mm long) through the hole |\n",
    "\n",
    "`Assembly(parts=[...])` keeps one volume per part and lists the faces where two parts touch,\n",
    "`assembly.interfaces`, the faces for contact or thermal contact conditions.\n",
    "\n",
    "**Reference.** The path of segments $l_1, l_2, l_3$ with two corners of radius $R$ has the length\n",
    "$L = l_1 + l_2 + l_3 - 4R + \\pi R$; the bar has $V = b t L - 2\\pi r_h^2 t$. A washer touches the\n",
    "bar on the ring between the hole and its outer edge, $\\pi(r_w^2 - r_h^2)$, and the bolt head on\n",
    "the ring $\\pi(r_k^2 - r_i^2)$ between the inner edge of the washer and the edge of the head."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Profile\n",
    "from onesim.cad.d3 import AnnularCylinder, Assembly, Cylinder, Sweep, UnionFromObjects\n",
    "from onesim.meshing import TetrahedralMesher\n",
    "from onesim.meshing.quality import quality\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parts\n",
    "\n",
    "The bar runs 120 mm along x, rises 80 mm and runs 100 mm on; the section is centred on the path.\n",
    "The holes sit 30 mm from each end."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "breadth, thickness, corner, hole = 0.04, 0.006, 0.015, 0.0045\n",
    "segments = (0.12, 0.08, 0.10)\n",
    "path = [(0.0, 0.0, 0.0), (0.12, 0.0, 0.0), (0.12, 0.0, 0.08), (0.22, 0.0, 0.08)]\n",
    "bar = Sweep(\n",
    "    profile=Profile.rectangle(\n",
    "        breadth, thickness, origin=(-breadth / 2, -thickness / 2)\n",
    "    ),\n",
    "    path=path,\n",
    "    corner_radius=corner,\n",
    ")\n",
    "holes = [(0.03, 0.0, 0.0), (0.19, 0.0, 0.08)]\n",
    "for index, (x, y, z) in enumerate(holes, start=1):\n",
    "    bar = bar - Cylinder(radius=hole, length=0.02, origin=(x, y, z - 0.01)).named(\n",
    "        f\"hole_{index}\"\n",
    "    )\n",
    "washer_outer, washer_inner, washer_thickness = 0.008, 0.0042, 0.0016\n",
    "head_radius, head_height, shank_radius, shank_length = 0.0065, 0.0055, 0.004, 0.03\n",
    "parts = [bar.named(\"busbar\")]\n",
    "for index, (x, y, z) in enumerate(holes, start=1):\n",
    "    top = z + thickness / 2\n",
    "    parts.append(\n",
    "        AnnularCylinder(\n",
    "            inner_radius=washer_inner,\n",
    "            outer_radius=washer_outer,\n",
    "            length=washer_thickness,\n",
    "            origin=(x, y, top),\n",
    "        ).named(f\"washer_{index}\")\n",
    "    )\n",
    "    parts.append(\n",
    "        UnionFromObjects(\n",
    "            objects=[\n",
    "                Cylinder(\n",
    "                    radius=head_radius,\n",
    "                    length=head_height,\n",
    "                    origin=(x, y, top + washer_thickness),\n",
    "                ),\n",
    "                Cylinder(\n",
    "                    radius=shank_radius,\n",
    "                    length=shank_length,\n",
    "                    origin=(x, y, top + washer_thickness - shank_length),\n",
    "                ),\n",
    "            ]\n",
    "        ).named(f\"bolt_{index}\")\n",
    "    )\n",
    "busbar = Assembly(parts=parts)\n",
    "print(f\"parts: {', '.join(part.id for part in busbar.volumes)}\")\n",
    "\n",
    "meshes = {\n",
    "    part.id: TetrahedralMesher(target_size=0.004, curvature_angle=0.5).generate(\n",
    "        busbar.part(part.id)\n",
    "    )\n",
    "    for part in busbar.volumes\n",
    "}\n",
    "view = plots.Camera(elevation=25, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(16, 7))\n",
    "plots.geometry(\n",
    "    busbar,\n",
    "    selection={part.id: busbar.volume_of(part.id) for part in busbar.volumes},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Busbar with washers and bolts\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"busbar\"],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Mesh of the bar: {meshes['busbar'].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Path length and volumes of every part, then every contact face of the assembly with its area."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "length = sum(segments) - 4 * corner + np.pi * corner\n",
    "closed = {\n",
    "    \"busbar\": breadth * thickness * length - 2 * np.pi * hole**2 * thickness,\n",
    "    **{\n",
    "        f\"washer_{k}\": np.pi * (washer_outer**2 - washer_inner**2) * washer_thickness\n",
    "        for k in (1, 2)\n",
    "    },\n",
    "    **{\n",
    "        f\"bolt_{k}\": np.pi\n",
    "        * (head_radius**2 * head_height + shank_radius**2 * shank_length)\n",
    "        for k in (1, 2)\n",
    "    },\n",
    "}\n",
    "print(\n",
    "    f\"path length {Sweep(profile=Profile.rectangle(breadth, thickness), path=path, corner_radius=corner).length * 1e3:.4f} mm, \"\n",
    "    f\"closed form {length * 1e3:.4f} mm\"\n",
    ")\n",
    "print(\"part        CAD [cm3]    mesh [cm3]   closed form [cm3]   deviation CAD\")\n",
    "for part in busbar.volumes:\n",
    "    meshed = quality(meshes[part.id])[\"size\"].sum()\n",
    "    print(\n",
    "        f\"{part.id:9s} {part.measure * 1e6:11.5f} {meshed * 1e6:12.5f} {closed[part.id] * 1e6:16.5f} {part.measure / closed[part.id] - 1:+15.1e}\"\n",
    "    )\n",
    "rings = {\n",
    "    \"busbar\": np.pi * (washer_outer**2 - hole**2),\n",
    "    \"bolt\": np.pi * (head_radius**2 - washer_inner**2),\n",
    "}\n",
    "print(\"contact                 area [mm2]   closed form [mm2]\")\n",
    "for contact in busbar.interfaces:\n",
    "    other = \"busbar\" if \"busbar\" in contact.parts else \"bolt\"\n",
    "    print(\n",
    "        f\"{' / '.join(contact.parts):22s} {contact.area * 1e6:11.4f} {rings[other] * 1e6:16.4f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The copper bar with its two bends, and the mesh of the upper bolt cut through its axis."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(16, 7))\n",
    "plots.render(\n",
    "    bar, camera=view, material=\"copper\", title=\"Copper busbar with two bends\", ax=fig[0]\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"bolt_2\"],\n",
    "    cell_values=quality(meshes[\"bolt_2\"])[\"shape\"],\n",
    "    limits=(0, 1),\n",
    "    plane=((0.19, 0.0, 0.08), (0.0, 1.0, 0.0)),\n",
    "    label=\"shape measure\",\n",
    "    camera=plots.Camera(elevation=5, azimuth=90),\n",
    "    title=f\"Upper bolt cut through its axis: {meshes['bolt_2'].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Pass the current through the bar and heat it with `onesim.physics` (Joule heating), give each\n",
    "contact face a contact resistance, or replace the simple bolts by `screw(\"M8\", 0.03)` with its\n",
    "thread."
   ]
  }
 ]
}
