{
 "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": [
    "# Modifying imported CAD geometry by deformation\n",
    "\n",
    "Imported parts often need a quick change of a dimension for a parameter study: a longer arm, a\n",
    "thicker flange, a top surface with a crown. Editing the CAD model means rebuilding and meshing\n",
    "again for every value; moving the nodes of one existing mesh is far cheaper and keeps the cell\n",
    "numbering, so results of different variants can be compared node by node.\n",
    "\n",
    "`deformed(mesh, {face: displacement}, fixed=[...])` (`onesim.meshing.adaptation`) moves the\n",
    "nodes of the named faces, holds those of the fixed faces and spreads the motion through the\n",
    "body by solving a Laplace problem for the displacement (method `\"harmonic\"`); control points\n",
    "away from the nodes need the radial basis method `\"rbf\"`. A move that would turn cells inside\n",
    "out is refused; `steps` carries a large move out in smaller ones.\n",
    "\n",
    "The block comes from the CAD file `deforming_imported_cad_part.step`, written by\n",
    "`deforming_imported_cad_part_geometry.py`; it names the faces `held`, `moved`, `bore` and `top`.\n",
    "\n",
    "**Reference.** With the bore and the opposite end held, moving the end face by $d$ changes\n",
    "$L\\times W\\times H$ to $(L+d)\\times W\\times H$ and leaves the bore as it is:\n",
    "$V(d) = (L+d)WH - \\pi r^2 W$. The same change on the CAD model is `move_faces`."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import TetrahedralMesher\n",
    "from onesim.meshing.adaptation import deformed\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 and mesh\n",
    "\n",
    "`load` returns the solid with the named face groups of the file. The mesh is made once."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "part = load(\"deforming_imported_cad_part.step\")\n",
    "faces = part.boundaries\n",
    "length, width, height, radius = 0.1, 0.04, 0.03, 0.008\n",
    "mesh = TetrahedralMesher(target_size=0.005, curvature_angle=0.4).generate(part)\n",
    "print(\n",
    "    f\"faces: {', '.join(face.id for face in part.faces)}; groups held, moved, bore, top\"\n",
    ")\n",
    "print(f\"mesh: {mesh.cell_count} tetrahedra, {len(mesh.coordinates)} nodes\")\n",
    "\n",
    "view = plots.Camera(elevation=30, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.geometry(\n",
    "    part,\n",
    "    selection={\"held\": faces.held, \"moved\": faces.moved, \"bore (held)\": faces.bore},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Imported clamp block\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Mesh made once: {mesh.cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Changing the length\n",
    "\n",
    "The end face moves by -20 to +30 mm; the shortening is carried out in two steps. For comparison\n",
    "each length is also made on the CAD model with `move_faces` and meshed anew."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "moves = [-0.02, 0.01, 0.02, 0.03]\n",
    "variants = {\n",
    "    move: deformed(\n",
    "        mesh,\n",
    "        {faces.moved: (move, 0.0, 0.0)},\n",
    "        fixed=[faces.held, faces.bore],\n",
    "        steps=2 if move < 0 else 1,\n",
    "    )\n",
    "    for move in moves\n",
    "}\n",
    "remodelled = {move: part.move_faces(faces.moved, (move, 0.0, 0.0)) for move in moves}\n",
    "volume = lambda d: (length + d) * width * height - np.pi * radius**2 * width\n",
    "start = quality(mesh)\n",
    "print(\n",
    "    f\"original mesh: volume {start['size'].sum() * 1e6:.4f} cm3 (closed form {volume(0.0) * 1e6:.4f}), smallest shape {start['shape'].min():.3f}\"\n",
    ")\n",
    "print(\n",
    "    \" move [mm]   deformed mesh [cm3]   change   closed-form change   CAD move_faces [cm3]   closed form   smallest shape   cells\"\n",
    ")\n",
    "for move, variant in variants.items():\n",
    "    report = quality(variant)\n",
    "    print(\n",
    "        f\"{1e3 * move:9.0f} {report['size'].sum() * 1e6:18.4f} {(report['size'].sum() - start['size'].sum()) * 1e6:10.4f}\"\n",
    "        f\" {move * width * height * 1e6:16.4f} {remodelled[move].measure * 1e6:21.4f} {volume(move) * 1e6:13.4f}\"\n",
    "        f\" {report['shape'].min():15.3f} {variant.cell_count:7d}\"\n",
    "    )\n",
    "print(\n",
    "    f\"the bore nodes did not move: largest displacement there {np.abs(variants[0.03].displacement[np.unique(np.asarray(mesh.facets(faces.bore)))]).max():.1e} m\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## A crowned top surface\n",
    "\n",
    "Two control points on the top face are lifted by 1.5 mm and lowered by 0.5 mm; with the radial\n",
    "basis method the top bends smoothly between them while the bottom, the ends and the bore stay."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "crowned = deformed(\n",
    "    mesh,\n",
    "    [\n",
    "        (\n",
    "            np.array([[0.07, 0.02, height], [0.045, 0.02, height]]),\n",
    "            np.array([[0.0, 0.0, 0.0015], [0.0, 0.0, -0.0005]]),\n",
    "        )\n",
    "    ],\n",
    "    method=\"rbf\",\n",
    "    fixed=[faces.held, faces.moved, faces.bore, faces.z_min],\n",
    ")\n",
    "print(\n",
    "    f\"crowned top: volume {quality(crowned)['size'].sum() * 1e6:.4f} cm3, highest point {1e3 * np.asarray(crowned.coordinates)[:, 2].max():.3f} mm, \"\n",
    "    f\"smallest shape {quality(crowned)['shape'].min():.3f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The shortest and the longest variant and the crowned top, coloured by the shape measure of their\n",
    "cells: the same cells, squeezed or stretched between the held bore and the moved end."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(21, 6))\n",
    "plots.mesh(\n",
    "    variants[-0.02],\n",
    "    cell_values=quality(variants[-0.02])[\"shape\"],\n",
    "    limits=(0, 1),\n",
    "    label=\"shape measure\",\n",
    "    camera=view,\n",
    "    title=\"End face moved by -20 mm\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    variants[0.03],\n",
    "    cell_values=quality(variants[0.03])[\"shape\"],\n",
    "    limits=(0, 1),\n",
    "    label=\"shape measure\",\n",
    "    camera=view,\n",
    "    title=\"End face moved by +30 mm\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.mesh(\n",
    "    crowned,\n",
    "    cell_values=quality(crowned)[\"shape\"],\n",
    "    limits=(0, 1),\n",
    "    label=\"shape measure\",\n",
    "    camera=view,\n",
    "    title=\"Top crowned by two control points\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Turn the end face with `rigid_motion(axis=..., angle=...)` for a tapered block, let\n",
    "`deformed(..., remesh_below=...)` mesh again where cells become too poor, or solve the same load\n",
    "case on every variant and compare the stresses node by node."
   ]
  }
 ]
}
