{
 "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": [
    "# Temperature field in a cooling flange\n",
    "\n",
    "Reaction fluids are cooled by passing them through a glass pipe with cooling flanges. The fluid\n",
    "heats the bore, the glass conducts the heat into the flanges, and room air removes it by\n",
    "**natural convection**. The pipe axis is horizontal ($x$), gravity points along $-y$.\n",
    "\n",
    "One half of the flange comes from the CAD file `cooling_flange_temperature.step`: a pipe of 16 mm\n",
    "bore and 4 mm wall with three fins, 4 mm wide and 10 mm tall, with rounded shoulders and tips,\n",
    "and a 12 mm connecting pipe with a 3 mm wall. The script `cooling_flange_temperature_geometry.py`\n",
    "builds it as a solid of revolution with the CAD objects of OneSimulation and names its faces.\n",
    "\n",
    "The glass obeys the stationary heat equation $\\nabla\\cdot(k\\nabla T)=0$ with\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `bore` | forced convection, $h_i=15$ W/(m² K), fluid at 363 K |\n",
    "| `outer` | natural convection $q=C(\\theta)\\,(T-T_a)^{5/4}$ to air at 298 K |\n",
    "| `pipe_end`, `flange_end`, `symmetry` | no heat flux |\n",
    "\n",
    "The air-side law is the laminar correlation for a horizontal cylinder (B. Sundén, *Kompendium i\n",
    "värmeöverföring*, 2003): $h_a=(k_\\mathrm{air}/D)\\,f(\\theta)\\,Gr^{1/4}$ with the Grashof number\n",
    "$Gr=g\\,(T-T_a)\\,D^3/(T_a\\nu^2)$ and a tabulated factor $f(\\theta)$ of the angle from the lowest\n",
    "point. It makes the problem nonlinear and three-dimensional: the bottom of the flange cools\n",
    "better than the top.\n",
    "\n",
    "**Reference.** No closed-form solution exists. The check is the energy balance (heat through the\n",
    "bore equals heat to the air) and a three-level mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import Block, Geometric, arc, bezier, line, merge_blocks, revolve\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.physics.heat_transfer import (\n",
    "    ConvectiveHeatFlux,\n",
    "    HeatConduction,\n",
    "    HeatFlux,\n",
    "    NonlinearHeatFlux,\n",
    ")\n",
    "from onesim.results.comparisons import convergence\n",
    "from onesim.simulation import Problem, Simulation\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 half flange with its named faces. The mesh consists of hexahedra: curved blocks\n",
    "cover the meridian section (straight sides, Bezier fillets at the shoulders, circular arcs at the\n",
    "fin tips, written as (radius, axial position)), `merge_blocks` joins them and `revolve` sweeps the\n",
    "section by 180° about the pipe axis. Bound to the loaded part, the mesh takes its boundary names\n",
    "from the faces of the STEP file."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "flange = load(\"cooling_flange_temperature.step\")\n",
    "faces = flange.boundaries\n",
    "mm = 1e-3\n",
    "bore, pipe_length, pipe_wall, wall, fin_height, fin_width = (\n",
    "    8 * mm,\n",
    "    12 * mm,\n",
    "    3 * mm,\n",
    "    4 * mm,\n",
    "    10 * mm,\n",
    "    4 * mm,\n",
    ")\n",
    "\n",
    "\n",
    "def flange_mesh(n):\n",
    "    \"\"\"Hexahedral mesh of the half flange with n cells across each block unit.\"\"\"\n",
    "    root, neck, shoulder, top = (\n",
    "        bore + wall,\n",
    "        -2 * pipe_length / 3,\n",
    "        bore + wall + fin_width / 2,\n",
    "        bore + wall + fin_height - fin_width / 2,\n",
    "    )\n",
    "    blocks = [\n",
    "        Block(\n",
    "            line((bore, -pipe_length), (bore, neck)),\n",
    "            line((bore, neck), (bore + pipe_wall, neck)),\n",
    "            line((bore + pipe_wall, -pipe_length), (bore + pipe_wall, neck)),\n",
    "            line((bore, -pipe_length), (bore + pipe_wall, -pipe_length)),\n",
    "            cells=(n, 2 * n),\n",
    "        ),\n",
    "        Block(\n",
    "            line((bore, neck), (bore, 0)),\n",
    "            line((bore, 0), (root, 0)),\n",
    "            bezier(\n",
    "                (bore + pipe_wall, neck),\n",
    "                (root, -pipe_length / 3),\n",
    "                (root, -pipe_length / 3),\n",
    "                (root, 0),\n",
    "            ),\n",
    "            line((bore, neck), (bore + pipe_wall, neck)),\n",
    "            cells=(2 * n, 2 * n),\n",
    "        ),\n",
    "    ]\n",
    "    for fin in range(3):\n",
    "        a, b, c, d = (\n",
    "            2 * fin_width * fin + offset\n",
    "            for offset in (0, fin_width / 2, 3 * fin_width / 2, 2 * fin_width)\n",
    "        )\n",
    "        tip = lambda start, end: arc((top, a + fin_width), fin_width / 2, start, end)\n",
    "        blocks += [\n",
    "            Block(\n",
    "                line((bore, a), (bore, b)),\n",
    "                line((bore, b), (shoulder, b)),\n",
    "                bezier((root, a), (root, b), (shoulder, b)),\n",
    "                line((bore, a), (root, a)),\n",
    "                cells=(n, 2 * n),\n",
    "            ),\n",
    "            Block(\n",
    "                line((bore, b), (bore, c)),\n",
    "                line((bore, c), (shoulder, c)),\n",
    "                line((shoulder, b), (shoulder, c)),\n",
    "                line((bore, b), (shoulder, b)),\n",
    "                cells=(2 * n, 2 * n),\n",
    "            ),\n",
    "            Block(\n",
    "                line((bore, c), (bore, d)),\n",
    "                line((bore, d), (root, d)),\n",
    "                bezier((shoulder, c), (root, c), (root, d)),\n",
    "                line((bore, c), (shoulder, c)),\n",
    "                cells=(n, 2 * n),\n",
    "            ),\n",
    "            Block(\n",
    "                line((shoulder, b), (shoulder, c)),\n",
    "                line((shoulder, c), (top, c)),\n",
    "                line((top, b), (top, c)),\n",
    "                line((shoulder, b), (top, b)),\n",
    "                cells=(2 * n, 3 * n),\n",
    "                grading=(None, Geometric(3 * n, growth=1.15 ** (-2 / n))),\n",
    "            ),\n",
    "            Block(\n",
    "                line((top, b), (top, c)),\n",
    "                tip(np.pi / 2, np.pi / 4),\n",
    "                tip(-np.pi / 4, np.pi / 4),\n",
    "                tip(-np.pi / 2, -np.pi / 4),\n",
    "                cells=(2 * n, n),\n",
    "            ),\n",
    "        ]\n",
    "    return revolve(\n",
    "        merge_blocks(blocks),\n",
    "        4 * n,\n",
    "        angle=np.pi,\n",
    "        axis=(1.0, 0.0, 0.0),\n",
    "        radial=(0.0, 1.0, 0.0),\n",
    "        geometry=flange,\n",
    "    )\n",
    "\n",
    "\n",
    "levels = (2, 3, 4)\n",
    "meshes = [flange_mesh(level) for level in levels]\n",
    "\n",
    "view = plots.Camera(elevation=14, azimuth=-58, up=\"y\")\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    flange,\n",
    "    selection={\"bore\": faces.bore, \"outer\": faces.outer, \"symmetry\": faces.symmetry},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Half flange 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} hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Fused silica conducts with $k=1.38$ W/(m K); air at 298 K has $k=0.0262$ W/(m K) and\n",
    "$\\nu=18\\times10^{-6}$ m²/s. Newton's method handles the nonlinear air-side flux, which enters as\n",
    "a `NonlinearHeatFlux` with its derivative $\\partial q/\\partial T$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "diameter = 2 * (bore + wall + fin_height)\n",
    "fluid_film, fluid_temperature, air_temperature = 15.0, 363.0, 298.0\n",
    "glass = IsotropicSolid(\n",
    "    density=2203.0,\n",
    "    specific_heat_capacity=703.0,\n",
    "    thermal_conductivity=1.38,\n",
    "    youngs_modulus=73.1e9,\n",
    "    poisson_ratio=0.17,\n",
    "    thermal_expansion_coefficient=5.5e-7,\n",
    ")\n",
    "angles = np.radians([0, 90, 100, 110, 120, 130, 140, 150, 160, 180])\n",
    "factors = np.array([0.48, 0.46, 0.45, 0.435, 0.42, 0.38, 0.35, 0.28, 0.22, 0.15])\n",
    "grashof_per_kelvin = 9.81 * diameter**3 / (air_temperature * 18e-6**2)\n",
    "\n",
    "\n",
    "def air_flux(temperature, y, z, power=1.25):\n",
    "    \"\"\"Natural-convection flux C(theta) (T - T_air)^(5/4) leaving the surface.\"\"\"\n",
    "    coefficient = (\n",
    "        0.0262\n",
    "        / diameter\n",
    "        * np.interp(np.arctan2(np.abs(z), -y), angles, factors)\n",
    "        * grashof_per_kelvin**0.25\n",
    "    )\n",
    "    return coefficient * np.maximum(temperature - air_temperature, 0.0) ** power\n",
    "\n",
    "\n",
    "model = HeatConduction(domain=flange.volume, material=glass, heating=0.0)\n",
    "problem = Problem(\n",
    "    name=\"Glass cooling flange\",\n",
    "    geometry=flange,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        ConvectiveHeatFlux(\n",
    "            boundary=faces.bore,\n",
    "            physics=model,\n",
    "            heat_transfer_coefficient=fluid_film,\n",
    "            ambient_temperature=fluid_temperature,\n",
    "        ),\n",
    "        NonlinearHeatFlux(\n",
    "            boundary=faces.outer,\n",
    "            physics=model,\n",
    "            flux=air_flux,\n",
    "            derivative=lambda T, y, z: 1.25 * air_flux(T, y, z, power=0.25),\n",
    "        ),\n",
    "        HeatFlux(\n",
    "            boundary=faces.pipe_end | faces.flange_end | faces.symmetry,\n",
    "            physics=model,\n",
    "            value=0.0,\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=SparseDirect(),\n",
    "    nonlinear_solver=Newton(),\n",
    "    initial_guess={model.temperature: 330.0},\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",
    "Heat rates of the full flange (twice the computed half). `convergence` returns the observed\n",
    "order and the Richardson estimate from the three meshes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "heat_in = [-2 * f.boundary_flux(faces.bore) for f in fields]\n",
    "heat_out = [2 * f.boundary_flux(faces.outer) for f in fields]\n",
    "study = convergence(heat_in, [1.0 / level for level in levels])\n",
    "surface = field.sample(along=faces.outer, subdivisions=2)\n",
    "print(\"level   hexahedra   heat through the bore [W]   heat to the air [W]\")\n",
    "for level, mesh, q_in, q_out in zip(levels, meshes, heat_in, heat_out):\n",
    "    print(f\"{level:5d} {mesh.cell_count:11d} {q_in:22.5f} {q_out:21.5f}\")\n",
    "print(f\"energy imbalance on the finest mesh: {abs(heat_in[-1] / heat_out[-1] - 1):.1e}\")\n",
    "print(\n",
    "    f\"observed order {study.order:.2f}, Richardson estimate {study.extrapolated:.4f} W \"\n",
    "    f\"(finest mesh {100 * (heat_in[-1] / study.extrapolated - 1):+.2f} %)\"\n",
    ")\n",
    "print(\n",
    "    f\"surface temperature between {surface.values.min():.1f} K and {surface.values.max():.1f} K\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The surface temperature of the complete flange, the vertical section through the axis (top of\n",
    "the flange above, bottom below), the mesh study, and the local air-side film coefficient."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "positions, surface_temperature = (\n",
    "    np.asarray(surface.positions),\n",
    "    np.asarray(surface.values).ravel(),\n",
    ")\n",
    "film = air_flux(surface_temperature, positions[:, 1], positions[:, 2]) / np.maximum(\n",
    "    surface_temperature - air_temperature, 1e-9\n",
    ")\n",
    "limits = (\n",
    "    surface_temperature.min(),\n",
    "    float(np.asarray(field.sample(along=faces.bore).values).max()),\n",
    ")\n",
    "fig = plots.figure(\n",
    "    layout=[[\"surface\", \"section\", \"study\"], [\"surface\", \"section\", \"film\"]],\n",
    "    size=(17, 6.2),\n",
    ")\n",
    "plots.surface(\n",
    "    field,\n",
    "    boundary=faces.outer | faces.pipe_end | faces.flange_end,\n",
    "    symmetry={\"planes\": [((0, 0, 1), (0, 0, 0))]},\n",
    "    limits=limits,\n",
    "    subdivisions=3,\n",
    "    camera=view,\n",
    "    label=\"T [K]\",\n",
    "    title=\"Surface temperature (full flange)\",\n",
    "    ax=fig[\"surface\"],\n",
    ")\n",
    "plots.surface(\n",
    "    field,\n",
    "    boundary=faces.symmetry,\n",
    "    limits=limits,\n",
    "    contours=10,\n",
    "    subdivisions=3,\n",
    "    label=\"T [K]\",\n",
    "    title=\"Vertical section through the axis\",\n",
    "    ax=fig[\"section\"],\n",
    ")\n",
    "plots.line(\n",
    "    levels,\n",
    "    {\"through the bore\": heat_in, \"to the air\": heat_out},\n",
    "    hlines={f\"Richardson estimate {study.extrapolated:.4f} W\": study.extrapolated},\n",
    "    markers=True,\n",
    "    xlabel=\"mesh level\",\n",
    "    ylabel=\"heat rate [W]\",\n",
    "    title=\"Mesh study of the cooling power\",\n",
    "    ax=fig[\"study\"],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"outer surface\": (\n",
    "            np.degrees(np.arctan2(np.abs(positions[:, 2]), -positions[:, 1])),\n",
    "            film,\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"angle from the bottom [deg]\",\n",
    "    ylabel=\"film coefficient [W/(m² K)]\",\n",
    "    title=\"Local natural-convection coefficient\",\n",
    "    legend=False,\n",
    "    ax=fig[\"film\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the bore radius between 6 and 10 mm in `cooling_flange_temperature_geometry.py` and write\n",
    "the STEP file again: the bore-side film resistance dominates, so a wider bore raises the cooling\n",
    "power noticeably. Add a fourth fin, or replace glass by a metal, and compare how much of the\n",
    "temperature drop sits in the wall and in the two films."
   ]
  }
 ]
}
