{
 "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": [
    "# Geometry clean-up on a wheel rim\n",
    "\n",
    "CAD models made for manufacturing carry details that matter for the drawing but not for the\n",
    "simulation: small fillets, chamfers, engravings, valve and vent holes. Each of them forces small\n",
    "cells, and a mesh of the whole part becomes many times larger than the physics needs. Clean-up\n",
    "removes such details from the CAD model before meshing.\n",
    "\n",
    "| operation | call | what it does |\n",
    "|---|---|---|\n",
    "| find details | `part.details()` | holes, fillets, pockets and patterns with their radius or width |\n",
    "| remove chosen faces | `part.remove_faces(selection)` | the faces of the details are removed and the faces around them extended over the gap |\n",
    "| roll back | `part.history()`, `part.rolled_back(n)`, `part.suppressed(step)` | the last steps are undone, or one step is left out and the rest rebuilt |\n",
    "\n",
    "**Reference.** The rim built the same way without the 3 mm window fillets and the 4 mm valve\n",
    "hole: the clean rim must have its volume. The volumes of the\n",
    "meshes must match the volume of the body they were made for."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from collections import Counter\n",
    "\n",
    "import numpy as np\n",
    "from onesim.cad.d2 import Profile\n",
    "from onesim.cad.d3 import CircularPattern, Cylinder, Prism, Revolution, 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": [
    "## The rim\n",
    "\n",
    "The barrel is the revolved cross-section of a 16 inch rim, 200 mm wide, with its two flanges.\n",
    "The disc sits 120 mm from the outer edge; five windows (a rounded quadrilateral swept through the\n",
    "disc and repeated about the axis), five lug holes of 14 mm and a centre bore of 70 mm are cut\n",
    "out. Then the window edges on the face of the disc are rounded with 3 mm and a valve hole of\n",
    "8 mm is drilled through the barrel."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mm = 1e-3\n",
    "barrel = Revolution(\n",
    "    profile=Profile.polygon(\n",
    "        [\n",
    "            (185 * mm, 0),\n",
    "            (200 * mm, 0),\n",
    "            (200 * mm, 8 * mm),\n",
    "            (192 * mm, 14 * mm),\n",
    "            (192 * mm, 186 * mm),\n",
    "            (200 * mm, 192 * mm),\n",
    "            (200 * mm, 200 * mm),\n",
    "            (185 * mm, 200 * mm),\n",
    "            (185 * mm, 190 * mm),\n",
    "            (186 * mm, 10 * mm),\n",
    "        ]\n",
    "    )\n",
    ")\n",
    "window = Prism(\n",
    "    profile=Profile.rounded_polygon(\n",
    "        [\n",
    "            (80 * mm, -25 * mm),\n",
    "            (160 * mm, -45 * mm),\n",
    "            (160 * mm, 45 * mm),\n",
    "            (80 * mm, 25 * mm),\n",
    "        ],\n",
    "        10 * mm,\n",
    "    ),\n",
    "    height=40 * mm,\n",
    ").moved((0, 0, 110 * mm))\n",
    "lug = Cylinder(radius=7 * mm, length=40 * mm, origin=(57 * mm, 0, 110 * mm)).rotated(\n",
    "    (0, 0, 1), np.pi / 5\n",
    ")\n",
    "plain = (\n",
    "    UnionFromObjects(\n",
    "        objects=[\n",
    "            barrel,\n",
    "            Cylinder(radius=186 * mm, length=20 * mm, origin=(0, 0, 120 * mm)),\n",
    "        ]\n",
    "    )\n",
    "    - Cylinder(radius=35 * mm, length=40 * mm, origin=(0, 0, 110 * mm)).named(\"bore\")\n",
    "    - CircularPattern(window, (0, 0, 1), 5).named(\"window\")\n",
    "    - CircularPattern(lug, (0, 0, 1), 5).named(\"lug\")\n",
    ")\n",
    "drilled = plain - Cylinder(\n",
    "    radius=4 * mm, length=30 * mm, origin=(175 * mm, 0, 60 * mm), axis=(1, 0, 0)\n",
    ").named(\"valve\")\n",
    "rim = drilled.fillet(\n",
    "    3 * mm,\n",
    "    edges=drilled.select(\n",
    "        edges=lambda edge: abs(edge.start[2] - 0.14) < 1e-9\n",
    "        and abs(edge.end[2] - 0.14) < 1e-9\n",
    "        and 0.07 < np.hypot(edge.start[0], edge.start[1]) < 0.17\n",
    "    ),\n",
    ")\n",
    "print(\n",
    "    f\"rim: {len(rim.faces)} faces, {len(rim.edges)} edges, volume {rim.measure * 1e6:.3f} cm3, valid {rim.is_valid}\"\n",
    ")\n",
    "print(f\"modelling steps: {', '.join(type(step).__name__ for step in rim.history())}\")\n",
    "\n",
    "detailed = TetrahedralMesher(target_size=0.02).generate(rim)\n",
    "view = plots.Camera(elevation=35, azimuth=-50)\n",
    "fig = plots.figure(1, 2, size=(16, 7))\n",
    "plots.geometry(\n",
    "    rim,\n",
    "    selection={\n",
    "        \"3 mm fillets\": rim.boundaries.fillet,\n",
    "        \"valve hole\": rim.boundaries[\"valve.outer_wall\"],\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Wheel rim with its small details\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    detailed,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Mesh with all details: {detailed.cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Finding the details\n",
    "\n",
    "`details()` reports every hole and fillet with its radius. The rounded window corners of the\n",
    "profile (10 mm) are found as fillets too, the lug holes, the bore and the inside of the barrel\n",
    "as holes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "found = Counter((item.kind, round(item.radius / mm, 1)) for item in rim.details())\n",
    "for (kind, radius), count in sorted(found.items()):\n",
    "    print(f\"{count:3d} x {kind:7s} radius {radius:6.1f} mm\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Removing them\n",
    "\n",
    "Two ways to the clean rim: removing the faces of the 3 mm fillets and of the valve hole from the\n",
    "finished rim, or rolling back the fillet step in the history and removing the valve hole."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "clean = rim.remove_faces(rim.boundaries.fillet | rim.boundaries[\"valve.outer_wall\"])\n",
    "by_hand = rim.rolled_back(1).remove_faces(drilled.boundaries[\"valve.outer_wall\"])\n",
    "print(\n",
    "    \"body                         faces   edges   volume [cm3]   against the rim built without details\"\n",
    ")\n",
    "for name, body in {\n",
    "    \"rim with details\": rim,\n",
    "    \"fillets and valve removed\": clean,\n",
    "    \"rolled back, valve removed\": by_hand,\n",
    "    \"built without details\": plain,\n",
    "}.items():\n",
    "    print(\n",
    "        f\"{name:28s} {len(body.faces):6d} {len(body.edges):7d} {body.measure * 1e6:13.4f} {body.measure / plain.measure - 1:+16.1e}\"\n",
    "    )\n",
    "\n",
    "meshes = {\n",
    "    \"rim with details\": detailed,\n",
    "    \"fillets and valve removed\": TetrahedralMesher(target_size=0.02).generate(clean),\n",
    "    \"rolled back, valve removed\": TetrahedralMesher(target_size=0.02).generate(by_hand),\n",
    "}\n",
    "print(\n",
    "    \"mesh                        cells   shortest edge [mm]   smallest shape   volume error\"\n",
    ")\n",
    "for name, mesh in meshes.items():\n",
    "    report = quality(mesh)\n",
    "    reference = rim.measure if name == \"rim with details\" else plain.measure\n",
    "    print(\n",
    "        f\"{name:25s} {mesh.cell_count:8d} {1e3 * report['shortest_edge'].min():14.2f} {report['shape'].min():16.3f}\"\n",
    "        f\" {100 * (report['size'].sum() / reference - 1):+12.3f} %\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The clean rim with its window edges sharp again, and its mesh: the cells along the windows and\n",
    "around the valve position are as large as the rest."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(16, 7))\n",
    "plots.geometry(\n",
    "    clean,\n",
    "    selection={\n",
    "        \"windows\": clean.boundaries[\"window.side\"],\n",
    "        \"lug holes\": clean.boundaries[\"lug.outer_wall\"],\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Rim without fillets and valve hole\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"fillets and valve removed\"],\n",
    "    cell_values=1e3 * quality(meshes[\"fillets and valve removed\"])[\"longest_edge\"],\n",
    "    limits=(0, 40),\n",
    "    label=\"longest cell edge [mm]\",\n",
    "    camera=view,\n",
    "    title=f\"Mesh of the clean rim: {meshes['fillets and valve removed'].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Remove the 10 mm window corner rounds too, merge the faces of a smooth patch with\n",
    "`TetrahedralMesher(merged_faces=...)`, or compare the stresses of a wheel load on the rim with and\n",
    "without its details."
   ]
  }
 ]
}
