{
 "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 stress in a fuel-cell bipolar plate\n",
    "\n",
    "A PEM fuel cell runs just below 100 °C, so a cold stack has to be heated before it can start.\n",
    "In the stack considered here every bipolar plate carries a heating element in the middle of\n",
    "its gas-feed channel; together the elements of the 25 plates deliver 200 W. The plates are\n",
    "titanium, the heating elements aluminium. Heating makes the plate non-uniformly hot, and the\n",
    "thermal expansion that cannot develop freely produces stress. The question is how large the\n",
    "stress is, where it peaks, and how far the plate bulges out of plane, which matters for the\n",
    "sealing of the membrane.\n",
    "\n",
    "**Geometry.** The plate is $240\\times180\\times10$ mm with two gas-feed slits, tie-rod holes and\n",
    "a central active area. With its three symmetry planes one eighth is modelled,\n",
    "$0\\le x\\le120$ mm, $0\\le y\\le90$ mm, $0\\le z\\le5$ mm (half the thickness), with the symmetry\n",
    "planes $x=120$ mm, $y=90$ mm and the mid-plane $z=0$:\n",
    "\n",
    "| feature | position (mm) |\n",
    "|---|---|\n",
    "| active part (titanium, clamped with 1 MPa) | $30\\le x\\le120$, $35\\le y\\le90$ |\n",
    "| manifold (titanium, clamped with 8 MPa) | the rest of the plate |\n",
    "| gas slit 1 | $10\\le x\\le20$, $35\\le y\\le70$, corner fillets $R=2.5$ |\n",
    "| gas slit 2 | $35\\le x\\le100$, $10\\le y\\le20$, corner fillets $R=2.5$ |\n",
    "| tie-rod hole, $R_0=5$ | centre $(15,15)$; half holes at $(15,90)$ and $(120,15)$ |\n",
    "| heating element (aluminium), half disc $R_0=5$ | centre $(70,90)$ on the symmetry plane |\n",
    "\n",
    "All fields depend on all three coordinates; the plate is thin, so the dependence on $z$ is\n",
    "weak but present (the faces of the slits are cooled, the top face is not).\n",
    "\n",
    "**Heat transfer** (steady, $-\\nabla\\cdot(k\\nabla T)=Q$). The heating element dissipates\n",
    "$200\\,\\text{W}/25$ per plate, i.e. $2$ W in the modelled eighth, uniformly over its volume.\n",
    "\n",
    "| face | thermal condition |\n",
    "|---|---|\n",
    "| outer edges $x=0$ and $y=0$ | convection to the surroundings, $h_1=5$ W/(m² K), $T_\\infty=20$ °C |\n",
    "| walls of the two gas slits | convection to the feed gas, $h_2=50$ W/(m² K), $T_\\mathrm{gas}=80$ °C |\n",
    "| tie-rod holes | insulated (rods not modelled) |\n",
    "| top face $z=5$ mm | insulated (contact with the neighbouring cell, which is heated alike) |\n",
    "| symmetry planes $x=120$, $y=90$, $z=0$ | zero flux |\n",
    "\n",
    "**Structure** (linear elasticity of the titanium only; the soft-mounted heating element carries\n",
    "no load). Thermal strain $\\varepsilon_\\mathrm{th}=\\alpha\\,(T-T_\\mathrm{ref})\\,\\mathbf I$ with\n",
    "the stress-free reference temperature $T_\\mathrm{ref}=0$ °C.\n",
    "\n",
    "| face | mechanical condition |\n",
    "|---|---|\n",
    "| symmetry plane $x=120$ mm | $u_x=0$ (roller) |\n",
    "| symmetry plane $y=90$ mm | $u_y=0$ (roller) |\n",
    "| mid-plane $z=0$ | $u_z=0$ (roller) |\n",
    "| top face of the active part | tie-rod clamping pressure $P_1=1$ MPa |\n",
    "| top face of the manifold | tie-rod clamping pressure $P_2=8$ MPa |\n",
    "| outer edges, slit walls, holes, seat of the heating element | traction-free |\n",
    "\n",
    "**Materials** (values of the published problem set-up): titanium $E=105$ GPa, $\\nu=0.33$,\n",
    "$\\alpha=7.06\\times10^{-6}$ 1/K, $k=7.5$ W/(m K); aluminium $k=160$ W/(m K). Densities and heat\n",
    "capacities do not enter the steady problem.\n",
    "\n",
    "**Numerical method.**\n",
    "\n",
    "* Spatial: continuous Galerkin finite elements with **27-node quadratic (Q2) Lagrange\n",
    "  hexahedra** for both the temperature and the displacement, on an unstructured all-hexahedral\n",
    "  mesh: the plate section is triangulated with a size field (DistMesh algorithm, P.-O. Persson\n",
    "  and G. Strang, SIAM Review 46, 329, 2004), every triangle is split into three quadrilaterals\n",
    "  through its centroid and edge midpoints, boundary midpoints are placed on the exact circular\n",
    "  arcs, and the quadrilaterals are swept through the thickness. Gauss quadrature with\n",
    "  $3\\times3\\times3$ points.\n",
    "* Coupling: one-way staggered. The temperature is solved first; the solid takes it at its own\n",
    "  quadrature points through finite-element evaluation (`FieldCoupling`). The displacement does\n",
    "  not feed back into the heat problem, so one pass is the exact coupled solution.\n",
    "* Solvers: both problems are linear and stationary; the heat problem is solved with a sparse\n",
    "  direct LU factorisation, the elastic problem with conjugate gradients preconditioned by\n",
    "  algebraic multigrid (relative residual $10^{-10}$).\n",
    "\n",
    "**Reference.** The published model gives no numbers in its text, only colour plots; their\n",
    "ranges (temperature, von Mises stress, out-of-plane displacement) are compared with\n",
    "a tolerance that reflects reading a colour bar. The quantitative checks are:\n",
    "\n",
    "* the **exact homogeneous solution**: at a uniform temperature $T_0$ and a uniform clamping\n",
    "  pressure $P$ on the whole top face, the plate with these supports expands freely in its plane\n",
    "  and is compressed through its thickness,\n",
    "  $$\\mathbf u=\\alpha(T_0-T_\\mathrm{ref})\\begin{pmatrix}x-120\\,\\text{mm}\\\\y-90\\,\\text{mm}\\\\z\\end{pmatrix}\n",
    "    +\\frac{P}{E}\\begin{pmatrix}\\nu\\,(x-120\\,\\text{mm})\\\\\\nu\\,(y-90\\,\\text{mm})\\\\-z\\end{pmatrix},\\qquad\n",
    "    \\boldsymbol\\sigma=-P\\,\\mathbf e_z\\otimes\\mathbf e_z ,$$\n",
    "  exactly, holes and slits included (their walls carry no load because the in-plane stress\n",
    "  vanishes). It is solved on the real 3D mesh with the real supports; the quadratic hexahedra\n",
    "  contain this linear field, so it must be reproduced to round-off;\n",
    "* the **heat balance**: the 2 W of the heating element must leave through the cooled faces;\n",
    "* the classical **fully restrained bound** $E\\alpha\\,(T_\\max-T_\\min)/(1-\\nu)$ for the thermal\n",
    "  stress (B. A. Boley and J. H. Weiner, *Theory of Thermal Stresses*, Wiley 1960, ch. 9), which\n",
    "  the free plate must stay well below;\n",
    "* a three-level mesh study of the peak temperature, the peak von Mises stress and the peak\n",
    "  out-of-plane displacement, with observed order and Richardson estimate."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import time\n",
    "from dataclasses import dataclass\n",
    "from hashlib import sha256\n",
    "\n",
    "import numpy as np\n",
    "from onesim.cad.geometry.primitives import Geometry\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing.generation.backends.structured.volume.hexahedral import (\n",
    "    StructuredHexahedralMesh,\n",
    ")\n",
    "from onesim.meshing.generation.contracts.hexahedral_geometry import (\n",
    "    FACES,\n",
    "    trilinear_hexahedral_geometry,\n",
    ")\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.field_transfer import FiniteElementEvaluation\n",
    "from onesim.numerics.linear import AlgebraicMultigrid, ConjugateGradient, SparseDirect\n",
    "from onesim.physics.heat_transfer import ConvectiveHeatFlux, HeatConduction, HeatFlux\n",
    "from onesim.physics.solid_mechanics import (\n",
    "    FixedDisplacementComponents,\n",
    "    IsotropicThermalExpansion,\n",
    "    LinearElasticity,\n",
    "    Traction,\n",
    "    TractionFree,\n",
    ")\n",
    "from onesim.results.sampling.points.simplex_locator import SimplexLocator\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.field_connections import FieldCoupling\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.spatial import Delaunay, cKDTree\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parameters"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mm = 1e-3\n",
    "LX, LY, TH2 = 120.0, 90.0, 5.0\n",
    "R0, FILLET = 5.0, 2.5\n",
    "HOLES = ((15.0, 15.0), (15.0, 90.0), (120.0, 15.0))\n",
    "SLITS = ((10.0, 20.0, 35.0, 70.0), (35.0, 100.0, 10.0, 20.0))\n",
    "HEATER = (70.0, 90.0)\n",
    "P_heater = 200.0 / 25 / 4\n",
    "h_surr, T_surr = 5.0, 293.15\n",
    "h_gas, T_gas = 50.0, 353.15\n",
    "k_ti, k_al = 7.5, 160.0\n",
    "E_ti, nu_ti, alpha_ti = 105e9, 0.33, 7.06e-6\n",
    "T_ref = 273.15\n",
    "P_active, P_manifold = 1e6, 8e6\n",
    "LEVELS = ((14.0, 3.5), (10.0, 2.5), (7.0, 1.75))\n",
    "published = {\"T_max\": 436.0, \"T_min\": 367.0, \"vm_max\": 33.0, \"w_max\": 6.3}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "The plate section is described by signed distance functions (rectangle minus discs and\n",
    "rounded slits). It is split into three regions that are meshed separately and share their\n",
    "boundary nodes: the manifold, the active part and the half disc of the heating element. Points\n",
    "on every boundary and interface are placed first, spaced by a size function that is\n",
    "$h_\\mathrm{near}$ on the holes, slits and heating element and grows with 0.3 times the distance\n",
    "up to $h_\\mathrm{far}$. Each region is then filled by the DistMesh force-equilibrium iteration\n",
    "with these points fixed. The triangles are split into three quadrilaterals each (corner, two\n",
    "edge midpoints, centroid); the midpoints of boundary edges on the circular arcs are moved onto\n",
    "the arcs. The quadrilaterals are swept through the half thickness into one layer of 27-node\n",
    "hexahedra (quadratic in all three directions). The temperature mesh contains the heating\n",
    "element; the elastic mesh is the same mesh without it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def d_rect(p, x0, x1, y0, y1):\n",
    "    return -np.minimum(\n",
    "        np.minimum(p[:, 1] - y0, y1 - p[:, 1]), np.minimum(p[:, 0] - x0, x1 - p[:, 0])\n",
    "    )\n",
    "\n",
    "\n",
    "def d_circle(p, c, r):\n",
    "    return np.hypot(p[:, 0] - c[0], p[:, 1] - c[1]) - r\n",
    "\n",
    "\n",
    "def d_slit(p, x0, x1, y0, y1, r=FILLET):\n",
    "    q = np.abs(p - ((x0 + x1) / 2, (y0 + y1) / 2)) - (\n",
    "        (x1 - x0) / 2 - r,\n",
    "        (y1 - y0) / 2 - r,\n",
    "    )\n",
    "    return (\n",
    "        np.hypot(np.maximum(q[:, 0], 0), np.maximum(q[:, 1], 0))\n",
    "        + np.minimum(np.maximum(q[:, 0], q[:, 1]), 0)\n",
    "        - r\n",
    "    )\n",
    "\n",
    "\n",
    "def d_plate(p):\n",
    "    d = d_rect(p, 0, LX, 0, LY)\n",
    "    for c in HOLES:\n",
    "        d = np.maximum(d, -d_circle(p, c, R0))\n",
    "    for s in SLITS:\n",
    "        d = np.maximum(d, -d_slit(p, *s))\n",
    "    return d\n",
    "\n",
    "\n",
    "def d_heater(p):\n",
    "    return np.maximum(d_circle(p, HEATER, R0), p[:, 1] - LY)\n",
    "\n",
    "\n",
    "def d_active(p):\n",
    "    return np.maximum(d_rect(p, 30, LX, 35, LY), -d_heater(p))\n",
    "\n",
    "\n",
    "def d_manifold(p):\n",
    "    return np.maximum(d_plate(p), -d_rect(p, 30, LX + 1, 35, LY + 1))\n",
    "\n",
    "\n",
    "def size_field(p, h_far, h_near):\n",
    "    d = np.full(len(p), np.inf)\n",
    "    for c in HOLES + (HEATER,):\n",
    "        d = np.minimum(d, np.abs(d_circle(p, c, R0)))\n",
    "    for s in SLITS:\n",
    "        d = np.minimum(d, np.abs(d_slit(p, *s)))\n",
    "    return np.minimum(h_far, h_near + 0.3 * d)\n",
    "\n",
    "\n",
    "def arc(c, r, a0, a1, n=20000):\n",
    "    a = np.linspace(a0, a1, n)\n",
    "    return np.column_stack((c[0] + r * np.cos(a), c[1] + r * np.sin(a)))\n",
    "\n",
    "\n",
    "def boundary_points(h_far, h_near):\n",
    "    def resample(P):\n",
    "        s = np.concatenate(([0], np.cumsum(np.hypot(*np.diff(P, axis=0).T))))\n",
    "        fine = np.linspace(0, s[-1], 40000)\n",
    "        Q = np.column_stack((np.interp(fine, s, P[:, 0]), np.interp(fine, s, P[:, 1])))\n",
    "        h = size_field(Q, h_far, h_near)\n",
    "        n = np.concatenate(([0], np.cumsum(np.diff(fine) / (0.5 * (h[1:] + h[:-1])))))\n",
    "        t = np.interp(np.linspace(0, n[-1], max(1, int(np.ceil(n[-1]))) + 1), n, fine)\n",
    "        return np.column_stack(\n",
    "            (np.interp(t, fine, Q[:, 0]), np.interp(t, fine, Q[:, 1]))\n",
    "        )\n",
    "\n",
    "    lines = [\n",
    "        [(0, 0), (LX, 0)],\n",
    "        [(LX, 0), (LX, 10)],\n",
    "        [(LX, 20), (LX, 35)],\n",
    "        [(LX, 35), (LX, LY)],\n",
    "        [(LX, LY), (75, LY)],\n",
    "        [(75, LY), (65, LY)],\n",
    "        [(65, LY), (30, LY)],\n",
    "        [(30, LY), (20, LY)],\n",
    "        [(10, LY), (0, LY)],\n",
    "        [(0, LY), (0, 0)],\n",
    "        [(30, LY), (30, 35)],\n",
    "        [(30, 35), (LX, 35)],\n",
    "    ]\n",
    "    pieces = [resample(np.array(P, float)) for P in lines]\n",
    "    pieces += [\n",
    "        resample(arc(HOLES[0], R0, 0, 2 * np.pi)),\n",
    "        resample(arc(HOLES[1], R0, np.pi, 2 * np.pi)),\n",
    "        resample(arc(HOLES[2], R0, np.pi / 2, 1.5 * np.pi)),\n",
    "        resample(arc(HEATER, R0, np.pi, 2 * np.pi)),\n",
    "    ]\n",
    "    for x0, x1, y0, y1 in SLITS:\n",
    "        r = FILLET\n",
    "        pieces.append(\n",
    "            resample(\n",
    "                np.vstack(\n",
    "                    [\n",
    "                        arc((x1 - r, y0 + r), r, -np.pi / 2, 0),\n",
    "                        arc((x1 - r, y1 - r), r, 0, np.pi / 2),\n",
    "                        arc((x0 + r, y1 - r), r, np.pi / 2, np.pi),\n",
    "                        arc((x0 + r, y0 + r), r, np.pi, 1.5 * np.pi),\n",
    "                        [[x1 - r, y0]],\n",
    "                    ]\n",
    "                )\n",
    "            )\n",
    "        )\n",
    "    P = np.vstack(pieces)\n",
    "    _, first = np.unique(np.round(P * 1e6).astype(np.int64), axis=0, return_index=True)\n",
    "    return P[np.sort(first)]\n",
    "\n",
    "\n",
    "def distmesh(fd, fixed, box, h_far, h_near, iterations=250):\n",
    "    \"\"\"DistMesh (Persson and Strang 2004) with fixed boundary points.\"\"\"\n",
    "    (x0, y0), (x1, y1) = box\n",
    "    X, Y = np.meshgrid(\n",
    "        np.arange(x0, x1 + h_near, h_near),\n",
    "        np.arange(y0, y1 + h_near, h_near * np.sqrt(3) / 2),\n",
    "    )\n",
    "    X[1::2] += h_near / 2\n",
    "    p = np.column_stack((X.ravel(), Y.ravel()))\n",
    "    p = p[fd(p) < -0.3 * h_near]\n",
    "    keep = (\n",
    "        np.random.default_rng(0).random(len(p))\n",
    "        < (h_near / size_field(p, h_far, h_near)) ** 2\n",
    "    )\n",
    "    p = p[keep]\n",
    "    p = p[cKDTree(fixed).query(p)[0] > 0.5 * size_field(p, h_far, h_near)]\n",
    "    nf = len(fixed)\n",
    "    p = np.vstack((fixed, p))\n",
    "    for it in range(iterations):\n",
    "        tri = Delaunay(p).simplices\n",
    "        tri = tri[fd(p[tri].mean(axis=1)) < -1e-3 * h_near]\n",
    "        bars = np.unique(\n",
    "            np.sort(\n",
    "                np.vstack((tri[:, [0, 1]], tri[:, [1, 2]], tri[:, [2, 0]])), axis=1\n",
    "            ),\n",
    "            axis=0,\n",
    "        )\n",
    "        vec = p[bars[:, 0]] - p[bars[:, 1]]\n",
    "        length = np.hypot(*vec.T)\n",
    "        h = size_field(0.5 * (p[bars[:, 0]] + p[bars[:, 1]]), h_far, h_near)\n",
    "        target = h * 1.2 * np.sqrt(np.sum(length**2) / np.sum(h**2))\n",
    "        force = (np.maximum(target - length, 0) / length)[:, None] * vec\n",
    "        total = np.zeros_like(p)\n",
    "        np.add.at(total, bars[:, 0], force)\n",
    "        np.add.at(total, bars[:, 1], -force)\n",
    "        total[:nf] = 0\n",
    "        p = p + 0.2 * total\n",
    "        d = fd(p)\n",
    "        out = d > 0\n",
    "        if np.any(out):\n",
    "            e = 1e-7 * h_near\n",
    "            gx = (fd(p[out] + [e, 0]) - d[out]) / e\n",
    "            gy = (fd(p[out] + [0, e]) - d[out]) / e\n",
    "            p[out] -= (d[out] / (gx**2 + gy**2))[:, None] * np.column_stack((gx, gy))\n",
    "        p[:nf] = fixed\n",
    "        if (\n",
    "            it > 30\n",
    "            and np.max(np.hypot(*(0.2 * total[d < -1e-3 * h_near]).T), initial=0)\n",
    "            < 1e-4 * h_near\n",
    "        ):\n",
    "            break\n",
    "    p = p[(np.arange(len(p)) < nf) | (fd(p) < -0.3 * size_field(p, h_far, h_near))]\n",
    "    tri = Delaunay(p).simplices\n",
    "    tri = tri[fd(p[tri].mean(axis=1)) < -1e-3 * h_near]\n",
    "    a = p[tri]\n",
    "    ccw = (a[:, 1, 0] - a[:, 0, 0]) * (a[:, 2, 1] - a[:, 0, 1]) - (\n",
    "        a[:, 1, 1] - a[:, 0, 1]\n",
    "    ) * (a[:, 2, 0] - a[:, 0, 0]) > 0\n",
    "    tri[~ccw] = tri[~ccw][:, [0, 2, 1]]\n",
    "    return p, tri\n",
    "\n",
    "\n",
    "def plate_section(h_far, h_near):\n",
    "    \"\"\"Triangles of the three regions (0 manifold, 1 active part, 2 heating element) with shared nodes.\"\"\"\n",
    "    fixed = boundary_points(h_far, h_near)\n",
    "    points, index, triangles, region = [], {}, [], []\n",
    "    boxes = (((0, 0), (LX, LY)), ((30, 35), (LX, LY)), ((65, 85), (75, LY)))\n",
    "    for k, (fd, box) in enumerate(zip((d_manifold, d_active, d_heater), boxes)):\n",
    "        p, t = distmesh(fd, fixed[np.abs(fd(fixed)) < 1e-6], box, h_far, h_near)\n",
    "        ids = []\n",
    "        for q in p:\n",
    "            key = (round(q[0] * 1e6), round(q[1] * 1e6))\n",
    "            if key not in index:\n",
    "                index[key] = len(points)\n",
    "                points.append(q)\n",
    "            ids.append(index[key])\n",
    "        triangles.append(np.array(ids)[t])\n",
    "        region += [k] * len(t)\n",
    "    return np.array(points), np.vstack(triangles), np.array(region)\n",
    "\n",
    "\n",
    "def split_into_quads(p, t, region):\n",
    "    \"\"\"Three quadrilaterals per triangle; boundary midpoints on arcs are moved onto the arcs.\"\"\"\n",
    "    circles = [(np.array(c), R0) for c in HOLES + (HEATER,)]\n",
    "    for x0, x1, y0, y1 in SLITS:\n",
    "        circles += [\n",
    "            (np.array(c), FILLET)\n",
    "            for c in (\n",
    "                (x1 - FILLET, y0 + FILLET),\n",
    "                (x1 - FILLET, y1 - FILLET),\n",
    "                (x0 + FILLET, y1 - FILLET),\n",
    "                (x0 + FILLET, y0 + FILLET),\n",
    "            )\n",
    "        ]\n",
    "    edges = np.sort(np.vstack((t[:, [0, 1]], t[:, [1, 2]], t[:, [2, 0]])), axis=1)\n",
    "    unique, counts = np.unique(edges, axis=0, return_counts=True)\n",
    "    boundary = set(map(tuple, unique[counts == 1]))\n",
    "    points, middle = list(p), {}\n",
    "\n",
    "    def mid(a, b):\n",
    "        key = (min(a, b), max(a, b))\n",
    "        if key not in middle:\n",
    "            m = 0.5 * (p[a] + p[b])\n",
    "            for c, r in circles:\n",
    "                on_arc = (\n",
    "                    abs(np.hypot(*(p[a] - c)) - r) < 1e-6\n",
    "                    and abs(np.hypot(*(p[b] - c)) - r) < 1e-6\n",
    "                )\n",
    "                if (\n",
    "                    on_arc\n",
    "                    and np.hypot(*(p[a] - p[b])) < r\n",
    "                    and (key in boundary or r == R0 and tuple(c) == HEATER)\n",
    "                ):\n",
    "                    m = c + r * (m - c) / np.hypot(*(m - c))\n",
    "                    break\n",
    "            else:\n",
    "                if key in boundary:\n",
    "                    for _ in range(3):\n",
    "                        d, e = d_plate(m[None])[0], 1e-7\n",
    "                        g = (\n",
    "                            np.array(\n",
    "                                [\n",
    "                                    d_plate((m + (e, 0))[None])[0] - d,\n",
    "                                    d_plate((m + (0, e))[None])[0] - d,\n",
    "                                ]\n",
    "                            )\n",
    "                            / e\n",
    "                        )\n",
    "                        m = m - d * g / (g @ g)\n",
    "            middle[key] = len(points)\n",
    "            points.append(m)\n",
    "        return middle[key]\n",
    "\n",
    "    quads, quad_region = [], []\n",
    "    for (a, b, c), r in zip(t, region):\n",
    "        ab, bc, ca = mid(a, b), mid(b, c), mid(c, a)\n",
    "        g = len(points)\n",
    "        points.append((p[a] + p[b] + p[c]) / 3)\n",
    "        quads += [(a, ab, g, ca), (b, bc, g, ab), (c, ca, g, bc)]\n",
    "        quad_region += [r] * 3\n",
    "    return np.array(points), np.array(quads), np.array(quad_region)\n",
    "\n",
    "\n",
    "class HexahedralMesh(StructuredHexahedralMesh):\n",
    "    \"\"\"Unstructured trilinear hexahedra with named boundary quadrilaterals.\"\"\"\n",
    "\n",
    "    def __init__(self, geometry, coordinates, cells, facets):\n",
    "        data = trilinear_hexahedral_geometry(\n",
    "            np.asarray(coordinates, float), np.asarray(cells)\n",
    "        )\n",
    "        self.geometry = geometry\n",
    "        self.coordinates, self.cells, self.cell_volumes = (\n",
    "            data.coordinates,\n",
    "            data.cells,\n",
    "            data.volumes,\n",
    "        )\n",
    "        self.cell_count = len(self.cells)\n",
    "        self.shape = (self.cell_count, 1, 1)\n",
    "        self.mesh_id = (\n",
    "            \"plate-hex:\"\n",
    "            + sha256(self.coordinates.tobytes() + self.cells.tobytes()).hexdigest()\n",
    "        )\n",
    "        self._facets = {name: list(faces) for name, faces in facets.items()}\n",
    "        self._carrier = self._build_carrier()\n",
    "\n",
    "    def to_mapping(self):\n",
    "        return {\n",
    "            **super().to_mapping(),\n",
    "            \"generator\": \"plate-hex\",\n",
    "            \"geometry_mapping\": \"trilinear_hex8\",\n",
    "        }\n",
    "\n",
    "\n",
    "@dataclass(frozen=True, eq=False, kw_only=True)\n",
    "class PlateForHeat(Geometry):\n",
    "    dimension = 3\n",
    "\n",
    "    def boundary_groups(self):\n",
    "        names = (\"outer_edges\", \"gas_slits\", \"tie_rod_holes\", \"top\", \"symmetry\")\n",
    "        return {**{name: (name,) for name in names}, \"all\": names}\n",
    "\n",
    "\n",
    "@dataclass(frozen=True, eq=False, kw_only=True)\n",
    "class PlateForStress(Geometry):\n",
    "    dimension = 3\n",
    "\n",
    "    def boundary_groups(self):\n",
    "        names = (\n",
    "            \"symmetry_x\",\n",
    "            \"symmetry_y\",\n",
    "            \"mid_plane\",\n",
    "            \"top_active\",\n",
    "            \"top_manifold\",\n",
    "            \"free\",\n",
    "        )\n",
    "        return {**{name: (name,) for name in names}, \"all\": names}\n",
    "\n",
    "\n",
    "def face_kind(P):\n",
    "    \"\"\"Boundary kind of a quadrilateral face from its corner coordinates in mm.\"\"\"\n",
    "    x, y, z = P.T\n",
    "    if np.all(np.abs(z) < 1e-9):\n",
    "        return \"mid_plane\"\n",
    "    if np.all(np.abs(z - TH2) < 1e-9):\n",
    "        return \"top\"\n",
    "    if np.all(np.abs(x - LX) < 1e-9):\n",
    "        return \"symmetry_x\"\n",
    "    if np.all(np.abs(y - LY) < 1e-9):\n",
    "        return \"symmetry_y\"\n",
    "    if np.all(np.abs(x) < 1e-9) or np.all(np.abs(y) < 1e-9):\n",
    "        return \"outer_edges\"\n",
    "    if any(np.all(np.abs(d_slit(P[:, :2], *s)) < 2e-3) for s in SLITS):\n",
    "        return \"gas_slits\"\n",
    "    if np.all(np.abs(d_circle(P[:, :2], HEATER, R0)) < 1e-6):\n",
    "        return \"heater_seat\"\n",
    "    if any(np.all(np.abs(d_circle(P[:, :2], c, R0)) < 1e-6) for c in HOLES):\n",
    "        return \"tie_rod_holes\"\n",
    "    raise ValueError(\"unclassified boundary face\")\n",
    "\n",
    "\n",
    "HEAT_NAMES = {\n",
    "    \"mid_plane\": \"symmetry\",\n",
    "    \"symmetry_x\": \"symmetry\",\n",
    "    \"symmetry_y\": \"symmetry\",\n",
    "}\n",
    "STRESS_NAMES = {\n",
    "    \"outer_edges\": \"free\",\n",
    "    \"gas_slits\": \"free\",\n",
    "    \"tie_rod_holes\": \"free\",\n",
    "    \"heater_seat\": \"free\",\n",
    "}\n",
    "\n",
    "\n",
    "def build_plate(h_far, h_near, layers=1):\n",
    "    p, t, region = plate_section(h_far, h_near)\n",
    "    xy, quads, quad_region = split_into_quads(p, t, region)\n",
    "    n2 = len(xy)\n",
    "    zs = np.linspace(0.0, TH2, layers + 1)\n",
    "    coords = np.column_stack(\n",
    "        (\n",
    "            np.tile(xy[:, 0], layers + 1),\n",
    "            np.tile(xy[:, 1], layers + 1),\n",
    "            np.repeat(zs, n2),\n",
    "        )\n",
    "    )\n",
    "    cells = np.vstack(\n",
    "        [np.column_stack((quads + k * n2, quads + (k + 1) * n2)) for k in range(layers)]\n",
    "    )\n",
    "    cell_region = np.tile(quad_region, layers)\n",
    "    out = dict(\n",
    "        xy=xy,\n",
    "        quads=quads,\n",
    "        quad_region=quad_region,\n",
    "        triangles=len(t),\n",
    "        layers=layers,\n",
    "        h=h_near,\n",
    "    )\n",
    "    for kind, keep, geometry in (\n",
    "        (\"heat\", np.ones(len(cells), bool), PlateForHeat()),\n",
    "        (\"stress\", cell_region != 2, PlateForStress()),\n",
    "    ):\n",
    "        kept = cells[keep]\n",
    "        used = np.unique(kept)\n",
    "        renumber = np.full(len(coords), -1)\n",
    "        renumber[used] = np.arange(len(used))\n",
    "        X, kept, kept_region = coords[used], renumber[kept], cell_region[keep]\n",
    "        groups = {name: [] for name in geometry.boundary_groups()[\"all\"]}\n",
    "        owners = {}\n",
    "        for c, cell in enumerate(kept):\n",
    "            for face in FACES:\n",
    "                corners = tuple(cell[list(face)])\n",
    "                owners.setdefault(tuple(sorted(corners)), []).append((corners, c))\n",
    "        for faces in owners.values():\n",
    "            if len(faces) == 1:\n",
    "                corners, c = faces[0]\n",
    "                name = face_kind(X[list(corners)])\n",
    "                if kind == \"heat\":\n",
    "                    name = HEAT_NAMES.get(name, name)\n",
    "                else:\n",
    "                    name = STRESS_NAMES.get(name, name)\n",
    "                    if name == \"top\":\n",
    "                        name = \"top_active\" if kept_region[c] == 1 else \"top_manifold\"\n",
    "                groups[name].append(corners)\n",
    "        out[kind] = dict(\n",
    "            geometry=geometry,\n",
    "            coords=X * mm,\n",
    "            cells=kept,\n",
    "            region=kept_region,\n",
    "            groups={name: np.array(faces) for name, faces in groups.items()},\n",
    "            mesh=HexahedralMesh(geometry, X * mm, kept, groups),\n",
    "        )\n",
    "    out[\"heater_volume\"] = float(\n",
    "        out[\"heat\"][\"mesh\"].cell_volumes[out[\"heat\"][\"region\"] == 2].sum()\n",
    "    )\n",
    "    locator = SimplexLocator.from_arrays(\n",
    "        xy, np.vstack((quads[:, [0, 1, 2]], quads[:, [0, 2, 3]])), dimension=2\n",
    "    )\n",
    "    out[\"finder\"] = lambda x, y: locator.locate(np.column_stack((x, y)))[0]\n",
    "    out[\"tri_region\"] = np.concatenate((quad_region, quad_region))\n",
    "    return out\n",
    "\n",
    "\n",
    "meshes = [build_plate(h_far, h_near) for h_far, h_near in LEVELS]\n",
    "for (h_far, h_near), data in zip(LEVELS, meshes):\n",
    "    print(\n",
    "        f\"h = {h_far:4.1f}/{h_near:4.2f} mm: {data['triangles']:5d} triangles -> {len(data['quads']):5d} quadrilaterals, \"\n",
    "        f\"{data['heat']['mesh'].cell_count:5d} Q2 hexahedra ({len(data['heat']['coords'])} vertices)\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The conductivity and the heat source are assigned per cell region: a point belongs to the\n",
    "heating element if it lies in one of its quadrilaterals. The source density is the 2 W of the\n",
    "eighth divided by the meshed volume of the half disc, so the meshed heater delivers exactly\n",
    "the prescribed power."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "titanium = IsotropicSolid(\n",
    "    density=4940.0,\n",
    "    specific_heat_capacity=710.0,\n",
    "    thermal_conductivity=k_ti,\n",
    "    youngs_modulus=E_ti,\n",
    "    poisson_ratio=nu_ti,\n",
    "    thermal_expansion_coefficient=alpha_ti,\n",
    ")\n",
    "\n",
    "\n",
    "def in_heater(data, x, y):\n",
    "    tri = data[\"finder\"](np.ravel(x) / mm, np.ravel(y) / mm)\n",
    "    return (tri >= 0) & (data[\"tri_region\"][np.maximum(tri, 0)] == 2)\n",
    "\n",
    "\n",
    "class PlateConductivity:\n",
    "    \"\"\"Titanium plate with the aluminium heating element (steady problem: capacity irrelevant).\"\"\"\n",
    "\n",
    "    density, specific_heat_capacity, thermal_conductivity = 4940.0, 710.0, \"by region\"\n",
    "\n",
    "    def __init__(self, data):\n",
    "        self.data = data\n",
    "\n",
    "    def evaluate(self, name, *, x, y, z, **state):\n",
    "        if name != \"thermal_conductivity\":\n",
    "            return 1000.0\n",
    "        return float(np.where(in_heater(self.data, x, y), k_al, k_ti)[0])\n",
    "\n",
    "\n",
    "class HeaterSource:\n",
    "    def __init__(self, data):\n",
    "        self.data, self.q = data, P_heater / data[\"heater_volume\"]\n",
    "\n",
    "    def evaluate(self, points, *, time=0.0):\n",
    "        return np.where(in_heater(self.data, points[:, 0], points[:, 1]), self.q, 0.0)\n",
    "\n",
    "\n",
    "def solve_heat(data):\n",
    "    mesh_data = data[\"heat\"]\n",
    "    b = mesh_data[\"geometry\"].boundaries\n",
    "    heat = HeatConduction(\n",
    "        domain=mesh_data[\"geometry\"].domain(),\n",
    "        material=PlateConductivity(data),\n",
    "        heating=HeaterSource(data),\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Bipolar plate heating\",\n",
    "        geometry=mesh_data[\"geometry\"],\n",
    "        physics=(heat,),\n",
    "        boundary_conditions=(\n",
    "            ConvectiveHeatFlux(\n",
    "                boundary=b.outer_edges,\n",
    "                physics=heat,\n",
    "                heat_transfer_coefficient=h_surr,\n",
    "                ambient_temperature=T_surr,\n",
    "            ),\n",
    "            ConvectiveHeatFlux(\n",
    "                boundary=b.gas_slits,\n",
    "                physics=heat,\n",
    "                heat_transfer_coefficient=h_gas,\n",
    "                ambient_temperature=T_gas,\n",
    "            ),\n",
    "            HeatFlux(\n",
    "                boundary=b.tie_rod_holes | b.top | b.symmetry, physics=heat, value=0.0\n",
    "            ),\n",
    "        ),\n",
    "    )\n",
    "    numerics = Numerics(\n",
    "        spatial=FiniteElement(element=Lagrange(order=2), quadrature_order=4),\n",
    "        linear_solver=SparseDirect(),\n",
    "    )\n",
    "    return (\n",
    "        Simulation(problem=problem, mesh=mesh_data[\"mesh\"], numerics=numerics)\n",
    "        .solve_stationary()\n",
    "        .field(heat.temperature)\n",
    "    )\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class UniformExpansion(IsotropicThermalExpansion):\n",
    "    \"\"\"Thermal strain of a uniform temperature T0, whatever the coupled field: the free-expansion check.\"\"\"\n",
    "\n",
    "    uniform_temperature: float = 373.15\n",
    "\n",
    "    def evaluate(self, *, temperature, coefficient):\n",
    "        return super().evaluate(\n",
    "            temperature=self.uniform_temperature, coefficient=coefficient\n",
    "        )\n",
    "\n",
    "    def evaluate_array(self, *, temperature, coefficient):\n",
    "        return super().evaluate_array(\n",
    "            temperature=np.full(np.shape(temperature), self.uniform_temperature),\n",
    "            coefficient=coefficient,\n",
    "        )\n",
    "\n",
    "\n",
    "def solve_stress(data, temperature, pressures=(P_active, P_manifold), strain=None):\n",
    "    \"\"\"Elastic titanium plate under the coupled temperature field and the clamping pressures.\"\"\"\n",
    "    mesh_data = data[\"stress\"]\n",
    "    b = mesh_data[\"geometry\"].boundaries\n",
    "    strain = (\n",
    "        IsotropicThermalExpansion(reference_temperature=T_ref)\n",
    "        if strain is None\n",
    "        else strain\n",
    "    )\n",
    "    solid = LinearElasticity(\n",
    "        domain=mesh_data[\"geometry\"].domain(), material=titanium, thermal_strain=strain\n",
    "    )\n",
    "    couplings = (\n",
    "        FieldCoupling(\n",
    "            source=temperature,\n",
    "            target=solid.temperature,\n",
    "            transfer=FiniteElementEvaluation(),\n",
    "        ),\n",
    "    )\n",
    "    problem = Problem(\n",
    "        name=\"Bipolar plate thermal stress\",\n",
    "        geometry=mesh_data[\"geometry\"],\n",
    "        physics=(solid,),\n",
    "        boundary_conditions=(\n",
    "            FixedDisplacementComponents(\n",
    "                boundary=b.symmetry_x, physics=solid, components=(\"x\",)\n",
    "            ),\n",
    "            FixedDisplacementComponents(\n",
    "                boundary=b.symmetry_y, physics=solid, components=(\"y\",)\n",
    "            ),\n",
    "            FixedDisplacementComponents(\n",
    "                boundary=b.mid_plane, physics=solid, components=(\"z\",)\n",
    "            ),\n",
    "            Traction(\n",
    "                boundary=b.top_active, physics=solid, value=(0.0, 0.0, -pressures[0])\n",
    "            ),\n",
    "            Traction(\n",
    "                boundary=b.top_manifold, physics=solid, value=(0.0, 0.0, -pressures[1])\n",
    "            ),\n",
    "            TractionFree(boundary=b.free, physics=solid),\n",
    "        ),\n",
    "        couplings=couplings,\n",
    "    )\n",
    "    solver = ConjugateGradient(\n",
    "        preconditioner=AlgebraicMultigrid(),\n",
    "        relative_tolerance=1e-10,\n",
    "        maximum_iterations=3000,\n",
    "    )\n",
    "    numerics = Numerics(\n",
    "        spatial=FiniteElement(element=Lagrange(order=2), quadrature_order=4),\n",
    "        linear_solver=solver,\n",
    "    )\n",
    "    result = Simulation(\n",
    "        problem=problem, mesh=mesh_data[\"mesh\"], numerics=numerics\n",
    "    ).solve_stationary()\n",
    "    return (\n",
    "        result.field(solid.displacement),\n",
    "        result.field(solid.von_mises_stress),\n",
    "        result.field(solid.stress),\n",
    "    )\n",
    "\n",
    "\n",
    "GAUSS = np.array([0.5 - 0.5 * np.sqrt(0.6), 0.5, 0.5 + 0.5 * np.sqrt(0.6)])\n",
    "GAUSS_W = np.array([5.0, 8.0, 5.0]) / 18.0\n",
    "\n",
    "\n",
    "def face_quadrature(coords, faces):\n",
    "    \"\"\"3x3 Gauss points and weights on bilinear boundary quadrilaterals.\"\"\"\n",
    "    P = coords[faces]\n",
    "    s, t = np.meshgrid(GAUSS, GAUSS, indexing=\"ij\")\n",
    "    s, t, w = s.ravel(), t.ravel(), np.outer(GAUSS_W, GAUSS_W).ravel()\n",
    "    N = np.stack(((1 - s) * (1 - t), s * (1 - t), s * t, (1 - s) * t), axis=1)\n",
    "    dNs = np.stack((-(1 - t), 1 - t, t, -t), axis=1)\n",
    "    dNt = np.stack((-(1 - s), -s, s, 1 - s), axis=1)\n",
    "    points = np.einsum(\"qk,fkd->fqd\", N, P)\n",
    "    jac = np.linalg.norm(\n",
    "        np.cross(np.einsum(\"qk,fkd->fqd\", dNs, P), np.einsum(\"qk,fkd->fqd\", dNt, P)),\n",
    "        axis=2,\n",
    "    )\n",
    "    return points.reshape(-1, 3), (jac * w).ravel()\n",
    "\n",
    "\n",
    "def evaluate(field, points):\n",
    "    return np.asarray(field.evaluate(np.asarray(points, float)))\n",
    "\n",
    "\n",
    "def heat_out(data, temperature):\n",
    "    heat = data[\"heat\"]\n",
    "    rates = {}\n",
    "    for name, h, T_inf in (\n",
    "        (\"outer_edges\", h_surr, T_surr),\n",
    "        (\"gas_slits\", h_gas, T_gas),\n",
    "    ):\n",
    "        points, weights = face_quadrature(heat[\"coords\"], heat[\"groups\"][name])\n",
    "        rates[name] = float(\n",
    "            np.sum(weights * h * (evaluate(temperature, points).ravel() - T_inf))\n",
    "        )\n",
    "    return rates\n",
    "\n",
    "\n",
    "def edge_samples(n=400):\n",
    "    \"\"\"Points just inside the material along every hole, slit and the heater seat, at three depths.\"\"\"\n",
    "    eps = 1e-3\n",
    "    curves = [\n",
    "        arc(HOLES[0], R0 + eps, 0, 2 * np.pi, n),\n",
    "        arc(HOLES[1], R0 + eps, np.pi, 2 * np.pi, n // 2),\n",
    "        arc(HOLES[2], R0 + eps, np.pi / 2, 1.5 * np.pi, n // 2),\n",
    "        arc(HEATER, R0 + eps, np.pi, 2 * np.pi, n // 2),\n",
    "    ]\n",
    "    for x0, x1, y0, y1 in SLITS:\n",
    "        r = FILLET + eps\n",
    "        corners = (\n",
    "            (x1 - FILLET, y0 + FILLET),\n",
    "            (x1 - FILLET, y1 - FILLET),\n",
    "            (x0 + FILLET, y1 - FILLET),\n",
    "            (x0 + FILLET, y0 + FILLET),\n",
    "        )\n",
    "        ring = np.vstack(\n",
    "            [\n",
    "                arc(c, r, a, a + np.pi / 2, n // 8)\n",
    "                for c, a in zip(corners, (-np.pi / 2, 0, np.pi / 2, np.pi))\n",
    "            ]\n",
    "        )\n",
    "        ring = np.vstack((ring, ring[:1]))\n",
    "        s_len = np.concatenate(([0], np.cumsum(np.hypot(*np.diff(ring, axis=0).T))))\n",
    "        t = np.linspace(0, s_len[-1], 3 * n)\n",
    "        curves.append(\n",
    "            np.column_stack(\n",
    "                (np.interp(t, s_len, ring[:, 0]), np.interp(t, s_len, ring[:, 1]))\n",
    "            )\n",
    "        )\n",
    "    xy = np.vstack(curves)\n",
    "    xy = xy[(xy[:, 0] < LX) & (xy[:, 1] < LY)]\n",
    "    return (\n",
    "        np.vstack(\n",
    "            [\n",
    "                np.column_stack((xy, np.full(len(xy), z)))\n",
    "                for z in (1e-6, TH2 / 2, TH2 - 1e-6)\n",
    "            ]\n",
    "        )\n",
    "        * mm\n",
    "    )\n",
    "\n",
    "\n",
    "EDGES_XYZ = edge_samples()\n",
    "\n",
    "\n",
    "def measure(data, temperature, displacement, von_mises):\n",
    "    heat, stress = data[\"heat\"], data[\"stress\"]\n",
    "    T = evaluate(temperature, heat[\"coords\"]).ravel()\n",
    "    u = evaluate(displacement, stress[\"coords\"])\n",
    "    vm = evaluate(von_mises, stress[\"coords\"]).ravel()\n",
    "    tri = data[\"finder\"](EDGES_XYZ[:, 0] / mm, EDGES_XYZ[:, 1] / mm)\n",
    "    edges = EDGES_XYZ[(tri >= 0) & (data[\"tri_region\"][np.maximum(tri, 0)] != 2)]\n",
    "    vm_edges = evaluate(von_mises, edges).ravel()\n",
    "    samples = np.vstack((stress[\"coords\"], edges))\n",
    "    vm_all = np.concatenate((vm, vm_edges))\n",
    "    top = np.abs(stress[\"coords\"][:, 2] - TH2 * mm) < 1e-12\n",
    "    rates = heat_out(data, temperature)\n",
    "    return dict(\n",
    "        T=T,\n",
    "        u=u,\n",
    "        vm=vm,\n",
    "        T_max=T.max(),\n",
    "        T_min=T.min(),\n",
    "        vm_max=vm_all.max(),\n",
    "        vm_where=samples[vm_all.argmax()] / mm,\n",
    "        w_max=u[top, 2].max(),\n",
    "        q_out=rates,\n",
    "        h=data[\"h\"],\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Solve\n",
    "\n",
    "Three meshes; on each the temperature is solved first and then the stress with the coupled\n",
    "temperature field. On the coarsest mesh one more stress problem serves as the exact check:\n",
    "a uniform temperature of 100 °C with the manifold pressure of 8 MPa on the whole top face.\n",
    "Only the fields of the finest mesh are kept for the figure."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "T_uniform = 373.15\n",
    "runs = []\n",
    "for data in meshes:\n",
    "    start = time.perf_counter()\n",
    "    temperature = solve_heat(data)\n",
    "    t_heat = time.perf_counter() - start\n",
    "    displacement, von_mises, stress = solve_stress(data, temperature)\n",
    "    run = measure(data, temperature, displacement, von_mises)\n",
    "    print(\n",
    "        f\"h_near = {data['h']:4.2f} mm ({data['heat']['mesh'].cell_count:5d} hexahedra): T = {run['T_min']:.2f} ... \"\n",
    "        f\"{run['T_max']:.2f} K, peak von Mises {run['vm_max'] / 1e6:6.3f} MPa, w_max = {run['w_max'] * 1e6:.4f} um  \"\n",
    "        f\"[heat {t_heat:.0f} s, total {time.perf_counter() - start:.0f} s]\"\n",
    "    )\n",
    "    if not runs:\n",
    "        start = time.perf_counter()\n",
    "        u_hom, vm_hom, s_hom = solve_stress(\n",
    "            data,\n",
    "            temperature,\n",
    "            pressures=(P_manifold, P_manifold),\n",
    "            strain=UniformExpansion(\n",
    "                reference_temperature=T_ref, uniform_temperature=T_uniform\n",
    "            ),\n",
    "        )\n",
    "        X = data[\"stress\"][\"coords\"]\n",
    "        hom = dict(\n",
    "            X=X,\n",
    "            u=evaluate(u_hom, X),\n",
    "            s=evaluate(s_hom, X),\n",
    "            vm=evaluate(vm_hom, X).ravel(),\n",
    "        )\n",
    "        del u_hom, vm_hom, s_hom\n",
    "        print(\n",
    "            f\"homogeneous check problem on the coarsest mesh: {time.perf_counter() - start:.0f} s\"\n",
    "        )\n",
    "    if data is meshes[-1]:\n",
    "        run.update(data=data, temperature=temperature, stress=stress)\n",
    "    runs.append(run)\n",
    "    del temperature, displacement, von_mises, stress\n",
    "fine = runs[-1]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the reference\n",
    "\n",
    "**Exact homogeneous solution** (coarsest mesh, uniform 100 °C, uniform 8 MPa clamping)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "X = hom[\"X\"]\n",
    "strain0, P = alpha_ti * (T_uniform - T_ref), P_manifold\n",
    "r = np.column_stack((X[:, 0] - LX * mm, X[:, 1] - LY * mm, X[:, 2]))\n",
    "u_exact = strain0 * r + P / E_ti * r * np.array([nu_ti, nu_ti, -1.0])\n",
    "u_num, s_num, vm = hom[\"u\"], hom[\"s\"], hom[\"vm\"]\n",
    "err_u = np.max(np.linalg.norm(u_num - u_exact, axis=1)) / np.max(\n",
    "    np.linalg.norm(u_exact, axis=1)\n",
    ")\n",
    "err_s = np.max(np.abs(s_num - np.array([0, 0, -P, 0, 0, 0])), axis=0) / P\n",
    "print(f\"homogeneous solution: max |u - u_exact| / max |u_exact| = {err_u:.1e}\")\n",
    "print(\n",
    "    f\"  max |sigma - sigma_exact| / P per component (xx, yy, zz, xy, yz, xz): \"\n",
    "    + \", \".join(f\"{e:.1e}\" for e in err_s)\n",
    ")\n",
    "print(\n",
    "    f\"  von Mises: {vm.min() / 1e6:.6f} ... {vm.max() / 1e6:.6f} MPa (exact {P / 1e6:.1f} MPa)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Heat balance.** The power leaving through the gas slits and the outer edges must equal the\n",
    "2 W of the heating element in the modelled eighth. The Galerkin solution satisfies the global\n",
    "balance exactly (the cooled faces are integrated exactly with 3x3 Gauss points), so the\n",
    "deviation is at round-off level on every mesh; the split between slits and edges converges."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\"\\nheat balance           \" + \"\".join(f\"  h = {r['h']:.2f} mm\" for r in runs))\n",
    "for name in (\"gas_slits\", \"outer_edges\"):\n",
    "    print(f\"  {name:20s} \" + \"\".join(f\"  {r['q_out'][name]:9.5f} W\" for r in runs))\n",
    "print(\n",
    "    f\"  {'total (ref 2 W)':20s} \"\n",
    "    + \"\".join(f\"  {sum(r['q_out'].values()):9.5f} W\" for r in runs)\n",
    ")\n",
    "print(\n",
    "    f\"  {'relative deviation':20s} \"\n",
    "    + \"\".join(f\"  {sum(r['q_out'].values()) / P_heater - 1:+10.1e}\" for r in runs)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Published levels and the restrained bound** (finest mesh). The published model shows the\n",
    "temperature, the von Mises stress and the out-of-plane displacement as colour plots; the\n",
    "values below are read from their colour bars (about +-1 K, +-1 MPa, +-0.2 um)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "bound = E_ti * alpha_ti * (fine[\"T_max\"] - fine[\"T_min\"]) / (1 - nu_ti)\n",
    "print(f\"\\nquantity                     computed    published   deviation\")\n",
    "print(\n",
    "    f\"  T_max [K]                  {fine['T_max']:9.2f}   {published['T_max']:9.1f}   {fine['T_max'] / published['T_max'] - 1:+.1%}\"\n",
    ")\n",
    "print(\n",
    "    f\"  T_min [K]                  {fine['T_min']:9.2f}   {published['T_min']:9.1f}   {fine['T_min'] / published['T_min'] - 1:+.1%}\"\n",
    ")\n",
    "print(\n",
    "    f\"  peak von Mises [MPa]       {fine['vm_max'] / 1e6:9.2f}   {published['vm_max']:9.1f}   {fine['vm_max'] / 1e6 / published['vm_max'] - 1:+.1%}\"\n",
    "    f\"   at (x, y, z) = ({fine['vm_where'][0]:.1f}, {fine['vm_where'][1]:.1f}, {fine['vm_where'][2]:.1f}) mm\"\n",
    ")\n",
    "print(\n",
    "    f\"  w_max [um]                 {fine['w_max'] * 1e6:9.3f}   {published['w_max']:9.1f}   {fine['w_max'] * 1e6 / published['w_max'] - 1:+.1%}\"\n",
    ")\n",
    "print(\n",
    "    f\"  restrained bound E alpha (T_max - T_min)/(1 - nu) = {bound / 1e6:.1f} MPa; peak / bound = {fine['vm_max'] / bound:.2f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Mesh study.** The cell size at the holes, slits and heater seat shrinks by a factor 1.4 per\n",
    "level (and the far-field size with it). Observed order and Richardson estimate from the three\n",
    "meshes; the peak von Mises stress is the maximum over all mesh vertices and over dense samples\n",
    "along every hole, slit and the heater seat at three depths."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def richardson(values, hs):\n",
    "    f1, f2, f3 = values\n",
    "    ratio = (f1 - f2) / (f2 - f3)\n",
    "    lo, hi = 0.2, 12.0\n",
    "    for _ in range(200):\n",
    "        p = 0.5 * (lo + hi)\n",
    "        if (hs[0] ** p - hs[1] ** p) / (hs[1] ** p - hs[2] ** p) > ratio:\n",
    "            hi = p\n",
    "        else:\n",
    "            lo = p\n",
    "    return p, f3 + (f3 - f2) * hs[2] ** p / (hs[1] ** p - hs[2] ** p)\n",
    "\n",
    "\n",
    "hs = np.array([r[\"h\"] for r in runs])\n",
    "print(\n",
    "    \"\\nmesh study                 \"\n",
    "    + \"\".join(f\"  h = {h:.2f} mm\" for h in hs)\n",
    "    + \"   change last two   order   Richardson\"\n",
    ")\n",
    "for key, label, scale in (\n",
    "    (\"T_max\", \"T_max [K]\", 1.0),\n",
    "    (\"vm_max\", \"peak von Mises [MPa]\", 1e-6),\n",
    "    (\"w_max\", \"w_max [um]\", 1e6),\n",
    "):\n",
    "    values = np.array([r[key] for r in runs])\n",
    "    monotone = (values[1] - values[0]) * (values[2] - values[1]) > 0\n",
    "    p, rich = richardson(values, hs) if monotone else (np.nan, np.nan)\n",
    "    if 0.5 < p < 6.0:\n",
    "        tail = f\"   {p:5.2f}   {rich * scale:10.4f}\"\n",
    "    else:\n",
    "        tail = \"   (changes at round-off/mesh-noise level: no asymptotic order)\"\n",
    "    print(\n",
    "        f\"  {label:24s} \"\n",
    "        + \"\".join(f\"  {v * scale:10.4f}\" for v in values)\n",
    "        + f\"   {abs(values[2] / values[1] - 1):12.1e}\"\n",
    "        + tail\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Top: temperature and von Mises stress on the surface of the whole plate (the computed eighth\n",
    "mirrored about its two in-plane symmetry planes; the upper half of the thickness is shown).\n",
    "Bottom left: out-of-plane displacement of the top face of the modelled eighth. Bottom middle:\n",
    "temperature and in-plane stresses along the line $x=70$ mm from the seat of the heating\n",
    "element down to gas slit 2, mid-thickness. Bottom right: mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "heat_mesh, stress_mesh = fine[\"data\"][\"heat\"], fine[\"data\"][\"stress\"]\n",
    "\n",
    "\n",
    "def mirrored_surface(mesh_data, names):\n",
    "    \"\"\"Points and triangles of the named faces, completed about the two symmetry planes (lengths in mm).\"\"\"\n",
    "    faces = np.vstack(\n",
    "        [mesh_data[\"groups\"][name] for name in names if len(mesh_data[\"groups\"][name])]\n",
    "    )\n",
    "    triangles = np.r_[faces[:, [0, 1, 2]], faces[:, [0, 2, 3]]]\n",
    "    base = mesh_data[\"coords\"] / mm\n",
    "    copies = [\n",
    "        base * (sx, sy, 1) + (2 * LX * (sx < 0), 2 * LY * (sy < 0), 0)\n",
    "        for sx, sy in ((1, 1), (-1, 1), (1, -1), (-1, -1))\n",
    "    ]\n",
    "    return np.vstack(copies), np.vstack([triangles + k * len(base) for k in range(4)])\n",
    "\n",
    "\n",
    "top_faces = np.vstack(\n",
    "    [stress_mesh[\"groups\"][name] for name in (\"top_active\", \"top_manifold\")]\n",
    ")\n",
    "y_line = np.linspace(85.0 - 1e-6, 20.0 + 1e-6, 200)\n",
    "line = np.column_stack((np.full(200, 70.0), y_line, np.full(200, 2.5))) * mm\n",
    "s_line = evaluate(fine[\"stress\"], line)\n",
    "tracked = {\n",
    "    \"T_max - 273.15 K\": np.array([r[\"T_max\"] for r in runs]) - 273.15,\n",
    "    \"peak von Mises\": np.array([r[\"vm_max\"] for r in runs]),\n",
    "    \"w_max\": np.array([r[\"w_max\"] for r in runs]),\n",
    "}\n",
    "fig = plots.figure(\n",
    "    layout=[\n",
    "        [\"temperature\"] * 3 + [\"stress\"] * 3,\n",
    "        [\"lift\", \"lift\", \"line\", \"line\", \"study\", \"study\"],\n",
    "    ],\n",
    "    size=(17, 12.5),\n",
    ")\n",
    "points, triangles = mirrored_surface(\n",
    "    heat_mesh, (\"top\", \"outer_edges\", \"gas_slits\", \"tie_rod_holes\")\n",
    ")\n",
    "plots.trisurface(\n",
    "    points,\n",
    "    triangles,\n",
    "    np.tile(fine[\"T\"], 4),\n",
    "    camera=plots.Camera(elevation=38, azimuth=-62),\n",
    "    label=\"temperature T [K]\",\n",
    "    title=\"Temperature of the heated plate (lengths in mm)\",\n",
    "    ax=fig[\"temperature\"],\n",
    ")\n",
    "points, triangles = mirrored_surface(\n",
    "    stress_mesh, (\"top_active\", \"top_manifold\", \"free\")\n",
    ")\n",
    "plots.trisurface(\n",
    "    points,\n",
    "    triangles,\n",
    "    np.tile(fine[\"vm\"] * 1e-6, 4),\n",
    "    camera=plots.Camera(elevation=38, azimuth=-62),\n",
    "    label=\"von Mises stress [MPa]\",\n",
    "    title=\"von Mises stress (lengths in mm)\",\n",
    "    ax=fig[\"stress\"],\n",
    ")\n",
    "plots.heatmap(\n",
    "    stress_mesh[\"coords\"][:, 0] / mm,\n",
    "    stress_mesh[\"coords\"][:, 1] / mm,\n",
    "    fine[\"u\"][:, 2] * 1e6,\n",
    "    triangles=np.r_[top_faces[:, [0, 1, 2]], top_faces[:, [0, 2, 3]]],\n",
    "    contours=10,\n",
    "    label=\"w [µm]\",\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"y [mm]\",\n",
    "    title=\"Out-of-plane displacement of the top face\",\n",
    "    ax=fig[\"lift\"],\n",
    ")\n",
    "plots.line(\n",
    "    90 - y_line,\n",
    "    {\n",
    "        \"sigma_xx (hoop at the seat)\": s_line[:, 0] / 1e6,\n",
    "        \"sigma_yy\": s_line[:, 1] / 1e6,\n",
    "        \"sigma_zz (clamping 1 / 8 MPa)\": s_line[:, 2] / 1e6,\n",
    "    },\n",
    "    right={\"temperature\": evaluate(fine[\"temperature\"], line).ravel()},\n",
    "    styles={\"sigma_zz (clamping 1 / 8 MPa)\": \"dashed\"},\n",
    "    hlines=0.0,\n",
    "    xlabel=\"distance from the heater centre, 90 - y [mm]\",\n",
    "    ylabel=\"stress [MPa]\",\n",
    "    right_label=\"T [K]\",\n",
    "    title=\"Line x = 70 mm, mid-thickness\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[\"line\"],\n",
    ")\n",
    "plots.line(\n",
    "    hs,\n",
    "    {label: values / values[-1] for label, values in tracked.items()},\n",
    "    hlines=1.0,\n",
    "    markers=True,\n",
    "    xlabel=\"cell size at the features h [mm]\",\n",
    "    ylabel=\"value / value on the finest mesh\",\n",
    "    title=\"Mesh study\",\n",
    "    ax=fig[\"study\"],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the heating transient: with the densities and heat capacities of the table the plate\n",
    "needs several minutes to approach the steady state, and the stress peak during warm-up can\n",
    "exceed the steady value because the heater seat is then much hotter than the rest of the plate.\n",
    "A second variant replaces the free sliding of the tie-rod holes by contact with the rods, which\n",
    "adds a constraint at the holes and raises the stress there."
   ]
  }
 ]
}
