{
 "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": [
    "# Thermal bridge in a composite wall (EN ISO 10211, case 2)\n",
    "\n",
    "Case 2 of EN ISO 10211 (*Thermal bridges in building construction - Heat flows and surface\n",
    "temperatures - Detailed calculations*) is a two-dimensional wall detail with four materials and\n",
    "conductivities that differ by four orders of magnitude. A thin L-shaped aluminium profile runs\n",
    "along the warm face and up the left cut, a wooden batten sits on top of it, the rest of the wall\n",
    "is insulation, and a concrete layer closes the cold side:\n",
    "\n",
    "| material | region (x, y in mm) | $\\lambda$ / (W/(m K)) |\n",
    "|---|---|---|\n",
    "| aluminium | $y<1.5$; $x<1.5,\\ y<36.5$; $x<15,\\ 35<y<36.5$ | 230 |\n",
    "| wood | $x<15,\\ 36.5<y<41.5$ | 0.12 |\n",
    "| concrete | $41.5<y<47.5$ | 1.15 |\n",
    "| insulation | everything else | 0.029 |\n",
    "\n",
    "The temperature solves $\\nabla\\cdot(\\lambda\\nabla\\theta)=0$ with surface resistances\n",
    "(Robin condition $-\\lambda\\,\\partial_n\\theta=(\\theta-\\theta_a)/R_s$):\n",
    "\n",
    "| side of the cross-section | condition |\n",
    "|---|---|\n",
    "| `y_min`, $y=0$ (warm side, face `inside`) | $\\theta_a=20$ °C, $R_{si}=0.11$ m² K/W |\n",
    "| `y_max`, $y=47.5$ mm (cold side, face `outside`) | $\\theta_a=0$ °C, $R_{se}=0.06$ m² K/W |\n",
    "| `x_min`, `x_max` (cut faces $x=0$ and $x=500$ mm) | adiabatic |\n",
    "\n",
    "The wall comes from the CAD file `thermal_bridge_composite_iso10211.step`; the files\n",
    "`thermal_bridge_composite_iso10211_aluminium.step`, `..._wood.step` and `..._concrete.step` hold\n",
    "the regions of the materials. The script `thermal_bridge_composite_iso10211_geometry.py` builds\n",
    "all of them with the CAD objects of OneSimulation. Nothing varies through the depth, so the\n",
    "model is the two-dimensional cross-section of the wall and of the three regions.\n",
    "\n",
    "**Reference.** EN ISO 10211, case 2: the temperatures at the nine points A to I and the heat flow\n",
    "9.5 W per metre of wall. A program passes with temperatures within 0.1 K and the heat flow\n",
    "within 0.1 W/m."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from dataclasses import replace\n",
    "\n",
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import Geometric, explicit_mesh, merge_blocks, rectangle_block\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 ConvectiveHeatFlux, HeatConduction, HeatFlux\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",
    "`load` returns the wall with its named faces and the three material regions; `section` cuts all\n",
    "of them at half depth; the sides of the cross-section are named `x_min` ... `y_max`. The\n",
    "mesh is built from graded rectangular blocks, one per strip between two material interfaces,\n",
    "and split into triangles, so it has a node line on every interface; the cells are 0.5 mm wide\n",
    "at the thin aluminium parts and grow away from them."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "part = load(\"thermal_bridge_composite_iso10211.step\")\n",
    "depth = part.size[2]\n",
    "cut = lambda solid: solid.section((0, 0, 1), origin=(0, 0, depth / 2))\n",
    "wall = cut(part)\n",
    "aluminium, wood, concrete = (\n",
    "    cut(load(f\"thermal_bridge_composite_iso10211_{name}.step\"))\n",
    "    for name in (\"aluminium\", \"wood\", \"concrete\")\n",
    ")\n",
    "faces = wall.boundaries\n",
    "width, thickness = wall.size[:2]\n",
    "mm, fine = 1e-3, 0.5e-3\n",
    "columns = (\n",
    "    (0.0, 1.5 * mm, 3, None),\n",
    "    (1.5 * mm, 13.5 * mm, 8, Geometric(8, first=fine)),\n",
    "    (15 * mm, 485 * mm, 24, Geometric(24, first=fine)),\n",
    ")\n",
    "rows = (\n",
    "    (0.0, 1.5 * mm, 3, None),\n",
    "    (1.5 * mm, 33.5 * mm, 14, Geometric(14, first=fine, toward=\"end\")),\n",
    "    (35 * mm, 1.5 * mm, 3, None),\n",
    "    (36.5 * mm, 5 * mm, 6, None),\n",
    "    (41.5 * mm, 6 * mm, 6, None),\n",
    ")\n",
    "blocks = merge_blocks(\n",
    "    [\n",
    "        rectangle_block((x0, y0), lx, ly, (nx, ny), (gx, gy))\n",
    "        for x0, lx, nx, gx in columns\n",
    "        for y0, ly, ny, gy in rows\n",
    "    ]\n",
    ").triangulated()\n",
    "mesh = explicit_mesh(wall, blocks.coordinates, blocks.cells)\n",
    "\n",
    "fig = plots.figure(2, 1, size=(16, 7))\n",
    "plots.geometry(\n",
    "    part,\n",
    "    selection={\n",
    "        \"inside, 20 °C\": part.boundaries.inside,\n",
    "        \"outside, 0 °C\": part.boundaries.outside,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=55, azimuth=-80),\n",
    "    title=\"Wall detail with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Cross-section: {mesh.cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The conductivity is given region by region (first match wins), insulation is the default. The\n",
    "same problem is solved with linear and with quadratic elements."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "conductivity = regionwise(\n",
    "    ((aluminium, 230.0), (wood, 0.12), (concrete, 1.15)), default=0.029, unit=\"W/m/K\"\n",
    ")\n",
    "material = replace(\n",
    "    IsotropicSolid(\n",
    "        density=150.0,\n",
    "        specific_heat_capacity=1000.0,\n",
    "        thermal_conductivity=0.029,\n",
    "        youngs_modulus=1e9,\n",
    "        poisson_ratio=0.3,\n",
    "        thermal_expansion_coefficient=0.0,\n",
    "    ),\n",
    "    thermal_conductivity=conductivity,\n",
    ")\n",
    "model = HeatConduction(domain=wall.domain(), material=material, heating=0.0)\n",
    "problem = Problem(\n",
    "    name=\"ISO 10211 case 2\",\n",
    "    geometry=wall,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        ConvectiveHeatFlux(\n",
    "            boundary=faces.y_min,\n",
    "            physics=model,\n",
    "            heat_transfer_coefficient=1 / 0.11,\n",
    "            ambient_temperature=20.0,\n",
    "        ),\n",
    "        ConvectiveHeatFlux(\n",
    "            boundary=faces.y_max,\n",
    "            physics=model,\n",
    "            heat_transfer_coefficient=1 / 0.06,\n",
    "            ambient_temperature=0.0,\n",
    "        ),\n",
    "        HeatFlux(boundary=faces.x_min | faces.x_max, physics=model, value=0.0),\n",
    "    ),\n",
    ")\n",
    "fields = {\n",
    "    order: Simulation(\n",
    "        problem=problem,\n",
    "        mesh=mesh,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(element=Lagrange(order=order)),\n",
    "            linear_solver=SparseDirect(),\n",
    "        ),\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(model.temperature)\n",
    "    for order in (1, 2)\n",
    "}\n",
    "field = fields[2]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Temperatures at the nine points of the standard and the heat flow per metre of wall (the\n",
    "boundary flux of the cross-section is already per metre of depth)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "points = {\n",
    "    \"A\": (0, 47.5),\n",
    "    \"B\": (0, 41.5),\n",
    "    \"C\": (0, 36.5),\n",
    "    \"D\": (0, 0),\n",
    "    \"E\": (500, 47.5),\n",
    "    \"F\": (500, 41.5),\n",
    "    \"G\": (500, 0),\n",
    "    \"H\": (15, 41.5),\n",
    "    \"I\": (15, 36.5),\n",
    "}\n",
    "iso = {\n",
    "    \"A\": 7.1,\n",
    "    \"B\": 7.9,\n",
    "    \"C\": 16.4,\n",
    "    \"D\": 16.8,\n",
    "    \"E\": 0.8,\n",
    "    \"F\": 0.8,\n",
    "    \"G\": 18.3,\n",
    "    \"H\": 6.3,\n",
    "    \"I\": 16.3,\n",
    "}\n",
    "at = np.array([(mm * x, mm * y) for x, y in points.values()])\n",
    "values = {order: f.evaluate(at).ravel() for order, f in fields.items()}\n",
    "flow = {order: f.boundary_flux(faces.y_max) for order, f in fields.items()}\n",
    "print(\n",
    "    \"point   (x, y) [mm]     ISO 10211 [°C]   linear [°C]   quadratic [°C]   deviation (quadratic)\"\n",
    ")\n",
    "for index, (name, (x, y)) in enumerate(points.items()):\n",
    "    print(\n",
    "        f\"{name:5s}   ({x:5.1f}, {y:4.1f})   {iso[name]:12.1f} {values[1][index]:13.3f} {values[2][index]:16.3f} \"\n",
    "        f\"{values[2][index] - iso[name]:+14.3f} K\"\n",
    "    )\n",
    "print(\n",
    "    f\"largest temperature deviation (quadratic): {max(abs(values[2] - np.array(list(iso.values())))):.3f} K (0.1 K allowed)\"\n",
    ")\n",
    "print(\n",
    "    f\"heat flow: ISO 10211 9.5 W/m, linear {flow[1]:.3f} W/m, quadratic {flow[2]:.3f} W/m; \"\n",
    "    f\"warm side {-field.boundary_flux(faces.y_min):.3f} W/m\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The temperature in the section with the aluminium profile on the left, an enlarged view of the\n",
    "corner with the batten, and the temperature along the warm and the cold face."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(0, width, 501)\n",
    "fig = plots.figure(layout=[[\"wall\", \"wall\"], [\"corner\", \"faces\"]], size=(16, 10))\n",
    "plots.surface(\n",
    "    field,\n",
    "    limits=(0, 20),\n",
    "    contours=21,\n",
    "    subdivisions=3,\n",
    "    aspect=3.0,\n",
    "    label=\"θ [°C]\",\n",
    "    title=\"Temperature in the wall (thickness drawn three times enlarged)\",\n",
    "    ax=fig[\"wall\"],\n",
    ")\n",
    "plots.surface(\n",
    "    field,\n",
    "    limits=(0, 20),\n",
    "    contours=21,\n",
    "    subdivisions=3,\n",
    "    xlimits=(0, 0.05),\n",
    "    ylimits=(0, thickness),\n",
    "    label=\"θ [°C]\",\n",
    "    title=\"Corner with the aluminium profile and the batten\",\n",
    "    ax=fig[\"corner\"],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        \"warm face y = 0\": (\n",
    "            1e3 * x,\n",
    "            field.evaluate(np.column_stack((x, np.zeros_like(x)))).ravel(),\n",
    "        ),\n",
    "        \"cold face y = 47.5 mm\": (\n",
    "            1e3 * x,\n",
    "            field.evaluate(np.column_stack((x, np.full_like(x, thickness)))).ravel(),\n",
    "        ),\n",
    "    },\n",
    "    points={\"ISO 10211 (D, G, A, E)\": ([0, 500, 0, 500], [16.8, 18.3, 7.1, 0.8])},\n",
    "    xlimits=(-5, 505),\n",
    "    xlabel=\"distance from the left cut x [mm]\",\n",
    "    ylabel=\"θ [°C]\",\n",
    "    title=\"Surface temperatures\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[\"faces\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Replace the aluminium profile by a steel one (50 W/(m K)) or thicken the insulation in\n",
    "`thermal_bridge_composite_iso10211_geometry.py` and write the STEP files again; the linear\n",
    "thermal transmittance of the detail is the heat flow minus that of the undisturbed wall."
   ]
  }
 ]
}
