{
 "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": [
    "# Out-of-plane heat transfer in a thin plate\n",
    "\n",
    "An aluminium plate, 100 mm × 100 mm and only 1 mm thick, is held at 100 °C along one edge and\n",
    "immersed in a liquid at 20 °C that cools both large faces with a film coefficient\n",
    "$h=100$ W/(m² K). The other three edges are insulated. Heat flows along the plate and leaves it\n",
    "through its faces, out of the plane.\n",
    "\n",
    "The plate is so thin that its temperature hardly changes through the thickness: the Biot number\n",
    "$hd/k=5\\times10^{-4}$ is tiny. Averaged over the thickness, the heat equation becomes the fin\n",
    "equation with the out-of-plane loss as a sink,\n",
    "\n",
    "$$k\\,d\\,\\frac{d^2T}{dx^2}=2h\\,(T-T_\\infty),$$\n",
    "\n",
    "which is how thin plates are often reduced to two (here even one) dimensions. This notebook\n",
    "solves the full three-dimensional plate instead and checks the reduction.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `base`, $x=0$ | $T=100$ °C |\n",
    "| `faces`, both large faces | $-k\\,\\partial_nT=h\\,(T-T_\\infty)$, $h=100$ W/(m² K), $T_\\infty=20$ °C |\n",
    "| `edges`: the far edge and the two sides | insulated |\n",
    "\n",
    "The plate comes from the CAD file `thin_plate_fin_cooling.step`; the script\n",
    "`thin_plate_fin_cooling_geometry.py` builds it with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** The fin with an insulated tip (F. P. Incropera, D. P. DeWitt, *Fundamentals of Heat\n",
    "and Mass Transfer*, ch. 3.6):\n",
    "\n",
    "$$\\frac{T(x)-T_\\infty}{T_b-T_\\infty}=\\frac{\\cosh m(L-x)}{\\cosh mL},\\qquad\n",
    "  Q=\\sqrt{2hk\\,d}\\;W\\,(T_b-T_\\infty)\\tanh mL,\\qquad m=\\sqrt{\\frac{2h}{k\\,d}} .$$"
   ]
  },
  {
   "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 Geometric, Piecewise, StructuredHexahedralMesher\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 (\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 mesh\n",
    "\n",
    "`load` returns the plate with its named faces. Quadratic hexahedra, one through the thickness and\n",
    "graded along the plate towards the held edge, where the temperature falls fastest."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plate = load(\"thin_plate_fin_cooling.step\")\n",
    "faces = plate.boundaries\n",
    "length, width, thickness = plate.size\n",
    "grading = (\n",
    "    Piecewise(((length, Geometric(24, ratio=4.0)),)),\n",
    "    Piecewise(((width, Geometric(4, ratio=1.0)),)),\n",
    "    Piecewise(((thickness, Geometric(1, ratio=1.0)),)),\n",
    ")\n",
    "mesh = StructuredHexahedralMesher(\n",
    "    cells=tuple(g.cells for g in grading), grading=grading\n",
    ").generate(plate)\n",
    "\n",
    "view = plots.Camera(elevation=30, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(14, 5.5))\n",
    "plots.geometry(\n",
    "    plate,\n",
    "    selection={\n",
    "        \"base, 100 °C\": faces.base,\n",
    "        \"cooled faces\": faces.faces,\n",
    "        \"insulated edges\": faces.edges,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Plate with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{mesh.cell_count} quadratic hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model and solution"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "base, liquid, film = 373.15, 293.15, 100.0\n",
    "aluminium = IsotropicSolid(\n",
    "    density=2700.0,\n",
    "    specific_heat_capacity=900.0,\n",
    "    thermal_conductivity=200.0,\n",
    "    youngs_modulus=7e10,\n",
    "    poisson_ratio=0.33,\n",
    "    thermal_expansion_coefficient=2.3e-5,\n",
    ")\n",
    "model = HeatConduction(domain=plate.volume, material=aluminium, heating=0.0)\n",
    "problem = Problem(\n",
    "    name=\"Thin plate cooled on both faces\",\n",
    "    geometry=plate,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedTemperature(boundary=faces.base, physics=model, value=base),\n",
    "        ConvectiveHeatFlux(\n",
    "            boundary=faces.faces,\n",
    "            physics=model,\n",
    "            heat_transfer_coefficient=film,\n",
    "            ambient_temperature=liquid,\n",
    "        ),\n",
    "        HeatFlux(boundary=faces.edges, physics=model, value=0.0),\n",
    "    ),\n",
    ")\n",
    "temperature = (\n",
    "    Simulation(\n",
    "        problem=problem,\n",
    "        mesh=mesh,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "            linear_solver=SparseDirect(),\n",
    "        ),\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(model.temperature)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The temperature on the mid-plane along the centre line, the difference between the two faces, and\n",
    "the heat given off, against the fin solution."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "k = aluminium.thermal_conductivity\n",
    "m = np.sqrt(2 * film / (k * thickness))\n",
    "fin = lambda x: liquid + (base - liquid) * np.cosh(m * (length - x)) / np.cosh(\n",
    "    m * length\n",
    ")\n",
    "x = np.linspace(0, length, 201)\n",
    "along = lambda z: np.column_stack((x, np.full_like(x, width / 2), np.full_like(x, z)))\n",
    "middle, top = (\n",
    "    temperature.evaluate(along(thickness / 2)).ravel(),\n",
    "    temperature.evaluate(along(thickness)).ravel(),\n",
    ")\n",
    "heat = temperature.boundary_flux(faces.faces)\n",
    "exact_heat = (\n",
    "    np.sqrt(2 * film * k * thickness) * width * (base - liquid) * np.tanh(m * length)\n",
    ")\n",
    "print(\n",
    "    f\"fin parameter m L = {m * length:.3f}, Biot number h d / k = {film * thickness / k:.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"largest deviation of the mid-plane temperature from the fin solution: {np.abs(middle - fin(x)).max():.4f} K\"\n",
    ")\n",
    "print(\n",
    "    f\"largest difference between mid-plane and face: {np.abs(middle - top).max():.4f} K\"\n",
    ")\n",
    "print(\n",
    "    f\"tip temperature: simulation {middle[-1] - 273.15:.3f} °C, fin solution {fin(length) - 273.15:.3f} °C\"\n",
    ")\n",
    "print(\n",
    "    f\"heat given off: simulation {heat:.3f} W, fin solution {exact_heat:.3f} W ({100 * (heat / exact_heat - 1):+.3f} %), \"\n",
    "    f\"heat entering at the base {-temperature.boundary_flux(faces.base):.3f} W\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The surface temperature of the plate, and the temperature along the plate against the fin\n",
    "solution."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.surface(\n",
    "    temperature,\n",
    "    component=lambda T, position: T - 273.15,\n",
    "    limits=(20, 100),\n",
    "    contours=9,\n",
    "    subdivisions=2,\n",
    "    camera=view,\n",
    "    label=\"T [°C]\",\n",
    "    title=\"Surface temperature\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation, mid-plane\": (1e3 * x[::5], middle[::5] - 273.15)},\n",
    "    reference={\"fin solution\": (1e3 * x, fin(x) - 273.15)},\n",
    "    hlines={\"liquid, 20 °C\": 20.0},\n",
    "    xlabel=\"distance from the held edge x [mm]\",\n",
    "    ylabel=\"T [°C]\",\n",
    "    title=\"Temperature along the plate\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the plate thicker in `thin_plate_fin_cooling_geometry.py` and write the STEP file again, or\n",
    "raise the film coefficient to boiling values: once $hd/k$ approaches 0.1 the temperature varies\n",
    "through the thickness and the fin reduction loses accuracy, while the 3D model stays valid."
   ]
  }
 ]
}
