{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "nickel_rod_boiling_quench-1",
   "source": [
    "# Cooling a nickel rod in boiling water\n",
    "\n",
    "A nickel rod starts at 108 °C in saturated water at 100 °C. Heat leaves through the curved surface. As the mantle cools, the centerline stays hot. This 3D calculation follows a 50 mm rod, 10 mm in diameter, for three minutes.\n",
    "\n",
    "The Rohsenow pool-boiling correlation gives a wall flux $q=C(T_w-T_{sat})^3$ for a specified fluid and surface finish. The example uses the water/nickel coefficient 0.006 and holds the same empirical law throughout the cooling curve. The late-time tail extrapolates that law as the superheat approaches zero. See W. M. Rohsenow, *Transactions of the ASME* 74 (1952), 969–976, and A. Bejan, *Heat Transfer* (1993), p. 427."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "nickel_rod_boiling_quench-2",
   "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 Geometric, disc_blocks, extrude, merge_blocks\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.numerics.time import AdaptiveTimeStep, BackwardEuler\n",
    "from onesim.physics.heat_transfer import HeatConduction, HeatFlux, NonlinearHeatFlux, rohsenow_pool_boiling_flux\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "nickel_rod_boiling_quench-3",
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "Read the rod and its named boundaries from STEP. Compare two annular block meshes through the length. The finer mesh has more circumferential, radial and axial nodes. Heat leaves the mantle while the ends are insulated."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "nickel_rod_boiling_quench-4",
   "source": [
    "rod = load(\"nickel_rod_boiling_quench.step\")\n",
    "faces = rod.boundaries\n",
    "radius, length = rod.size[0] / 2, rod.size[2]\n",
    "meshes = []\n",
    "for sectors, radial, axial in ((6, 3, 3), (10, 5, 6)):\n",
    "    blocks = disc_blocks((0, 0), (0.6 * radius, radius), sectors, (radial, radial), core=0.5)\n",
    "    meshes.append(extrude(merge_blocks(blocks, order=1), length, Geometric(axial, ratio=1), geometry=rod))\n",
    "camera = plots.Camera(elevation=30, azimuth=-60, roll=30, distance=1.2)\n",
    "fig = plots.figure(1, 2, size=(11, 5))\n",
    "plots.geometry(rod, selection={\"boiling surface\": faces.mantle, \"insulated\": faces.ends}, labels=False,\n",
    "               camera=camera, title=\"Nickel rod\", ax=fig[0])\n",
    "plots.mesh(meshes[-1], groups=(\"all\",), camera=camera, legend=False, title=\"Hexahedral mesh\", ax=fig[1])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "nickel_rod_boiling_quench-5",
   "source": [
    "## Surface flux and transient conduction\n",
    "\n",
    "The water properties are for saturation at atmospheric pressure. Evaluate the boiling law at 1 K superheat to obtain its cubic coefficient. Use the derivative $3C(T_w-T_{sat})^2$ in the implicit solve. Adaptive stepping resolves the initial rapid cooling."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "nickel_rod_boiling_quench-6",
   "source": [
    "saturation, initial = 373.15, 381.15\n",
    "C = float(rohsenow_pool_boiling_flux(1.0, liquid_viscosity=2.79e-4, vaporization_enthalpy=2.257e6,\n",
    "    gravity=9.81, density_difference=957.9 - 0.6, surface_tension=0.0589, liquid_heat_capacity=4217,\n",
    "    prandtl=1.76, surface_fluid_coefficient=0.006, prandtl_exponent=1))\n",
    "nickel = IsotropicSolid(density=8900, specific_heat_capacity=444, thermal_conductivity=90.7,\n",
    "    youngs_modulus=2e11, poisson_ratio=0.31, thermal_expansion_coefficient=1.3e-5)\n",
    "model = HeatConduction(domain=rod.volume, material=nickel)\n",
    "problem = Problem(name=\"Nickel rod in saturated water\", geometry=rod, physics=(model,), boundary_conditions=(\n",
    "    HeatFlux(physics=model, boundary=faces.ends, value=0.0),\n",
    "    NonlinearHeatFlux(physics=model, boundary=faces.mantle, flux=lambda T: C * np.maximum(T-saturation, 0)**3,\n",
    "                      derivative=lambda T: 3*C * np.maximum(T-saturation, 0)**2)),\n",
    "    initial_conditions=(InitialValue(model.temperature, initial),))\n",
    "method = Numerics(spatial=FiniteElement(element=Lagrange(order=1)), linear_solver=SparseDirect(),\n",
    "                  nonlinear_solver=Newton(relative_tolerance=1e-7), time_integrator=BackwardEuler())\n",
    "steps = AdaptiveTimeStep(initial=0.02, minimum=1e-6, maximum=10, relative_tolerance=0, absolute_tolerance=0.04)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "nickel_rod_boiling_quench-7",
   "source": [
    "## Core, surface and lumped reference\n",
    "\n",
    "An isothermal rod with the same heat capacity and cooled area obeys $\\rho c_p V \\,d\\theta/dt=-AC\\theta^3$, where $\\theta=T-T_{sat}$ and $A/V=2/R$. Its closed-form solution approaches the full field as the radial gradient fades. The early cross-section shows the gradient that the lumped calculation omits."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "nickel_rod_boiling_quench-8",
   "source": [
    "for mesh in meshes:\n",
    "    T = Simulation(problem=problem, mesh=mesh, numerics=method).run(start_time=0, end_time=180, time_step=steps).field(model.temperature)\n",
    "    wall_nodes = mesh.coordinates[np.unique(mesh.facets(faces.mantle))]\n",
    "    wall_probe = wall_nodes[np.argmin(np.linalg.norm(wall_nodes - [radius, 0, length/2], axis=1))]\n",
    "    times, probes = T.time_series([[0, 0, length/2], wall_probe])\n",
    "    print(f\"{len(mesh.coordinates)} nodes, {mesh.cell_count} hexes: peak core–wall gap {np.max(probes[:, 0]-probes[:, 1]):.3f} K, final core {probes[-1, 0]-273.15:.4f} °C\")\n",
    "lumped = saturation + ((initial-saturation)**-2 + 4*C*times/(radius*nickel.density*nickel.specific_heat_capacity))**-0.5\n",
    "print(f\"Initial cooling flux: {C*(initial-saturation)**3/1e3:.1f} kW/m²\")\n",
    "print(f\"Largest core–surface gap: {np.max(probes[:, 0]-probes[:, 1]):.2f} K\")\n",
    "print(f\"At 180 s: core {probes[-1, 0]-273.15:.3f} °C, surface {probes[-1, 1]-273.15:.3f} °C, lumped {lumped[-1]-273.15:.3f} °C\")\n",
    "peak = times[np.argmax(probes[:, 0]-probes[:, 1])]\n",
    "fig = plots.figure(1, 2, size=(11.5, 4.7))\n",
    "plots.section(T, time=peak, plane=Plane(origin=(0, 0, length/2), normal=(0, 0, 1)),\n",
    "              component=lambda T, position: T-273.15, length_unit=\"mm\", contours=8, subdivisions=3,\n",
    "              title=f\"Mid-section at {peak:.2f} s\", label=\"Temperature [°C]\", ax=fig[0])\n",
    "plots.line(times[1:], {\"Core\": probes[1:, 0]-273.15, \"Surface\": probes[1:, 1]-273.15},\n",
    "           reference={\"Lumped rod\": lumped[1:]-273.15}, scale=\"logx\", xlabel=\"Time [s]\",\n",
    "           ylabel=\"Temperature [°C]\", title=\"Cooling from 108 °C\", ax=fig[1])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
