{
 "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": [
    "# Rotating helix geometry\n",
    "\n",
    "Helical bodies appear in springs, coils of heat exchangers, screw conveyors and ribbon mixers.\n",
    "The CAD object `Helix(radius, pitch, turns)` is a path; `Sweep(profile=..., path=helix)` moves a\n",
    "profile along it with the profile always standing across the wire. A rotating helix is the same\n",
    "body turned about its axis by `rotated(axis, angle)`: for a sequence of angles it gives the\n",
    "positions of a mixer blade, and the fluid domain at each position is the vessel minus the coil.\n",
    "\n",
    "| quantity | value |\n",
    "|---|---|\n",
    "| helix radius $R$, pitch $p$, turns $N$ | 30 mm, 25 mm, 3 |\n",
    "| wire radius $a$ | 4 mm |\n",
    "| vessel radius and height | 45 mm, 100 mm |\n",
    "\n",
    "**Reference.** A helix of radius $R$ and pitch $p$ has the length $L = N\\sqrt{(2\\pi R)^2+p^2}$\n",
    "and runs from $(R,0,0)$ to $(R\\cos 2\\pi N, R\\sin 2\\pi N, Np)$. A tube of radius $a$ around a\n",
    "curve that does not cut itself has the volume $\\pi a^2 L$ (the theorem of Pappus and Guldin\n",
    "applied along the curve). Turning the coil leaves its volume and the fluid volume unchanged and\n",
    "turns its end point by the same angle."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Profile\n",
    "from onesim.cad.d3 import Cylinder, Helix, Sweep\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 coil\n",
    "\n",
    "The helix starts 12.5 mm above the floor of the vessel; the swept coil keeps the names `start`,\n",
    "`end` and `side` for its end faces and its wall."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "radius, pitch, turns, wire = 0.03, 0.025, 3, 0.004\n",
    "vessel_radius, vessel_height, lift = 0.045, 0.1, 0.0125\n",
    "helix = Helix(radius=radius, pitch=pitch, turns=turns, origin=(0.0, 0.0, lift))\n",
    "coil = Sweep(profile=Profile.circle(wire), path=helix)\n",
    "length = turns * np.hypot(2 * np.pi * radius, pitch)\n",
    "print(f\"helix length {helix.length * 1e3:.4f} mm, closed form {length * 1e3:.4f} mm\")\n",
    "print(\n",
    "    f\"coil volume {coil.measure * 1e6:.5f} cm3, pi a^2 L {np.pi * wire**2 * length * 1e6:.5f} cm3, \"\n",
    "    f\"deviation {coil.measure / (np.pi * wire**2 * length) - 1:+.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"end face centre {np.round(np.array(coil.topology.face(coil.boundary_groups()['end'][0]).center) * 1e3, 4)} mm, \"\n",
    "    f\"closed form {np.round(np.array([radius * np.cos(2 * np.pi * turns), radius * np.sin(2 * np.pi * turns), lift + turns * pitch]) * 1e3, 4)} mm\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The coil turned inside the vessel\n",
    "\n",
    "Four positions 30 degrees apart. For each the fluid domain is the vessel minus the turned coil,\n",
    "meshed with tetrahedra of at most 6 mm that turn by at most half a radian round the wire."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "angles = np.radians([0.0, 30.0, 60.0, 90.0])\n",
    "vessel = Cylinder(radius=vessel_radius, length=vessel_height)\n",
    "turned = [coil.rotated((0, 0, 1), angle) for angle in angles]\n",
    "fluids = [vessel - blade.named(\"coil\") for blade in turned]\n",
    "meshes = [\n",
    "    TetrahedralMesher(target_size=0.006, curvature_angle=0.5).generate(fluid)\n",
    "    for fluid in fluids\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=22, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(16, 7))\n",
    "plots.geometry(\n",
    "    coil,\n",
    "    selection={\"start\": coil.boundaries.start, \"end\": coil.boundaries.end},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Coil swept along a helix of three turns\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0],\n",
    "    groups=(\"coil.side\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Fluid mesh ({meshes[0].cell_count} tetrahedra): triangles on the coil\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "For every angle: the volume of the turned coil, the angle of its end point about the axis and\n",
    "the fluid volume of the CAD body and of its mesh."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fluid_exact = np.pi * vessel_radius**2 * vessel_height - np.pi * wire**2 * length\n",
    "print(\n",
    "    \"angle   coil volume [cm3]   end point angle   fluid CAD [cm3]   fluid mesh [cm3]   closed form   cells\"\n",
    ")\n",
    "for angle, blade, fluid, mesh in zip(angles, turned, fluids, meshes):\n",
    "    end = np.array(blade.topology.face(blade.boundary_groups()[\"end\"][0]).center)\n",
    "    print(\n",
    "        f\"{np.degrees(angle):5.0f} {blade.measure * 1e6:16.5f} {np.degrees(np.arctan2(end[1], end[0])):14.2f} deg\"\n",
    "        f\" {fluid.measure * 1e6:16.5f} {quality(mesh)['size'].sum() * 1e6:17.5f} {fluid_exact * 1e6:13.5f} {mesh.cell_count:7d}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The four positions of the coil seen from above at an angle, and the vessel cut open along its\n",
    "axis with the cells around the turned coil."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(2, 3, size=(19, 12))\n",
    "for index, (angle, blade) in enumerate(zip(angles, turned)):\n",
    "    plots.render(\n",
    "        blade,\n",
    "        camera=view,\n",
    "        material=\"steel\",\n",
    "        title=f\"coil turned by {np.degrees(angle):.0f} deg\",\n",
    "        ax=fig[index],\n",
    "    )\n",
    "for index in (0, 3):\n",
    "    plots.mesh(\n",
    "        meshes[index],\n",
    "        cell_values=quality(meshes[index])[\"shape\"],\n",
    "        limits=(0, 1),\n",
    "        plane=((0.0, 0.0, vessel_height / 2), (0.0, 1.0, 0.0)),\n",
    "        label=\"shape measure\",\n",
    "        camera=plots.Camera(elevation=10, azimuth=90),\n",
    "        title=f\"fluid cut along the axis, {np.degrees(angles[index]):.0f} deg\",\n",
    "        ax=fig[4 + index // 3],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Use the turned fluid domains as the frames of a rotating-machinery model, give the coil a flat\n",
    "ribbon profile (`Profile.rectangle`) for a ribbon blender, or a left-handed helix\n",
    "(`Helix(..., left_handed=True)`) for a counter-rotating screw."
   ]
  }
 ]
}
