{
 "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": [
    "# Natural convection cooling of a vacuum flask\n",
    "\n",
    "A vacuum flask holds coffee at 90 °C (radius 40 mm, 200 mm high). The coffee sits in a glass\n",
    "vessel (1.5 mm, $k=1.0$ W/(m K)) surrounded by an evacuated gap (4 mm) and a stainless steel\n",
    "shell (1 mm, $k=16$ W/(m K)); a plastic shoulder ring (1.5 mm) closes the gap at the top, and a plastic\n",
    "stopper (35 mm, $k=0.2$ W/(m K)) closes the flask. Across the vacuum heat passes only by\n",
    "radiation between the silvered walls ($\\varepsilon=0.05$); linearised about the mean gap\n",
    "temperature it acts like a conductivity\n",
    "\n",
    "$$k_\\mathrm{vac}=\\frac{4\\sigma T_m^3\\,\\delta}{1/\\varepsilon_1+1/\\varepsilon_2-1}.$$\n",
    "\n",
    "Steady conduction $\\nabla\\cdot(k\\nabla T)=0$ holds in all solids. The coffee is well mixed and\n",
    "holds its temperature over the hour considered; outside, free convection and radiation carry the\n",
    "heat to the room at 25 °C, $q''=(h_c+h_r)(T-T_\\infty)$, with $h_c$ from the Churchill-Chu\n",
    "correlation for the vertical side and from $\\overline{Nu}=0.54\\,Ra^{1/4}$ for the hot top\n",
    "(F. P. Incropera et al., *Fundamentals of Heat and Mass Transfer*, Eqs. 9.26 and 9.30) and\n",
    "$h_r=4\\varepsilon\\sigma T_m^3$ (steel $\\varepsilon=0.15$, plastic $\\varepsilon=0.9$).\n",
    "\n",
    "The geometry comes from the CAD files `vacuum_flask_cooling*.step`, written by\n",
    "`vacuum_flask_cooling_geometry.py` with the CAD objects of OneSimulation: the flask and each\n",
    "material region.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `coffee` | $T=90$ °C |\n",
    "| `side`, `top` | $q''=(h_c+h_r)(T-T_\\infty)$ |\n",
    "| `base` | insulated (standing on the floor) |\n",
    "| `start` (the cut through the axis) | symmetry |\n",
    "\n",
    "**Reference.** A thermal resistance estimate: the cylindrical wall layers in series with the\n",
    "outer film, $R_\\mathrm{side}=\\big[\\sum\\ln(r_{i+1}/r_i)/k_i\\big]/(2\\pi H)+1/(2\\pi r_4Hh_\\mathrm{side})$,\n",
    "and the stopper as a slab, $R_\\mathrm{top}=(t/k_p+1/h_\\mathrm{top})/(\\pi r_1^2)$; it leaves out the\n",
    "shoulder ring that bridges the vacuum. In the steady state the heat leaving the coffee must leave\n",
    "the flask."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid, regionwise\n",
    "from onesim.meshing import TriangularMesher, joined\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, RevolvedH1SpaceFactory\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.heat_transfer import (\n",
    "    ConvectiveHeatFlux,\n",
    "    FixedTemperature,\n",
    "    HeatConduction,\n",
    "    HeatFlux,\n",
    ")\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 meshes\n",
    "\n",
    "Every part is cut in the plane through the axis. The material regions are meshed one by one with\n",
    "all their edges divided into equal pieces of the same size, so `joined` merges them node on node\n",
    "into one mesh of the flask; two meshes, with 0.5 mm and 0.25 mm pieces, form the mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "names = (\"glass\", \"vacuum\", \"shell\", \"neck\", \"stopper\")\n",
    "flask = load(\"vacuum_flask_cooling.step\").section((0, 1, 0))\n",
    "regions = {\n",
    "    name: load(f\"vacuum_flask_cooling_{name}.step\").section((0, 1, 0)) for name in names\n",
    "}\n",
    "faces = flask.boundaries\n",
    "meshes = {\n",
    "    size: joined(\n",
    "        [\n",
    "            TriangularMesher(\n",
    "                target_size=2e-3,\n",
    "                hard_sizes={edge.id: size for edge in region.edges},\n",
    "                grading=0.25,\n",
    "            ).generate(region)\n",
    "            for region in regions.values()\n",
    "        ],\n",
    "        geometry=flask,\n",
    "    )\n",
    "    for size in (5e-4, 2.5e-4)\n",
    "}\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 7))\n",
    "plots.geometry(\n",
    "    [load(f\"vacuum_flask_cooling_{name}.step\").named(name) for name in names],\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=20, azimuth=-60),\n",
    "    title=\"Half of the flask, one part per material\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[5e-4],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Flask: {meshes[5e-4].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conduction model with free-convection coefficients\n",
    "\n",
    "The coefficients are evaluated for a surface 3 K above the room (air at 27 °C), the vacuum\n",
    "conductivity at the mean gap temperature. `regionwise` lays the conductivities on the regions,\n",
    "and the revolved space makes the planar elements axisymmetric."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "coffee, ambient, gravity, sigma = 363.15, 298.15, 9.81, 5.670e-8\n",
    "r1, r2, r3, r4, base, height, stopper = (\n",
    "    0.040,\n",
    "    0.0415,\n",
    "    0.0455,\n",
    "    0.0465,\n",
    "    -6.5e-3,\n",
    "    regions[\"shell\"].size[1],\n",
    "    0.035,\n",
    ")\n",
    "k_glass, k_steel, k_plastic = 1.0, 16.0, 0.2\n",
    "k_vacuum = 4 * sigma * 330.0**3 * (r3 - r2) / (1 / 0.05 + 1 / 0.05 - 1)\n",
    "air_k, air_nu, air_alpha = 0.0262, 1.59e-5, 2.25e-5\n",
    "rayleigh = lambda length: gravity / 300.15 * 3.0 * length**3 / (air_nu * air_alpha)\n",
    "h_side_c = (\n",
    "    air_k\n",
    "    / height\n",
    "    * (\n",
    "        0.68\n",
    "        + 0.670\n",
    "        * rayleigh(height) ** 0.25\n",
    "        / (1 + (0.492 * air_alpha / air_nu) ** (9 / 16)) ** (4 / 9)\n",
    "    )\n",
    ")\n",
    "h_top_c = air_k / (r1 / 2) * 0.54 * rayleigh(r1 / 2) ** 0.25\n",
    "h_side, h_top = (\n",
    "    h_side_c + 4 * 0.15 * sigma * 300.15**3,\n",
    "    h_top_c + 4 * 0.9 * sigma * 300.15**3,\n",
    ")\n",
    "material = IsotropicSolid(\n",
    "    density=1.0,\n",
    "    specific_heat_capacity=1.0,\n",
    "    youngs_modulus=1.0,\n",
    "    poisson_ratio=0.3,\n",
    "    thermal_expansion_coefficient=0.0,\n",
    "    thermal_conductivity=regionwise(\n",
    "        (\n",
    "            (regions[\"glass\"], k_glass),\n",
    "            (regions[\"vacuum\"], k_vacuum),\n",
    "            (regions[\"shell\"], k_steel),\n",
    "            (regions[\"neck\"], k_plastic),\n",
    "        ),\n",
    "        default=k_plastic,\n",
    "        unit=\"W/m/K\",\n",
    "    ),\n",
    ")\n",
    "heat = HeatConduction(domain=flask.domain(), material=material)\n",
    "problem = Problem(\n",
    "    name=\"Vacuum flask, conduction\",\n",
    "    geometry=flask,\n",
    "    physics=(heat,),\n",
    "    boundary_conditions=(\n",
    "        FixedTemperature(physics=heat, boundary=faces.coffee, value=coffee),\n",
    "        ConvectiveHeatFlux(\n",
    "            physics=heat,\n",
    "            boundary=faces.side,\n",
    "            heat_transfer_coefficient=h_side,\n",
    "            ambient_temperature=ambient,\n",
    "        ),\n",
    "        ConvectiveHeatFlux(\n",
    "            physics=heat,\n",
    "            boundary=faces.top,\n",
    "            heat_transfer_coefficient=h_top,\n",
    "            ambient_temperature=ambient,\n",
    "        ),\n",
    "        HeatFlux(physics=heat, boundary=faces.base | faces.start, value=0.0),\n",
    "    ),\n",
    ")\n",
    "conduction = {\n",
    "    size: Simulation(\n",
    "        problem=problem,\n",
    "        mesh=mesh,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(\n",
    "                element=Lagrange(order=2), provider=RevolvedH1SpaceFactory()\n",
    "            ),\n",
    "            linear_solver=SparseDirect(),\n",
    "        ),\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(heat.temperature)\n",
    "    for size, mesh in meshes.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cooling power\n",
    "\n",
    "The fluxes through the named faces are the full-revolution heat flows in W. The resistance\n",
    "estimate covers the radial path only, while the steel shell also spreads the heat that reaches it\n",
    "through the base and near the top; the heat flux across the vacuum at mid-height, read from the\n",
    "temperature gradient, is the like-for-like comparison."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "side_1d = (coffee - ambient) / (\n",
    "    (np.log(r2 / r1) / k_glass + np.log(r3 / r2) / k_vacuum + np.log(r4 / r3) / k_steel)\n",
    "    / (2 * np.pi * height)\n",
    "    + 1 / (2 * np.pi * r4 * height * h_side)\n",
    ")\n",
    "top_1d = (coffee - ambient) * np.pi * r1**2 / (stopper / k_plastic + 1 / h_top)\n",
    "mass = 1000.0 * np.pi * r1**2 * 0.2\n",
    "print(\n",
    "    f\"h_side = {h_side_c:.2f} + {h_side - h_side_c:.2f} (radiation), h_top = {h_top_c:.2f} + {h_top - h_top_c:.2f} W/(m² K); \"\n",
    "    f\"vacuum conductivity {1e3 * k_vacuum:.3f} mW/(m K)\"\n",
    ")\n",
    "print(\"mesh      triangles   from the coffee [W]   side [W]   top [W]   balance\")\n",
    "for size, temperature in conduction.items():\n",
    "    out_side, out_top, taken = (\n",
    "        temperature.boundary_flux(faces.side),\n",
    "        temperature.boundary_flux(faces.top),\n",
    "        -temperature.boundary_flux(faces.coffee),\n",
    "    )\n",
    "    print(\n",
    "        f\"{1e3 * size:.2f} mm {meshes[size].cell_count:11d} {taken:21.4f} {out_side:10.4f} {out_top:9.4f} \"\n",
    "        f\"{100 * (out_side + out_top - taken) / taken:+8.3f} %\"\n",
    "    )\n",
    "temperature = conduction[2.5e-4]\n",
    "out_side, out_top = temperature.boundary_flux(faces.side), temperature.boundary_flux(\n",
    "    faces.top\n",
    ")\n",
    "print(\n",
    "    f\"resistance estimate: side {side_1d:.4f} W (simulation {100 * (out_side / side_1d - 1):+.1f} %), stopper {top_1d:.4f} W \"\n",
    "    f\"(simulation top incl. shoulder ring {100 * (out_top / top_1d - 1):+.1f} %)\"\n",
    ")\n",
    "print(\n",
    "    f\"cooling power {out_side + out_top:.3f} W; the coffee ({mass:.3f} kg) cools by {3600 * (out_side + out_top) / (mass * 4190):.2f} K per hour\"\n",
    ")\n",
    "surface = temperature.evaluate(\n",
    "    np.column_stack((np.full(50, r4 - 1e-7), np.linspace(0.0, 0.2, 50)))\n",
    ").ravel()\n",
    "print(\n",
    "    f\"outer shell {surface.mean() - ambient:.2f} K above the room on average (the coefficients assumed 3 K)\"\n",
    ")\n",
    "flux_1d = side_1d / (2 * np.pi * r3 * height)\n",
    "flux = -k_vacuum * np.ravel(temperature.gradient([[r3 - 1e-4, 0.1]]))[0]\n",
    "print(\n",
    "    f\"heat flux across the vacuum at mid-height: {flux:.3f} W/m², resistance estimate {flux_1d:.3f} W/m² ({100 * (flux / flux_1d - 1):+.1f} %)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Temperature in the whole flask wall, near the top, where stopper and shoulder ring carry most of\n",
    "the heat, and through the wall at mid-height, where the vacuum takes almost the whole drop."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "wall = np.linspace(r1 + 1e-7, r4 - 1e-7, 300)\n",
    "fig = plots.figure(layout=[[\"top\", \"whole\"], [\"wall\", \"whole\"]], size=(14, 12))\n",
    "plots.surface(\n",
    "    temperature,\n",
    "    component=lambda T, position: T - 273.15,\n",
    "    limits=(25.0, 90.0),\n",
    "    contours=12,\n",
    "    subdivisions=2,\n",
    "    label=\"T [°C]\",\n",
    "    xlabel=\"r [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    xlimits=(0.0, 0.05),\n",
    "    ylimits=(0.17, 0.24),\n",
    "    title=\"Flask top: stopper and shoulder ring\",\n",
    "    ax=fig[\"top\"],\n",
    ")\n",
    "plots.surface(\n",
    "    temperature,\n",
    "    component=lambda T, position: T - 273.15,\n",
    "    limits=(25.0, 90.0),\n",
    "    contours=12,\n",
    "    subdivisions=2,\n",
    "    label=\"T [°C]\",\n",
    "    xlabel=\"r [m]\",\n",
    "    ylabel=\"z [m]\",\n",
    "    title=\"Whole flask\",\n",
    "    ax=fig[\"whole\"],\n",
    ")\n",
    "plots.line(\n",
    "    1e3 * wall,\n",
    "    {\n",
    "        \"simulation, mid-height\": temperature.evaluate(\n",
    "            np.column_stack((wall, np.full_like(wall, 0.1)))\n",
    "        ).ravel()\n",
    "        - 273.15\n",
    "    },\n",
    "    vlines={\"glass | vacuum\": 1e3 * r2, \"vacuum | steel\": 1e3 * r3},\n",
    "    xlabel=\"radius [mm]\",\n",
    "    ylabel=\"temperature [°C]\",\n",
    "    title=\"Through the wall: the vacuum takes the drop\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[\"wall\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lose the vacuum (air in the gap) or the silvering ($\\varepsilon=0.9$) in the gap conductivity and\n",
    "watch the cooling power rise tenfold; make the stopper thinner in `vacuum_flask_cooling_geometry.py`;\n",
    "or let the coffee cool in time with its heat capacity."
   ]
  }
 ]
}
