{
 "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": [
    "# Removing details in model geometries\n",
    "\n",
    "Small features force small cells: a mesher has to place nodes on every edge of the model, so an\n",
    "edge half a millimetre from another gives cells half a millimetre wide, however coarse the mesh\n",
    "is elsewhere. Typical culprits in imported parts are\n",
    "\n",
    "| detail | how it arises | remedy in OneSimulation |\n",
    "|---|---|---|\n",
    "| sliver face | two pieces of a body that almost, but not quite, line up | `part.defeatured(max_width=...)`, `TetrahedralMesher(merged_faces=...)` |\n",
    "| short edge | a groove, a step or a chamfer far smaller than the part | `part.short_edges(length)` finds them, `defeatured` removes them |\n",
    "| small hole | a vent, a pin hole, a thread core | `part.defeatured(max_radius=...)` |\n",
    "| small round | an edge fillet of a casting or a deburred edge | `part.defeatured(max_radius=...)`, `remove_faces` |\n",
    "#\n",
    "**Reference.** The block in closed form: three pieces of $L_1 + s + L_2$ = 100.5 mm length,\n",
    "50 mm width and 20 mm height, less a groove of $g\\times g$ = 0.5 x 0.5 mm along its length, a bore\n",
    "of 10 mm radius, a hole of 2 mm radius and two edge rounds of 1.5 mm radius:\n",
    "$V = (L_1+s+L_2)\\,W H - (L_1+s+L_2)\\,g^2 - \\pi(r_b^2 + r_h^2) H - 2\\,(1-\\pi/4)\\,\\rho^2 H$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from collections import Counter\n",
    "\n",
    "import numpy as np\n",
    "from onesim.cad.d3 import Box\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 block\n",
    "\n",
    "Pieces `a` and `c` are 50 mm long; between them the strip `b` is 0.5 mm wide. Their union keeps the\n",
    "faces of each piece, so the top, bottom and long sides consist of three faces each, one of them a\n",
    "sliver. The groove runs along the top front edge."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "length, width, height, strip, groove = 0.05, 0.05, 0.02, 0.0005, 0.0005\n",
    "total = 2 * length + strip\n",
    "block = (\n",
    "    Box(length=length, width=width, height=height).named(\"a\")\n",
    "    | Box(length=strip, width=width, height=height, origin=(length, 0.0, 0.0)).named(\n",
    "        \"b\"\n",
    "    )\n",
    "    | Box(\n",
    "        length=length, width=width, height=height, origin=(length + strip, 0.0, 0.0)\n",
    "    ).named(\"c\")\n",
    ")\n",
    "block = block - Box(\n",
    "    length=total, width=groove, height=groove, origin=(0.0, 0.0, height - groove)\n",
    ").named(\"groove\")\n",
    "block = block.hole(0.02, at=(0.075, 0.025, height)).hole(\n",
    "    0.004, at=(0.025, 0.025, height)\n",
    ")\n",
    "part = block.fillet(\n",
    "    0.0015,\n",
    "    edges=lambda edge: abs(edge.start[2] - edge.end[2]) > 0.015\n",
    "    and max(edge.start[0], edge.end[0]) < 1e-9,\n",
    ")\n",
    "exact = (\n",
    "    total * width * height\n",
    "    - total * groove**2\n",
    "    - np.pi * (0.01**2 + 0.002**2) * height\n",
    "    - 2 * (1 - np.pi / 4) * 0.0015**2 * height\n",
    ")\n",
    "without = total * width * height - np.pi * 0.01**2 * height\n",
    "print(\n",
    "    f\"{len(part.faces)} faces, {len(part.edges)} edges; volume {part.measure * 1e6:.5f} cm3, closed form {exact * 1e6:.5f} cm3\"\n",
    ")\n",
    "\n",
    "as_is = TetrahedralMesher(target_size=0.006).generate(part)\n",
    "view = plots.Camera(elevation=35, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(16, 7))\n",
    "plots.geometry(\n",
    "    part,\n",
    "    selection={\n",
    "        \"strip\": part.boundaries.b,\n",
    "        \"groove\": part.boundaries.groove,\n",
    "        \"small hole\": part.boundaries[\"hole_2.outer_wall\"],\n",
    "        \"edge rounds\": part.boundaries.fillet,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Machined block and its small details\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    as_is,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Meshed as it is: {as_is.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()` lists holes and rounds with their radius, `short_edges(length)` the edges shorter\n",
    "than a length: here those of the groove and the strip."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "for (kind, radius), count in sorted(\n",
    "    Counter((item.kind, round(item.radius * 1e3, 2)) for item in part.details()).items()\n",
    "):\n",
    "    print(f\"{count:3d} x {kind:8s} radius {radius:6.2f} mm\")\n",
    "print(f\"edges shorter than 2 mm: {len(part.short_edges(0.002).members)}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Removing them from the model\n",
    "\n",
    "First the narrow faces (`max_width`), then the small holes and rounds (`max_radius`). What is\n",
    "left is the block with its bore."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "no_slivers = part.defeatured(max_width=0.001)\n",
    "clean = no_slivers.defeatured(max_radius=0.0025)\n",
    "print(\"body                     faces   edges   volume [cm3]   closed form   deviation\")\n",
    "for name, body, reference in (\n",
    "    (\"as built\", part, exact),\n",
    "    (\"without slivers\", no_slivers, exact + total * groove**2),\n",
    "    (\"without small details\", clean, without),\n",
    "):\n",
    "    print(\n",
    "        f\"{name:22s} {len(body.faces):6d} {len(body.edges):7d} {body.measure * 1e6:13.5f} {reference * 1e6:13.5f} {body.measure / reference - 1:+11.1e}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Merging faces in the mesh only\n",
    "\n",
    "Without touching the model, `merged_faces` lets the faces of the three pieces on the bottom and\n",
    "the back count as one face each, so the mesh no longer follows the strip there; the faces keep\n",
    "their names and the nodes stay on the exact faces. The mesh of the clean body is the reference."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sides = [\n",
    "    part.boundaries[f\"a.{side}\"]\n",
    "    | part.boundaries[f\"b.{side}\"]\n",
    "    | part.boundaries[f\"c.{side}\"]\n",
    "    for side in (\"z_min\", \"y_max\")\n",
    "]\n",
    "meshes = {\n",
    "    \"meshed as it is\": as_is,\n",
    "    \"strip faces merged\": TetrahedralMesher(\n",
    "        target_size=0.006, merged_faces=sides\n",
    "    ).generate(part),\n",
    "    \"clean body\": TetrahedralMesher(target_size=0.006).generate(clean),\n",
    "}\n",
    "print(\n",
    "    \"mesh                          cells   shortest edge [mm]   smallest shape   volume [cm3]\"\n",
    ")\n",
    "for name, mesh in meshes.items():\n",
    "    report = quality(mesh)\n",
    "    print(\n",
    "        f\"{name:27s} {mesh.cell_count:7d} {1e3 * report['shortest_edge'].min():14.3f} {report['shape'].min():16.3f} {report['size'].sum() * 1e6:13.4f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The three meshes coloured by the longest edge of their cells: the small cells along the strip,\n",
    "the groove and around the small hole disappear with the details."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(21, 6))\n",
    "for index, (name, mesh) in enumerate(meshes.items()):\n",
    "    plots.mesh(\n",
    "        mesh,\n",
    "        cell_values=1e3 * quality(mesh)[\"longest_edge\"],\n",
    "        limits=(0, 10),\n",
    "        label=\"longest cell edge [mm]\",\n",
    "        camera=view,\n",
    "        title=f\"{name}: {mesh.cell_count} cells\",\n",
    "        ax=fig[index],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Use `part.comparison(clean)` to list the faces that were removed and added, give a face of the\n",
    "clean body a boundary layer, or add the top and front faces of the three pieces to `sides`."
   ]
  }
 ]
}
