{
 "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": [
    "# Heat transfer through a finned pipe\n",
    "\n",
    "Warm water flows through a copper pipe, air blows across the outside. Thin annular **disk fins**\n",
    "enlarge the air-side area, twelve axial **grooves** the water-side area. The arrangement repeats\n",
    "with the fin pitch and every 30° around the axis, so one fin and a 15° wedge between two mirror\n",
    "planes represent the whole pipe.\n",
    "\n",
    "This element comes from the CAD file `finned_pipe_heat_transfer.step` (pipe: 20 mm bore, 2 mm\n",
    "wall, grooves 0.8 mm deep; fin: 0.6 mm thick, 35 mm outer radius, 5 mm pitch); the script\n",
    "`finned_pipe_heat_transfer_geometry.py` builds it with the CAD objects of OneSimulation and names\n",
    "its face groups. The copper obeys the stationary heat equation $\\nabla\\cdot(k\\nabla T)=0$ with\n",
    "\n",
    "| face group | condition |\n",
    "|---|---|\n",
    "| `bore` | convection to the water, $-k\\,\\partial_n T=h_w\\,(T-T_w)$ |\n",
    "| `fin_surface`, `pipe_surface` | convection to the air, $-k\\,\\partial_n T=h_a\\,(T-T_a)$ |\n",
    "| `end_planes`, `wedge_planes` | no heat flux (periodicity and mirror symmetry) |\n",
    "\n",
    "**Reference.** A thin annular fin between the radii $r_1$ and $r_2$ follows the fin equation with\n",
    "the Bessel-function solution $\\theta(r)=A\\,I_0(mr)+B\\,K_0(mr)$, $m=\\sqrt{2h/(kt)}$ (K. A. Gardner,\n",
    "*Trans. ASME* 67, 1945). With the base temperature fixed and a convective tip it gives the\n",
    "temperature along the fin and the **fin efficiency**, the heat the fin gives off relative to a\n",
    "fin at base temperature throughout."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import LocalRefinement, TetrahedralMesher, with_order\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.heat_transfer import ConvectiveHeatFlux, HeatConduction, HeatFlux\n",
    "from onesim.results.comparisons import convergence\n",
    "from onesim.results.integration import measure\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.special import i0, i1, k0, k1\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the element with its named face groups. It is meshed with tetrahedra at three cell\n",
    "sizes, half as large at the pipe wall; `with_order` gives them quadratic edges that follow the\n",
    "round faces."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "pipe = load(\"finned_pipe_heat_transfer.step\")\n",
    "faces = pipe.boundaries\n",
    "sizes = (0.7e-3, 0.5e-3, 0.35e-3)\n",
    "meshes = [\n",
    "    with_order(\n",
    "        TetrahedralMesher(\n",
    "            target_size=size,\n",
    "            refinements=(\n",
    "                LocalRefinement(\n",
    "                    region=faces.bore | faces.pipe_surface, target_size=size / 2\n",
    "                ),\n",
    "            ),\n",
    "        ).generate(pipe),\n",
    "        2,\n",
    "    )\n",
    "    for size in sizes\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=25, azimuth=-62)\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    pipe,\n",
    "    selection={\n",
    "        \"bore\": faces.bore,\n",
    "        \"fin_surface\": faces.fin_surface,\n",
    "        \"pipe_surface\": faces.pipe_surface,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"One fin pitch, 15° wedge, with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[0],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Coarsest mesh: {meshes[0].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Water at 30 °C flows at 0.5 m/s (Dittus-Boelter gives the film coefficient), air at 20 °C is\n",
    "taken with 80 W/(m² K)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mm = 1e-3\n",
    "bore_radius, wall_radius, fin_radius, fin_thickness, grooves = (\n",
    "    10 * mm,\n",
    "    12 * mm,\n",
    "    35 * mm,\n",
    "    0.6 * mm,\n",
    "    12,\n",
    ")\n",
    "wedge = np.pi / grooves\n",
    "water_temperature, air_temperature, air_film = 303.15, 293.15, 80.0\n",
    "water_film = (\n",
    "    0.023\n",
    "    * (0.5 * 2 * bore_radius / 0.801e-6) ** 0.8\n",
    "    * 5.42**0.4\n",
    "    * 0.615\n",
    "    / (2 * bore_radius)\n",
    ")\n",
    "copper = IsotropicSolid(\n",
    "    density=8933.0,\n",
    "    specific_heat_capacity=385.0,\n",
    "    thermal_conductivity=401.0,\n",
    "    youngs_modulus=110e9,\n",
    "    poisson_ratio=0.34,\n",
    "    thermal_expansion_coefficient=17e-6,\n",
    ")\n",
    "model = HeatConduction(domain=pipe.volume, material=copper, heating=0.0)\n",
    "problem = Problem(\n",
    "    name=\"Finned pipe periodic element\",\n",
    "    geometry=pipe,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        ConvectiveHeatFlux(\n",
    "            boundary=faces.bore,\n",
    "            physics=model,\n",
    "            heat_transfer_coefficient=water_film,\n",
    "            ambient_temperature=water_temperature,\n",
    "        ),\n",
    "        ConvectiveHeatFlux(\n",
    "            boundary=faces.fin_surface | faces.pipe_surface,\n",
    "            physics=model,\n",
    "            heat_transfer_coefficient=air_film,\n",
    "            ambient_temperature=air_temperature,\n",
    "        ),\n",
    "        HeatFlux(\n",
    "            boundary=faces.end_planes | faces.wedge_planes, physics=model, value=0.0\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "fields = [\n",
    "    Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "    .solve_stationary()\n",
    "    .field(model.temperature)\n",
    "    for mesh in meshes\n",
    "]\n",
    "field = fields[-1]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The fin efficiency is the heat leaving the fin divided by $h_a A_\\mathrm{fin}(T_b-T_a)$, with\n",
    "the base temperature $T_b$ averaged over the fin root. Heat rates are given for one pitch of the\n",
    "full circumference (24 wedges)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def annular_fin(r1, r2, t, h, k):\n",
    "    \"\"\"Efficiency and temperature profile theta(r)/theta_base of an annular fin with a convective tip.\"\"\"\n",
    "    m = np.sqrt(2 * h / (k * t))\n",
    "    A, B = np.linalg.solve(\n",
    "        [\n",
    "            [i0(m * r1), k0(m * r1)],\n",
    "            [k * m * i1(m * r2) + h * i0(m * r2), -k * m * k1(m * r2) + h * k0(m * r2)],\n",
    "        ],\n",
    "        [1.0, 0.0],\n",
    "    )\n",
    "    base_flux = -k * m * (A * i1(m * r1) - B * k1(m * r1))\n",
    "    return base_flux * 2 * np.pi * r1 * t / (\n",
    "        h * (2 * np.pi * (r2**2 - r1**2) + 2 * np.pi * r2 * t)\n",
    "    ), lambda r: A * i0(m * r) + B * k0(m * r)\n",
    "\n",
    "\n",
    "x_root, angle_root = np.meshgrid(\n",
    "    (np.arange(16) + 0.5) / 16 * fin_thickness - fin_thickness / 2,\n",
    "    (np.arange(48) + 0.5) / 48 * wedge,\n",
    ")\n",
    "root = np.column_stack(\n",
    "    (\n",
    "        x_root.ravel(),\n",
    "        wall_radius * np.cos(angle_root.ravel()),\n",
    "        wall_radius * np.sin(angle_root.ravel()),\n",
    "    )\n",
    ")\n",
    "base_temperature = [float(np.mean(f.evaluate(root))) for f in fields]\n",
    "efficiency = [\n",
    "    f.boundary_flux(faces.fin_surface)\n",
    "    / (air_film * measure(f, boundary=faces.fin_surface) * (T - air_temperature))\n",
    "    for f, T in zip(fields, base_temperature)\n",
    "]\n",
    "exact_efficiency, fin_profile = annular_fin(\n",
    "    wall_radius, fin_radius, fin_thickness, air_film, copper.thermal_conductivity\n",
    ")\n",
    "study = convergence(efficiency, sizes)\n",
    "heat_water, heat_air = -24 * field.boundary_flux(faces.bore), 24 * field.boundary_flux(\n",
    "    faces.fin_surface | faces.pipe_surface\n",
    ")\n",
    "print(\"cell size [mm]   tetrahedra   fin efficiency\")\n",
    "for size, mesh, eta in zip(sizes, meshes, efficiency):\n",
    "    print(f\"{size / mm:14.2f} {mesh.cell_count:12d} {eta:16.5f}\")\n",
    "print(\n",
    "    f\"Richardson estimate {study.extrapolated:.5f} (order {study.order:.2f}),  Bessel solution {exact_efficiency:.5f},  \"\n",
    "    f\"deviation of the finest mesh {100 * (efficiency[-1] / exact_efficiency - 1):+.3f} %\"\n",
    ")\n",
    "print(\n",
    "    f\"heat from the water {heat_water:.5f} W, heat to the air {heat_air:.5f} W, imbalance {abs(heat_water / heat_air - 1):.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The surface temperature of four pitches (completed by the mirror planes and the 12-fold\n",
    "rotation), the section through the fin mid-plane near the grooved bore, the temperature along\n",
    "the fin against the Bessel solution, and the mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "pitch = pipe.size[0]\n",
    "surface_temperature = np.asarray(\n",
    "    field.sample(along=faces.fin_surface | faces.bore).values\n",
    ")\n",
    "limits = (float(surface_temperature.min()), float(surface_temperature.max()))\n",
    "mirror, repeat = [((0, 0, 1), (0, 0, 0))], [\n",
    "    ((1, 0, 0), (x, 0, 0)) for x in (pitch / 2, -pitch / 2, 1.5 * pitch)\n",
    "]\n",
    "r_line = np.linspace(wall_radius, fin_radius - 0.05 * mm, 80)\n",
    "along_fin = {\n",
    "    f\"3D model, {np.degrees(angle):.0f}° from a groove ridge\": np.column_stack(\n",
    "        (np.zeros_like(r_line), r_line * np.cos(angle), r_line * np.sin(angle))\n",
    "    )\n",
    "    for angle in (0.0, wedge)\n",
    "}\n",
    "fig = plots.figure(\n",
    "    layout=[\n",
    "        [\"surface\", \"surface\", \"cut\", \"fin\"],\n",
    "        [\"surface\", \"surface\", \"cut\", \"study\"],\n",
    "    ],\n",
    "    size=(17, 6.4),\n",
    ")\n",
    "plots.surface(\n",
    "    field,\n",
    "    boundary=faces.fin_surface | faces.pipe_surface | faces.bore,\n",
    "    symmetry={\"planes\": mirror + repeat, \"sector\": ((1, 0, 0), grooves)},\n",
    "    limits=limits,\n",
    "    subdivisions=1,\n",
    "    camera=plots.Camera(elevation=25, azimuth=-62, distance=0.85),\n",
    "    label=\"T [K]\",\n",
    "    title=\"Surface temperature, four pitches\",\n",
    "    ax=fig[\"surface\"],\n",
    ")\n",
    "plots.section(\n",
    "    field,\n",
    "    plane=Plane(origin=(0.0, 0.0, 0.0), normal=(1.0, 0.0, 0.0)),\n",
    "    symmetry={\"planes\": mirror, \"sector\": ((1, 0, 0), grooves)},\n",
    "    subdivisions=3,\n",
    "    contours=12,\n",
    "    limits=limits,\n",
    "    label=\"T [K]\",\n",
    "    title=\"Fin mid-plane near the grooved bore\",\n",
    "    xlimits=(-14 * mm, 14 * mm),\n",
    "    ylimits=(-14 * mm, 14 * mm),\n",
    "    ax=fig[\"cut\"],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        label: (\n",
    "            r_line[::4] / mm,\n",
    "            (\n",
    "                (np.asarray(field.evaluate(points)).ravel() - air_temperature)\n",
    "                / (base_temperature[-1] - air_temperature)\n",
    "            )[::4],\n",
    "        )\n",
    "        for label, points in along_fin.items()\n",
    "    },\n",
    "    reference={\"Bessel solution\": (r_line / mm, fin_profile(r_line))},\n",
    "    xlabel=\"radius [mm]\",\n",
    "    ylabel=\"(T - T_air) / (T_base - T_air)\",\n",
    "    title=\"Temperature along the fin\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[\"fin\"],\n",
    ")\n",
    "plots.line(\n",
    "    np.array(sizes) / mm,\n",
    "    {\"3D model\": efficiency},\n",
    "    hlines={\"Bessel solution\": exact_efficiency},\n",
    "    markers=True,\n",
    "    xlabel=\"cell size [mm]\",\n",
    "    ylabel=\"fin efficiency\",\n",
    "    title=\"Mesh study\",\n",
    "    ax=fig[\"study\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Halve the fin thickness or double the air-side coefficient and watch the fin efficiency fall:\n",
    "the fin tip then runs colder and adds less. Set the groove depth to zero in\n",
    "`finned_pipe_heat_transfer_geometry.py` and write the STEP file again to see how much of the total\n",
    "resistance sits on the water side."
   ]
  }
 ]
}
