{
 "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": [
    "# Composite thermal barrier: resolved layers and a lumped resistance\n",
    "\n",
    "Thin insulating layers are stacked to protect a part from a heat source or to set the thermal\n",
    "resistance between them. A copper heater (30 mm × 30 mm, 10 mm thick) releasing 1 W rests on a\n",
    "barrier of four layers of its footprint, each 1 mm thick, which lies on an aluminium plate\n",
    "(60 mm × 60 mm, 5 mm thick) cooled from below. Meshing such layers costs elements through their\n",
    "thickness; a common shortcut replaces them by a **lumped thermal resistance** between the faces\n",
    "they connect, the series resistance per area\n",
    "\n",
    "$$R''=\\sum_i\\frac{d_i}{k_i}.$$\n",
    "\n",
    "| part | thickness [mm] | $k$ [W/(m K)] | $\\rho c$ [MJ/(m³ K)] |\n",
    "|---|---|---|---|\n",
    "| copper heater | 10 | 400 | 3.43 |\n",
    "| graphite foil | 1 | 5 | 0.71 |\n",
    "| glass-fibre mat | 1 | 0.04 | 0.084 |\n",
    "| ceramic paper | 1 | 0.10 | 0.25 |\n",
    "| mica sheet | 1 | 0.5 | 2.46 |\n",
    "| aluminium plate | 5 | 200 | 2.43 |\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| bottom of the plate | forced air, $h=200$ W/(m² K), 25 °C |\n",
    "| all other faces | insulated |\n",
    "\n",
    "The resolved stack comes from `composite_thermal_barrier_lumped.step` with one region file per\n",
    "layer and for the heater; for the lumped model, `composite_thermal_barrier_lumped_plate.step` and\n",
    "`composite_thermal_barrier_lumped_heater_on_plate.step` hold the plate and the heater placed\n",
    "directly on it. The script `composite_thermal_barrier_lumped_geometry.py` writes all of them with\n",
    "the CAD objects of OneSimulation. In the lumped model the faces between heater and plate carry a\n",
    "`ThermalContact` of conductance $1/R''$: the temperature jumps across them by $q''R''$.\n",
    "\n",
    "**Reference.** The barrier is much less conductive than copper and aluminium, so the heat crosses\n",
    "it almost uniformly over the footprint $A$, and the temperature step across the barrier is close to\n",
    "$P\\,R''/A$ (Incropera and DeWitt, *Fundamentals of Heat and Mass Transfer*, ch. 3.1). In the steady\n",
    "state all of the 1 W leaves through the cooled face. The resolved model is the reference for the\n",
    "lumped one."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.d3 import Assembly\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import TetrahedralMesher, interface\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",
    "    HeatConduction,\n",
    "    HeatFlux,\n",
    "    ThermalContact,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation, regionwise\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",
    "The resolved stack is one solid with the layers and the heater embedded as regions; its mesh\n",
    "follows every interface. The lumped model is an assembly of plate and heater; its mesh keeps the\n",
    "two parts apart on their common face, where the contact acts."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "stack = load(\"composite_thermal_barrier_lumped.step\")\n",
    "layers = {\n",
    "    \"mica sheet\": (\"mica\", 0.5, 2.46e6),\n",
    "    \"ceramic paper\": (\"ceramic_paper\", 0.10, 0.25e6),\n",
    "    \"glass-fibre mat\": (\"glass_fibre\", 0.04, 0.084e6),\n",
    "    \"graphite foil\": (\"graphite_foil\", 5.0, 0.71e6),\n",
    "}\n",
    "regions = {\n",
    "    name: load(f\"composite_thermal_barrier_lumped_{file}.step\")\n",
    "    for name, (file, _, _) in layers.items()\n",
    "}\n",
    "heater = load(\"composite_thermal_barrier_lumped_heater.step\")\n",
    "lumped = Assembly(\n",
    "    parts=(\n",
    "        load(\"composite_thermal_barrier_lumped_plate.step\").named(\"plate\"),\n",
    "        load(\"composite_thermal_barrier_lumped_heater_on_plate.step\").named(\"heater\"),\n",
    "    )\n",
    ")\n",
    "meshes = {\n",
    "    \"resolved\": TetrahedralMesher(\n",
    "        target_size=0.004, embedded_regions=(*regions.values(), heater)\n",
    "    ).generate(stack),\n",
    "    \"lumped\": TetrahedralMesher(target_size=0.004).generate(lumped),\n",
    "}\n",
    "\n",
    "view = plots.Camera(elevation=25, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(15, 6))\n",
    "plots.geometry(\n",
    "    [part.named(name) for name, part in ((\"heater\", heater), *regions.items())]\n",
    "    + [load(\"composite_thermal_barrier_lumped_plate.step\").named(\"plate\")],\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Heater, four layers and plate (STEP)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[\"resolved\"],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Resolved layers: {meshes['resolved'].cell_count} quadratic tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Models\n",
    "\n",
    "Conductivity, heat capacity and heating are given region by region; with the density set to one,\n",
    "the specific heat capacity is the volumetric one (it matters only for transients). Both models are\n",
    "solved for the steady state."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "power, film, ambient = 1.0, 200.0, 298.15\n",
    "area, heater_volume = (\n",
    "    heater.size[0] * heater.size[1],\n",
    "    heater.size[0] * heater.size[1] * heater.size[2],\n",
    ")\n",
    "resistance = sum(\n",
    "    r.size[2] / k for r, (_, k, _) in zip(regions.values(), layers.values())\n",
    ")\n",
    "solid = lambda k, c: IsotropicSolid(\n",
    "    density=1.0,\n",
    "    specific_heat_capacity=c,\n",
    "    thermal_conductivity=k,\n",
    "    youngs_modulus=7e10,\n",
    "    poisson_ratio=0.33,\n",
    "    thermal_expansion_coefficient=0.0,\n",
    ")\n",
    "resolved = HeatConduction(\n",
    "    domain=stack.volume,\n",
    "    material=solid(\n",
    "        regionwise(\n",
    "            ((heater, 400.0), *((regions[n], k) for n, (_, k, _) in layers.items())),\n",
    "            default=200.0,\n",
    "            unit=\"W/m/K\",\n",
    "        ),\n",
    "        regionwise(\n",
    "            ((heater, 3.43e6), *((regions[n], c) for n, (_, _, c) in layers.items())),\n",
    "            default=2.43e6,\n",
    "            unit=\"J/kg/K\",\n",
    "        ),\n",
    "    ),\n",
    "    heating=regionwise(((heater, power / heater_volume),), default=0.0, unit=\"W/m^3\"),\n",
    ")\n",
    "contact = HeatConduction(\n",
    "    domain=lumped.domain(),\n",
    "    material=solid(\n",
    "        regionwise({\"heater\": 400.0, \"plate\": 200.0}, unit=\"W/m/K\"),\n",
    "        regionwise({\"heater\": 3.43e6, \"plate\": 2.43e6}, unit=\"J/kg/K\"),\n",
    "    ),\n",
    "    heating=regionwise({\"heater\": power / heater_volume, \"plate\": 0.0}, unit=\"W/m^3\"),\n",
    ")\n",
    "problems = {\n",
    "    \"resolved\": Problem(\n",
    "        name=\"Resolved barrier\",\n",
    "        geometry=stack,\n",
    "        physics=(resolved,),\n",
    "        boundary_conditions=(\n",
    "            ConvectiveHeatFlux(\n",
    "                boundary=stack.boundaries.bottom,\n",
    "                physics=resolved,\n",
    "                heat_transfer_coefficient=film,\n",
    "                ambient_temperature=ambient,\n",
    "            ),\n",
    "            HeatFlux(\n",
    "                boundary=stack.boundaries.all - stack.boundaries.bottom,\n",
    "                physics=resolved,\n",
    "                value=0.0,\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "    \"lumped\": Problem(\n",
    "        name=\"Lumped barrier\",\n",
    "        geometry=lumped,\n",
    "        physics=(contact,),\n",
    "        boundary_conditions=(\n",
    "            ConvectiveHeatFlux(\n",
    "                boundary=lumped.boundaries[\"plate.bottom\"],\n",
    "                physics=contact,\n",
    "                heat_transfer_coefficient=film,\n",
    "                ambient_temperature=ambient,\n",
    "            ),\n",
    "            HeatFlux(\n",
    "                boundary=lumped.boundaries.all - lumped.boundaries[\"plate.bottom\"],\n",
    "                physics=contact,\n",
    "                value=0.0,\n",
    "            ),\n",
    "            ThermalContact(\n",
    "                boundary=interface(meshes[\"lumped\"], \"heater_plate\"),\n",
    "                physics=contact,\n",
    "                conductance=1 / resistance,\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "}\n",
    "models = {\"resolved\": resolved, \"lumped\": contact}\n",
    "spatial = dict(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "steady = {\n",
    "    name: Simulation(\n",
    "        problem=problem, mesh=meshes[name], numerics=Numerics(**spatial)\n",
    "    ).solve_stationary()\n",
    "    for name, problem in problems.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Temperatures at the centre of the heater's top and of the plate's top beside the heater, the step\n",
    "across the barrier, and the heat into the air."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plate_top, heater_top = 0.005, stack.size[2]\n",
    "middle = stack.size[0] / 2\n",
    "probes = {\n",
    "    \"resolved\": [\n",
    "        [middle, middle, heater_top],\n",
    "        [middle, middle, plate_top + 4e-3],\n",
    "        [middle, middle, plate_top],\n",
    "    ],\n",
    "    \"lumped\": [\n",
    "        [middle, middle, plate_top + heater.size[2]],\n",
    "        [middle, middle, plate_top + 1e-9],\n",
    "        [middle, middle, plate_top - 1e-9],\n",
    "    ],\n",
    "}\n",
    "values = {\n",
    "    name: np.ravel(steady[name].field(models[name].temperature).evaluate(points))\n",
    "    for name, points in probes.items()\n",
    "}\n",
    "print(\n",
    "    f\"series resistance of the layers R'' = {1e4 * resistance:.3f} cm² K/W; 1D estimate of the step across the barrier P R''/A = {power * resistance / area:.3f} K\"\n",
    ")\n",
    "print(\n",
    "    \"steady state           heater top [°C]   barrier top [°C]   plate below the barrier [°C]   step across the barrier [K]   heat into the air [W]\"\n",
    ")\n",
    "for name in values:\n",
    "    print(\n",
    "        f\"{name:12s} {values[name][0] - 273.15:24.3f} {values[name][1] - 273.15:18.3f} {values[name][2] - 273.15:30.3f} {values[name][1] - values[name][2]:29.3f}\"\n",
    "        f\" {abs(steady[name].field(models[name].temperature).boundary_flux(problems[name].boundary_conditions[0].boundary)):23.5f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"lumped against resolved: heater top {values['lumped'][0] - values['resolved'][0]:+.1e} K \"\n",
    "    f\"({100 * (values['lumped'][0] - values['resolved'][0]) / (values['resolved'][0] - ambient):+.1e} % of the rise)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left: the steady temperature on a vertical line through the middle of the stack, resolved and\n",
    "lumped (the heater of the lumped model is drawn above the barrier it replaces). Right: the steady temperature of the resolved stack on its vertical mid-plane."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "z = np.linspace(0.0, heater_top, 400)\n",
    "z_lumped = np.linspace(0.0, plate_top + heater.size[2], 300)\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.line(\n",
    "    y={\n",
    "        \"resolved layers\": (\n",
    "            steady[\"resolved\"]\n",
    "            .field(resolved.temperature)\n",
    "            .evaluate(\n",
    "                np.column_stack((np.full_like(z, middle), np.full_like(z, middle), z))\n",
    "            )\n",
    "            .ravel()\n",
    "            - 273.15,\n",
    "            1e3 * z,\n",
    "        ),\n",
    "        \"lumped resistance\": (\n",
    "            steady[\"lumped\"]\n",
    "            .field(contact.temperature)\n",
    "            .evaluate(\n",
    "                np.column_stack(\n",
    "                    (\n",
    "                        np.full_like(z_lumped, middle),\n",
    "                        np.full_like(z_lumped, middle),\n",
    "                        z_lumped,\n",
    "                    )\n",
    "                )\n",
    "            )\n",
    "            .ravel()\n",
    "            - 273.15,\n",
    "            1e3 * np.where(z_lumped > plate_top, z_lumped + 4e-3, z_lumped),\n",
    "        ),\n",
    "    },\n",
    "    hlines={\"barrier\": 5.0, \"\": 9.0},\n",
    "    xlabel=\"T [°C]\",\n",
    "    ylabel=\"height in the stack [mm]\",\n",
    "    title=\"Steady temperature through the middle\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.section(\n",
    "    steady[\"resolved\"].field(resolved.temperature),\n",
    "    plane=Plane(origin=(0, middle, 0), normal=(0, 1, 0)),\n",
    "    component=lambda T, p: np.ravel(T) - 273.15,\n",
    "    limits=(25, 70),\n",
    "    contours=10,\n",
    "    subdivisions=2,\n",
    "    label=\"T [°C]\",\n",
    "    title=\"Resolved layers: temperature on the mid-plane\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Give the barrier a larger footprint than the heater in `composite_thermal_barrier_lumped_geometry.py`:\n",
    "heat then spreads sideways in the graphite foil, which the lumped resistance cannot do, and the two\n",
    "models drift apart. Swapping two layers changes neither model in the steady state."
   ]
  }
 ]
}
