{
 "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": [
    "# Adjusting the element size of an unstructured mesh\n",
    "\n",
    "An unstructured tetrahedral mesher decides the size of every cell from a few controls. This\n",
    "tutorial changes them one at a time on the same part and shows what each one does:\n",
    "\n",
    "| control | keyword of `TetrahedralMesher` | acts |\n",
    "|---|---|---|\n",
    "| largest size | `target_size` | everywhere: no cell is larger |\n",
    "| curvature | `curvature_angle` | on curved faces and edges: one cell turns by at most this angle |\n",
    "| grading | `grading` | between fine and coarse regions: largest change of size per unit length |\n",
    "| smallest size | `minimum_size` | everywhere: no cell is asked to be smaller |\n",
    "| thin walls | `gap_cells` | across gaps and walls: least number of cells |\n",
    "| size on faces, edges, points, bodies | `refinements=(LocalRefinement(...),)` | on the selection |\n",
    "| size by distance | `refinements=(DistanceRefinement(...),)` | grows from a face, edge or point |\n",
    "| size field | `size_field=lambda points: ...` | wherever the function says |\n",
    "\n",
    "`fineness(part, level)` bundles the first five into the five usual degrees from `very_coarse`\n",
    "to `very_fine`, scaled to the diagonal of the part.\n",
    "\n",
    "**Reference.** The volume of the part in closed form,\n",
    "$V = LWt - 4\\pi r_h^2 t + \\pi R^2 h - \\pi r_b^2 (t+h)$; a full turn of a circle of the bore takes\n",
    "about $2\\pi/\\alpha$ cells for the curvature angle $\\alpha$; and the number of cells of every mesh\n",
    "is predicted before the body is filled (`estimated_cells`), from the triangles on the faces and\n",
    "the points inside."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d3 import Box, Cylinder, UnionFromObjects\n",
    "from onesim.meshing import (\n",
    "    DistanceRefinement,\n",
    "    LocalRefinement,\n",
    "    TetrahedralMesher,\n",
    "    estimated_cells,\n",
    "    fineness,\n",
    "    fineness_levels,\n",
    ")\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",
    "A base plate of 120 x 80 x 12 mm with four bolt holes of 8 mm and a boss of 50 mm diameter and\n",
    "30 mm height with a bore of 24 mm through boss and plate. `UnionFromObjects` joins plate and\n",
    "boss into one body with new face identifiers; `hole` and the subtraction of a named cylinder add\n",
    "the bores, whose walls keep the names `hole.outer_wall` ... and `bore.outer_wall`."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "length, width, plate, radius, height, bore, bolt = (\n",
    "    0.12,\n",
    "    0.08,\n",
    "    0.012,\n",
    "    0.025,\n",
    "    0.03,\n",
    "    0.012,\n",
    "    0.004,\n",
    ")\n",
    "part = UnionFromObjects(\n",
    "    objects=[\n",
    "        Box(length=length, width=width, height=plate),\n",
    "        Cylinder(radius=radius, length=height, origin=(length / 2, width / 2, plate)),\n",
    "    ]\n",
    ")\n",
    "for x, y in [(0.015, 0.015), (0.105, 0.015), (0.015, 0.065), (0.105, 0.065)]:\n",
    "    part = part.hole(2 * bolt, at=(x, y, plate))\n",
    "part = part - Cylinder(\n",
    "    radius=bore, length=plate + height, origin=(length / 2, width / 2, 0.0)\n",
    ").named(\"bore\")\n",
    "faces = part.boundaries\n",
    "exact = (\n",
    "    length * width * plate\n",
    "    - 4 * np.pi * bolt**2 * plate\n",
    "    + np.pi * radius**2 * height\n",
    "    - np.pi * bore**2 * (plate + height)\n",
    ")\n",
    "print(f\"{len(part.faces)} faces, {len(part.edges)} edges\")\n",
    "print(f\"volume: CAD {part.measure * 1e6:.4f} cm3, closed form {exact * 1e6:.4f} cm3\")\n",
    "\n",
    "view = plots.Camera(elevation=32, azimuth=-58)\n",
    "normal = TetrahedralMesher(**fineness(part, \"normal\")).generate(part)\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.geometry(\n",
    "    part, camera=view, title=\"Flanged boss with its face identifiers\", ax=fig[0]\n",
    ")\n",
    "plots.mesh(\n",
    "    normal,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Fineness 'normal': {normal.cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Predefined fineness\n",
    "\n",
    "The five degrees set the largest size from a sixth to a fortieth of the diagonal of the part,\n",
    "together with grading, curvature angle and gap cells. Before each\n",
    "mesh is made, `estimated_cells` lays the faces exactly as the mesher will and counts the cells\n",
    "that will fill the body."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "levels = {level: fineness(part, level) for level in fineness_levels()}\n",
    "by_level = {\n",
    "    level: TetrahedralMesher(**controls).generate(part)\n",
    "    for level, controls in levels.items()\n",
    "}\n",
    "estimates = {\n",
    "    level: estimated_cells(TetrahedralMesher(**controls), part)\n",
    "    for level, controls in levels.items()\n",
    "}\n",
    "print(\"fineness      size [mm]  angle  grading   cells   estimate   volume error\")\n",
    "for level, mesh in by_level.items():\n",
    "    print(\n",
    "        f\"{level:12s} {1e3 * levels[level]['target_size']:9.2f} {levels[level]['curvature_angle']:6.2f} {levels[level]['grading']:8.2f}\"\n",
    "        f\" {mesh.cell_count:7d} {estimates[level]:10d} {100 * (quality(mesh)['size'].sum() / exact - 1):+12.3f} %\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## One control at a time\n",
    "\n",
    "Starting from a largest size of 10 mm, each mesher below changes one control. The number of\n",
    "triangles on the bore wall and the smallest and largest cell edge show where the control acts."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "base = dict(target_size=0.010)\n",
    "meshers = {\n",
    "    \"largest size 10 mm\": TetrahedralMesher(**base),\n",
    "    \"largest size 5 mm\": TetrahedralMesher(target_size=0.005),\n",
    "    \"curvature angle 1.0 rad\": TetrahedralMesher(**base, curvature_angle=1.0),\n",
    "    \"curvature angle 0.2 rad\": TetrahedralMesher(**base, curvature_angle=0.2),\n",
    "    \"grading 0.15\": TetrahedralMesher(**base, curvature_angle=0.3, grading=0.15),\n",
    "    \"grading 0.8\": TetrahedralMesher(**base, curvature_angle=0.3, grading=0.8),\n",
    "    \"smallest size 3 mm\": TetrahedralMesher(\n",
    "        **base, curvature_angle=0.2, minimum_size=0.003\n",
    "    ),\n",
    "    \"two cells across walls\": TetrahedralMesher(**base, gap_cells=2),\n",
    "    \"bore wall 1.5 mm\": TetrahedralMesher(\n",
    "        **base,\n",
    "        refinements=(\n",
    "            LocalRefinement(region=faces[\"bore.outer_wall\"], target_size=0.0015),\n",
    "        ),\n",
    "    ),\n",
    "    \"distance from the bore\": TetrahedralMesher(\n",
    "        **base,\n",
    "        refinements=(\n",
    "            DistanceRefinement(\n",
    "                source=faces[\"bore.outer_wall\"],\n",
    "                target_size=0.0015,\n",
    "                near=0.002,\n",
    "                far=0.03,\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "    \"size field along x\": TetrahedralMesher(\n",
    "        **base, size_field=lambda points: 0.0015 + 0.12 * points[:, 0]\n",
    "    ),\n",
    "}\n",
    "meshes = {name: mesher.generate(part) for name, mesher in meshers.items()}\n",
    "reports = {name: quality(mesh) for name, mesh in meshes.items()}\n",
    "print(\n",
    "    \"control                     cells   bore triangles   cell edge median / largest [mm]   volume error\"\n",
    ")\n",
    "for name, mesh in meshes.items():\n",
    "    edges = reports[name][\"longest_edge\"]\n",
    "    print(\n",
    "        f\"{name:25s} {mesh.cell_count:7d} {len(mesh.facets(faces['bore.outer_wall'])):12d}\"\n",
    "        f\" {1e3 * np.median(edges):17.2f} / {1e3 * edges.max():5.2f} {100 * (reports[name]['size'].sum() / exact - 1):+20.3f} %\"\n",
    "    )\n",
    "print(\n",
    "    f\"curvature angle 0.2 rad: about {2 * np.pi / 0.2:.0f} cells around a circle of the bore; \"\n",
    "    f\"1.0 rad: about {2 * np.pi / 1.0:.0f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Four of the meshes side by side: a coarse turn on the bore against a fine one, and a size that\n",
    "grows slowly against one that grows fast away from the fine bore. Then the size of the cells on\n",
    "the surface for the distance control, and the number of cells against the largest\n",
    "size for a series of meshes with the estimate made before meshing. The fine cells of the bolt\n",
    "holes and the bore stay at every largest size, so the count grows more slowly than $h^{-3}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sizes = [0.007, 0.0055, 0.0045, 0.0037, 0.003]\n",
    "series = [\n",
    "    TetrahedralMesher(target_size=size).generate(part).cell_count for size in sizes\n",
    "]\n",
    "predicted = [\n",
    "    estimated_cells(TetrahedralMesher(target_size=size), part) for size in sizes\n",
    "]\n",
    "exponent = np.polyfit(np.log(sizes), np.log(series), 1)[0]\n",
    "print(\"largest size [mm]   cells   estimate   deviation\")\n",
    "for size, cells, estimate in zip(sizes, series, predicted):\n",
    "    print(\n",
    "        f\"{1e3 * size:17.1f} {cells:7d} {estimate:10d} {100 * (estimate / cells - 1):+10.1f} %\"\n",
    "    )\n",
    "print(\n",
    "    f\"cells grow as h^{exponent:.2f} from 7 to 3 mm (h^-3 only once h is small against every detail and the 12 mm plate)\"\n",
    ")\n",
    "fig = plots.figure(2, 2, size=(16, 11))\n",
    "for index, name in enumerate(\n",
    "    [\n",
    "        \"curvature angle 1.0 rad\",\n",
    "        \"curvature angle 0.2 rad\",\n",
    "        \"grading 0.15\",\n",
    "        \"grading 0.8\",\n",
    "    ]\n",
    "):\n",
    "    plots.mesh(\n",
    "        meshes[name],\n",
    "        groups=(\"all\",),\n",
    "        legend=False,\n",
    "        camera=view,\n",
    "        title=f\"{name}: {meshes[name].cell_count} cells\",\n",
    "        ax=fig[index],\n",
    "    )\n",
    "plots.show()\n",
    "\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.mesh(\n",
    "    meshes[\"distance from the bore\"],\n",
    "    cell_values=1e3 * reports[\"distance from the bore\"][\"longest_edge\"],\n",
    "    limits=(0, 14),\n",
    "    label=\"longest cell edge [mm]\",\n",
    "    camera=view,\n",
    "    title=\"Size grows with the distance from the bore\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * np.array(sizes),\n",
    "    {\"tetrahedral mesher\": np.array(series)},\n",
    "    reference={\"estimate before meshing\": (1e3 * np.array(sizes), np.array(predicted))},\n",
    "    markers=True,\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"largest size h [mm]\",\n",
    "    ylabel=\"number of cells\",\n",
    "    title=\"Cells against the largest size\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Combine controls: a `LocalRefinement` on a selection of edges with `cells=` fixes the exact\n",
    "number of cells along them, `quality_limits=QualityLimits.finite_elements()` improves the mesh\n",
    "until every cell keeps the limits, and `size_preview(mesher, part)` shows the face mesh before the\n",
    "body is filled."
   ]
  }
 ]
}
