{
 "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": [
    "# Light bulb geometry\n",
    "\n",
    "Lamps are a classic case for heat transfer and radiation models, and a good exercise in building\n",
    "a model geometry from its natural pieces:\n",
    "\n",
    "| part | built from | material |\n",
    "|---|---|---|\n",
    "| `glass` | revolved outline of the envelope less revolved outline of its inside | glass, 0.8 mm wall |\n",
    "| `gas` | revolved inside outline less the filament | argon |\n",
    "| `base` | cylinder below the neck | brass |\n",
    "| `filament` | circle of 0.3 mm radius swept along a helix of six turns | tungsten |\n",
    "\n",
    "The outline of the envelope is a closed path in the $(r,z)$ half-plane: along the axis, out to\n",
    "the neck of radius 13 mm, up the neck, out along a straight shoulder and round a circular arc of\n",
    "30 mm radius to the top. The inner outline is the same path 0.8 mm smaller.\n",
    "\n",
    "**Reference.** A plane region of area $A$ whose centroid lies at the distance $\\bar r$ from the\n",
    "axis sweeps the volume $V = 2\\pi\\bar r A$ when it turns about the axis (Pappus and Guldin);\n",
    "area and centroid of each outline follow exactly from its lines and arcs. The filament is a tube\n",
    "of radius $a$ around a helix of $N$ turns, radius $R$ and pitch $p$:\n",
    "$V = \\pi a^2 N\\sqrt{(2\\pi R)^2 + p^2}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Path, PlanarRegion, Profile, Segment\n",
    "from onesim.cad.d3 import Assembly, Cylinder, Helix, Revolution, 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": [
    "## Outlines and parts\n",
    "\n",
    "The inner outline is the outer one made smaller by the wall thickness: the arc keeps its centre,\n",
    "the neck moves in, the top moves down and the bottom moves up, so the glass is closed at the base."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "neck, neck_height, sphere, centre, wall = 0.013, 0.025, 0.030, 0.065, 0.0008\n",
    "outer, inner = [\n",
    "    Profile(\n",
    "        Path(\n",
    "            (0.0, t),\n",
    "            (\n",
    "                Segment((neck - t, t)),\n",
    "                Segment((neck - t, neck_height)),\n",
    "                Segment(\n",
    "                    (\n",
    "                        (sphere - t) * np.cos(np.pi / 3),\n",
    "                        centre - (sphere - t) * np.sin(np.pi / 3),\n",
    "                    )\n",
    "                ),\n",
    "                Segment((0.0, centre + sphere - t), center=(0.0, centre)),\n",
    "                Segment((0.0, t)),\n",
    "            ),\n",
    "        )\n",
    "    )\n",
    "    for t in (0.0, wall)\n",
    "]\n",
    "helix = Helix(\n",
    "    radius=0.0015, pitch=0.001, turns=6, origin=(-0.003, 0.0, 0.06), axis=(1, 0, 0)\n",
    ")\n",
    "filament = Sweep(profile=Profile.circle(0.0003), path=helix).named(\"filament\")\n",
    "glass = (Revolution(profile=outer) - Revolution(profile=inner).named(\"inside\")).named(\n",
    "    \"glass\"\n",
    ")\n",
    "gas = (Revolution(profile=inner) - filament).named(\"gas\")\n",
    "base = Cylinder(radius=neck, length=0.02, origin=(0.0, 0.0, -0.02)).named(\"base\")\n",
    "bulb = Assembly(parts=[glass, gas, base, filament])\n",
    "print(\n",
    "    f\"parts: {', '.join(part.id for part in bulb.volumes)}; contacts: \"\n",
    "    f\"{', '.join(' / '.join(contact.parts) for contact in bulb.interfaces)}\"\n",
    ")\n",
    "\n",
    "lamp = Assembly(parts=[glass, Revolution(profile=inner).named(\"inside\"), base])\n",
    "mesh = TetrahedralMesher(target_size=0.003, gap_cells=1).generate(lamp)\n",
    "view = plots.Camera(elevation=15, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(15, 8))\n",
    "plots.geometry(\n",
    "    bulb,\n",
    "    selection={part.id: bulb.volume_of(part.id) for part in bulb.volumes},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Light bulb: glass, gas, base and filament\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    cell_values=quality(mesh)[\"shape\"],\n",
    "    limits=(0, 1),\n",
    "    plane=((0.0, 0.0, 0.04), (0.0, 1.0, 0.0)),\n",
    "    label=\"shape measure\",\n",
    "    camera=plots.Camera(elevation=5, azimuth=90),\n",
    "    title=f\"Glass, inside and base meshed as one, cut: {mesh.cell_count} cells\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Pappus and Guldin from the section values of the two outlines and the helix length of the\n",
    "filament against the volume of every part of the CAD model, then the three meshed parts."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "pappus = lambda profile: 2 * np.pi * profile.section_values().centroid[0] * profile.area\n",
    "coil = np.pi * 0.0003**2 * 6 * np.hypot(2 * np.pi * 0.0015, 0.001)\n",
    "closed = {\n",
    "    \"glass\": pappus(outer) - pappus(inner),\n",
    "    \"gas\": pappus(inner) - coil,\n",
    "    \"base\": np.pi * neck**2 * 0.02,\n",
    "    \"filament\": coil,\n",
    "}\n",
    "print(\"part        CAD [cm3]   closed form [cm3]   deviation\")\n",
    "for part in bulb.volumes:\n",
    "    print(\n",
    "        f\"{part.id:9s} {part.measure * 1e6:12.5f} {closed[part.id] * 1e6:16.5f} {part.measure / closed[part.id] - 1:+12.1e}\"\n",
    "    )\n",
    "cells = quality(mesh)[\"size\"]\n",
    "reference = {\"glass\": closed[\"glass\"], \"inside\": pappus(inner), \"base\": closed[\"base\"]}\n",
    "for part in lamp.volumes:\n",
    "    meshed = cells[list(mesh.region_cells(lamp.volume_of(part.id)))].sum()\n",
    "    print(\n",
    "        f\"mesh of {part.id:7s}: {meshed * 1e6:10.5f} cm3 against {reference[part.id] * 1e6:10.5f} cm3 ({meshed / reference[part.id] - 1:+.2%})\"\n",
    "    )\n",
    "print(\n",
    "    f\"filament wire length {helix.length * 1e3:.3f} mm, closed form {6 * np.hypot(2 * np.pi * 0.0015, 0.001) * 1e3:.3f} mm\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The two outlines in the half-plane and the filament with its helix, rendered."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(20, 7))\n",
    "plots.geometry(\n",
    "    PlanarRegion(profile=outer), title=\"Outline of the envelope (r, z)\", ax=fig[0]\n",
    ")\n",
    "plots.geometry(\n",
    "    PlanarRegion(profile=inner),\n",
    "    title=\"Outline of the inside, 0.8 mm smaller\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.render(\n",
    "    filament,\n",
    "    camera=plots.Camera(elevation=20, azimuth=-60),\n",
    "    material=\"steel\",\n",
    "    title=\"Filament: six turns of 0.6 mm wire\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Give the parts their materials with `regionwise`, heat the filament and let the gas carry the\n",
    "heat to the glass (`onesim.physics.heat_transfer`), or add the two support wires as swept paths\n",
    "from the base to the coil."
   ]
  }
 ]
}
