{
 "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": [
    "# Swept meshing of a bracket\n",
    "\n",
    "A body that is one face carried along a path, straight or round a bend, can be filled with\n",
    "hexahedra layer by layer. Swept meshes need far fewer cells than tetrahedra for the same size,\n",
    "their layers follow the part, and the number and the thickness of the layers is free: thin\n",
    "layers near a face where the solution changes fast, few layers through a thin wall.\n",
    "\n",
    "`SweepMesher(source=face, target_size=..., layers=...)` meshes the source face with\n",
    "quadrilaterals and copies them through the body. It finds the face opposite the source, or\n",
    "follows the side faces round a bend when the body is swept along a curved path; `layers` is a\n",
    "number of equal layers or a distribution such as `Geometric(cells=6, ratio=3)` counted from the\n",
    "source.\n",
    "\n",
    "| part | built from | source face | sweep |\n",
    "|---|---|---|---|\n",
    "| gusset bracket | `Prism` of a rounded outline with three holes | `bottom` | straight, 12 mm |\n",
    "| bent strap | `Sweep` of a 30 x 4 mm section along a path with a 30 mm corner | `start` | three pieces, one sweep |\n",
    "\n",
    "**Reference.** The exact volumes of the parts: the bracket as its outline area times the\n",
    "thickness, the strap as $V = b\\,t\\,L$ with the path length $L = (h - R) + (l - R) + \\pi R / 2$\n",
    "of two straight pieces and a quarter circle of radius $R$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Profile\n",
    "from onesim.cad.d3 import Prism, Sweep\n",
    "from onesim.meshing import Geometric, SweepMesher, 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": [
    "## Geometry\n",
    "\n",
    "The bracket outline is a five-sided plate of 150 x 120 mm with rounded corners; two bolt holes of\n",
    "12 mm and a lightening hole of 36 mm become faces of their own names. The strap rises 60 mm,\n",
    "turns through a corner of 30 mm radius and runs 80 mm on."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "outline = Profile.rounded_polygon(\n",
    "    [(0.0, 0.0), (0.15, 0.0), (0.15, 0.025), (0.035, 0.12), (0.0, 0.12)],\n",
    "    [0.008, 0.008, 0.01, 0.01, 0.008],\n",
    ").with_holes(\n",
    "    Profile.circle(0.006, center=(0.12, 0.0125), name=\"bolt_lower\"),\n",
    "    Profile.circle(0.006, center=(0.0175, 0.09), name=\"bolt_upper\"),\n",
    "    Profile.circle(0.018, center=(0.045, 0.04), name=\"lightening\"),\n",
    ")\n",
    "thickness = 0.012\n",
    "bracket = Prism(profile=outline, height=thickness)\n",
    "section, rise, run, corner = (0.03, 0.004), 0.06, 0.08, 0.03\n",
    "strap = Sweep(\n",
    "    profile=Profile.rectangle(*section, origin=(-section[0] / 2, -section[1] / 2)),\n",
    "    path=[(0.0, 0.0, 0.0), (0.0, 0.0, rise), (run, 0.0, rise)],\n",
    "    corner_radius=corner,\n",
    ")\n",
    "path_length = (rise - corner) + (run - corner) + np.pi * corner / 2\n",
    "print(\n",
    "    f\"bracket: faces {', '.join(face.id for face in bracket.faces)}; volume {bracket.measure * 1e6:.4f} cm3 \"\n",
    "    f\"= outline area x thickness {outline.area * thickness * 1e6:.4f} cm3\"\n",
    ")\n",
    "print(\n",
    "    f\"strap: path length {strap.length * 1e3:.3f} mm (closed form {path_length * 1e3:.3f} mm), \"\n",
    "    f\"volume {strap.measure * 1e6:.4f} cm3 (closed form {section[0] * section[1] * path_length * 1e6:.4f} cm3)\"\n",
    ")\n",
    "\n",
    "swept = SweepMesher(\n",
    "    source=bracket.boundaries.bottom, target_size=0.005, layers=4\n",
    ").generate(bracket)\n",
    "view = plots.Camera(elevation=35, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.geometry(\n",
    "    bracket,\n",
    "    selection={\n",
    "        \"source face\": bracket.boundaries.bottom,\n",
    "        \"bolt holes\": bracket.boundaries.bolt_lower | bracket.boundaries.bolt_upper,\n",
    "        \"lightening hole\": bracket.boundaries.lightening,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Gusset bracket\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    swept,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Swept mesh: {swept.cell_count} hexahedra in 4 layers\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Straight sweep through the bracket\n",
    "\n",
    "Four equal layers, six layers that grow by a factor of three from the source face, and a\n",
    "tetrahedral mesh of the same size for comparison. The scaled Jacobian (1 for a perfect cell, 0\n",
    "for a flat one) and the shape measure tell how well the cells are formed."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "meshes = {\n",
    "    \"4 equal layers\": swept,\n",
    "    \"6 graded layers\": SweepMesher(\n",
    "        source=bracket.boundaries.bottom,\n",
    "        target_size=0.005,\n",
    "        layers=Geometric(cells=6, ratio=3.0),\n",
    "    ).generate(bracket),\n",
    "    \"tetrahedra\": TetrahedralMesher(target_size=0.005).generate(bracket),\n",
    "}\n",
    "print(\n",
    "    \"mesh               cells   kind          volume error   scaled Jacobian min   shape mean\"\n",
    ")\n",
    "for name, mesh in meshes.items():\n",
    "    report = quality(mesh)\n",
    "    print(\n",
    "        f\"{name:16s} {mesh.cell_count:7d}   {report.family:12s} {100 * (report['size'].sum() / bracket.measure - 1):+10.3f} %\"\n",
    "        f\" {report['scaled_jacobian'].min():18.3f} {report['shape'].mean():12.3f}\"\n",
    "    )\n",
    "heights = np.unique(\n",
    "    np.round(np.asarray(meshes[\"6 graded layers\"].coordinates)[:, 2], 9)\n",
    ")\n",
    "print(\n",
    "    f\"graded layers: heights {', '.join(f'{1e3 * h:.2f}' for h in heights)} mm; \"\n",
    "    f\"last to first layer {np.diff(heights)[-1] / np.diff(heights)[0]:.2f} (stated 3)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Sweep round the bend of the strap\n",
    "\n",
    "The strap has no face opposite its start face in a straight line; the mesher follows its side\n",
    "faces through the three pieces and shares the 30 layers out by their lengths. Every layer holds\n",
    "the same quadrilaterals as the start face."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "bent = SweepMesher(\n",
    "    source=strap.boundaries.start, target_size=0.004, layers=30\n",
    ").generate(strap)\n",
    "bent_tetrahedra = TetrahedralMesher(target_size=0.004).generate(strap)\n",
    "per_layer = len(bent.facets(strap.boundaries.start))\n",
    "print(\n",
    "    f\"strap: {per_layer} quadrilaterals on the start face, {len(bent.facets(strap.boundaries.end))} on the end face, \"\n",
    "    f\"{bent.cell_count // per_layer} layers\"\n",
    ")\n",
    "for name, mesh in {\"swept hexahedra\": bent, \"tetrahedra\": bent_tetrahedra}.items():\n",
    "    report = quality(mesh)\n",
    "    print(\n",
    "        f\"{name:16s} {mesh.cell_count:7d} cells, volume error {100 * (report['size'].sum() / strap.measure - 1):+.3f} %, \"\n",
    "        f\"scaled Jacobian min {report['scaled_jacobian'].min():.3f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The graded sweep and the tetrahedra of the bracket coloured by the scaled Jacobian of their\n",
    "cells, the strap with its start face, and its swept mesh round the bend."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "strap_view = plots.Camera(elevation=20, azimuth=-70)\n",
    "fig = plots.figure(2, 2, size=(16, 12))\n",
    "plots.mesh(\n",
    "    meshes[\"6 graded layers\"],\n",
    "    cell_values=quality(meshes[\"6 graded layers\"])[\"scaled_jacobian\"],\n",
    "    limits=(0, 1),\n",
    "    label=\"scaled Jacobian\",\n",
    "    camera=view,\n",
    "    title=f\"6 graded layers: {meshes['6 graded layers'].cell_count} hexahedra\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"tetrahedra\"],\n",
    "    cell_values=quality(meshes[\"tetrahedra\"])[\"scaled_jacobian\"],\n",
    "    limits=(0, 1),\n",
    "    label=\"scaled Jacobian\",\n",
    "    camera=view,\n",
    "    title=f\"Tetrahedra: {meshes['tetrahedra'].cell_count} cells\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.geometry(\n",
    "    strap,\n",
    "    selection={\"start face\": strap.boundaries.start, \"end face\": strap.boundaries.end},\n",
    "    labels=False,\n",
    "    camera=strap_view,\n",
    "    title=\"Bent strap\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.mesh(\n",
    "    bent,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=strap_view,\n",
    "    title=f\"Swept round the bend: {bent.cell_count} hexahedra\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Sweep a revolved part (`Revolution(..., angle=np.pi / 2)`) from its start face, give the edges of\n",
    "the source face their own sizes with `SweepMesher(sizes=((edges, size),))`, or join the swept\n",
    "mesh of one part with the tetrahedra of another through `hybrid_mesh`."
   ]
  }
 ]
}
