{
 "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: half of a square column (EN ISO 10211, case 1)\n",
    "\n",
    "EN ISO 10211 (*Thermal bridges in building construction - Heat flows and surface temperatures -\n",
    "Detailed calculations*) classes a program as a two-dimensional high-precision method only if it\n",
    "reproduces its test reference cases. Case 1 is the one with an exact solution: a square column,\n",
    "2 m × 2 m, whose top face is held at 20 °C and whose three other faces are held at 0 °C. Because\n",
    "of the symmetry only one half, 1 m wide and 2 m high, is computed:\n",
    "\n",
    "$$\\nabla\\cdot(\\lambda\\nabla\\theta)=0,\\qquad \\lambda=1\\ \\mathrm{W/(m\\,K)}.$$\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `warm`, top $y=2$ m | $\\theta=20$ °C |\n",
    "| `cold`: external face $x=0$ and bottom $y=0$ | $\\theta=0$ °C |\n",
    "| `symmetry`, $x=1$ m (middle of the column) | adiabatic |\n",
    "\n",
    "The two top corners, where 20 °C meets 0 °C, are singular; the field must still be accurate\n",
    "everywhere else.\n",
    "\n",
    "The half column comes from the CAD file `thermal_bridge_square_column_iso10211.step`; the script\n",
    "`thermal_bridge_square_column_iso10211_geometry.py` builds it with the CAD objects of OneSimulation.\n",
    "The two-dimensional model is its mid-plane section.\n",
    "\n",
    "**Reference.** The standard tabulates the temperature at 28 points of an equidistant grid\n",
    "($x=0.25,\\dots,1$ m, $y=0.25,\\dots,1.75$ m) and accepts deviations of at most 0.1 K. The table\n",
    "values come from the separation-of-variables solution of the full square,\n",
    "\n",
    "$$\\theta(x,y)=\\sum_{n=1,3,5,\\dots}\\frac{80}{n\\pi}\\,\\sin\\frac{n\\pi x}{2}\\,\n",
    "  \\frac{\\sinh(n\\pi y/2)}{\\sinh(n\\pi)}\\ \\ ^\\circ\\mathrm C,$$\n",
    "\n",
    "which the notebook evaluates as a second, more precise reference (Carslaw and Jaeger,\n",
    "*Conduction of Heat in Solids*, 1959)."
   ]
  },
  {
   "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 TriangularMesher\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 FixedTemperature, HeatConduction, HeatFlux\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 half column with its named faces; `section` returns the mid-plane region,\n",
    "whose sides keep the names of the faces they were cut from. Three triangular meshes halve the cell\n",
    "size from one to the next and are refined along the warm face, where the singular corners are."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "column = load(\"thermal_bridge_square_column_iso10211.step\")\n",
    "faces = column.boundaries\n",
    "region = column.section((0, 0, 1), origin=(0, 0, column.size[2] / 2))\n",
    "sides = region.boundaries\n",
    "sizes = [0.2, 0.1, 0.05]\n",
    "meshes = [\n",
    "    TriangularMesher(\n",
    "        target_size=size, grading=0.25, local_sizes={\"y_max\": size / 4}\n",
    "    ).generate(region)\n",
    "    for size in sizes\n",
    "]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(13, 6.5))\n",
    "plots.geometry(\n",
    "    column,\n",
    "    selection={\n",
    "        \"warm, 20 °C\": faces.warm,\n",
    "        \"cold, 0 °C\": faces.cold,\n",
    "        \"symmetry\": faces.symmetry,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=30, azimuth=-115),\n",
    "    title=\"Half column with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Middle mesh: {meshes[1].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Quadratic triangles on all three meshes; the temperature is written in °C directly. The warm and\n",
    "the cold faces share the corner $(0,\\,2)$; one prescribed temperature on all three faces gives\n",
    "that node 0 °C, the value of the external face."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = IsotropicSolid(\n",
    "    density=2000.0,\n",
    "    specific_heat_capacity=1000.0,\n",
    "    thermal_conductivity=1.0,\n",
    "    youngs_modulus=1e10,\n",
    "    poisson_ratio=0.2,\n",
    "    thermal_expansion_coefficient=0.0,\n",
    ")\n",
    "model = HeatConduction(domain=region.domain(), material=material, heating=0.0)\n",
    "problem = Problem(\n",
    "    name=\"ISO 10211 case 1\",\n",
    "    geometry=region,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedTemperature(\n",
    "            boundary=sides.y_max | sides.x_min | sides.y_min,\n",
    "            physics=model,\n",
    "            value=lambda x, y: np.where(np.isclose(y, 2.0) & (x > 1e-9), 20.0, 0.0),\n",
    "        ),\n",
    "        HeatFlux(boundary=sides.x_max, physics=model, value=0.0),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "fields = [\n",
    "    Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "    .solve_stationary()\n",
    "    .field(model.temperature)\n",
    "    for mesh in meshes\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The 28 temperatures of the finest mesh against the table of the standard (rows from the top) and\n",
    "the largest deviation on each mesh."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "iso = np.array(\n",
    "    [\n",
    "        [9.7, 13.4, 14.7, 15.1],\n",
    "        [5.3, 8.6, 10.3, 10.8],\n",
    "        [3.2, 5.6, 7.0, 7.5],\n",
    "        [2.0, 3.6, 4.7, 5.0],\n",
    "        [1.3, 2.3, 3.0, 3.2],\n",
    "        [0.7, 1.4, 1.8, 1.9],\n",
    "        [0.3, 0.6, 0.8, 0.9],\n",
    "    ]\n",
    ")\n",
    "X, Y = np.meshgrid([0.25, 0.5, 0.75, 1.0], [1.75, 1.5, 1.25, 1.0, 0.75, 0.5, 0.25])\n",
    "n = np.arange(1, 400, 2)[:, None]\n",
    "series = lambda x, y: np.sum(\n",
    "    80\n",
    "    / (n * np.pi)\n",
    "    * np.sin(n * np.pi * x / 2)\n",
    "    * np.exp(n * np.pi * (y - 2) / 2)\n",
    "    * (1 - np.exp(-n * np.pi * y))\n",
    "    / (1 - np.exp(-2 * n * np.pi)),\n",
    "    axis=0,\n",
    ")\n",
    "grid = [\n",
    "    f.evaluate(np.column_stack((X.ravel(), Y.ravel()))).reshape(X.shape) for f in fields\n",
    "]\n",
    "print(\"y [m]   simulation at x = 0.25 / 0.5 / 0.75 / 1.0 m       ISO 10211 table\")\n",
    "for row in range(7):\n",
    "    print(\n",
    "        f\"{Y[row, 0]:5.2f}  \"\n",
    "        + \" \".join(f\"{v:7.3f}\" for v in grid[-1][row])\n",
    "        + \"      \"\n",
    "        + \" \".join(f\"{v:5.1f}\" for v in iso[row])\n",
    "    )\n",
    "for size, mesh, values in zip(sizes, meshes, grid):\n",
    "    print(\n",
    "        f\"mesh {size:.2f} m ({mesh.cell_count:5d} triangles): largest deviation from the table {np.abs(values - iso).max():.3f} K \"\n",
    "        f\"(0.1 K allowed), from the exact series {np.abs(values - series(X.ravel(), Y.ravel()).reshape(X.shape)).max():.1e} K\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The temperature field with isotherms, and the temperature along the four grid columns with the\n",
    "table of the standard (markers) and the exact series (dashed)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "y = np.linspace(0.02, 1.98, 197)\n",
    "fig = plots.figure(1, 2, size=(15, 7))\n",
    "plots.surface(\n",
    "    fields[-1],\n",
    "    limits=(0, 20),\n",
    "    contours=21,\n",
    "    subdivisions=3,\n",
    "    xlabel=\"x [m]\",\n",
    "    ylabel=\"y [m]\",\n",
    "    label=\"θ [°C]\",\n",
    "    title=\"Temperature in the half column\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"x = {x} m\": (\n",
    "            y,\n",
    "            fields[-1].evaluate(np.column_stack((np.full_like(y, x), y))).ravel(),\n",
    "        )\n",
    "        for x in X[0]\n",
    "    },\n",
    "    reference={f\"x = {x} m\": (y, series(np.full_like(y, x), y)) for x in X[0]},\n",
    "    points={\n",
    "        f\"ISO 10211, x = {x} m\": (Y[:, column_index], iso[:, column_index])\n",
    "        for column_index, x in enumerate(X[0])\n",
    "    },\n",
    "    xlabel=\"height y [m]\",\n",
    "    ylabel=\"θ [°C]\",\n",
    "    title=\"Columns: simulation, series (dashed), ISO (markers)\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "EN ISO 10211 case 2 adds four materials and surface resistances; see the composite-structure\n",
    "example. Here, replace the fixed temperatures by surface resistances (`ConvectiveHeatFlux`), or\n",
    "make the column rectangular in `thermal_bridge_square_column_iso10211_geometry.py` and change\n",
    "the series accordingly."
   ]
  }
 ]
}
