{
 "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 expansion in a MEMS device\n",
    "\n",
    "Micro-electro-mechanical devices such as gyroscopes and resonators must keep their shape while\n",
    "the drive current heats them. The device is a meander of four hairpins etched from a 10 µm layer\n",
    "of the copper-beryllium alloy UNS C17500: legs 10 µm wide and 80 µm tall, half-ring arches with\n",
    "radii of 10 and 20 µm, and short bars that join the hairpins at the bottom. The meander stands on\n",
    "its bottom faces, which are bonded to a circuit board; all other faces lose heat to the\n",
    "surrounding air by natural convection.\n",
    "\n",
    "The temperature follows from steady heat conduction with a volumetric source $Q$, the\n",
    "displacement from linear thermoelasticity with the thermal strain $\\alpha\\,(T-T_\\mathrm{ref})$:\n",
    "\n",
    "$$-\\nabla\\cdot(k\\nabla T)=Q,\\qquad \\nabla\\cdot\\boldsymbol\\sigma=0,\\quad\n",
    "  \\boldsymbol\\sigma=\\mathbb C:\\big(\\boldsymbol\\varepsilon(\\mathbf u)-\\alpha\\,(T-T_\\mathrm{ref})\\,\\mathbf I\\big).$$\n",
    "\n",
    "**Joule heating.** The heat comes from the drive current. A Joule source computed from an\n",
    "electric-current model is not yet available through `Problem`/`Simulation`, so the heat is\n",
    "prescribed as the uniform volumetric source it produces, $Q=I^2R/V=I^2\\rho_e/A^2=10^8$ W/m³.\n",
    "With the resistivity $\\rho_e\\approx3.8\\cdot10^{-8}$ Ω m of the alloy and the 10 µm × 10 µm\n",
    "cross-section $A$ this is a drive current of about 5 mA; the slight current crowding at the inner\n",
    "edge of the arches is neglected.\n",
    "\n",
    "The part comes from the CAD file `mems_thermal_actuator_expansion.step`, written by\n",
    "`mems_thermal_actuator_expansion_geometry.py` with the CAD objects of OneSimulation. It names the\n",
    "bonded faces `base`.\n",
    "\n",
    "| face | thermal condition | mechanical condition |\n",
    "|---|---|---|\n",
    "| `base` (bonded to the board) | insulated | fixed (rigid board), or the board's own free expansion (matched board) |\n",
    "| all other faces | convection, $h=10$ W/(m² K), air at 298 K | traction free |\n",
    "\n",
    "**Reference.** (1) The published device temperature of 323.67 K for this configuration. The Biot\n",
    "number $h\\,d/k$ is of order $10^{-6}$, so the device is isothermal to within millikelvin at the\n",
    "lumped-body temperature $T_\\infty+QV/(hA)$ (F. P. Incropera et al., *Fundamentals of Heat and\n",
    "Mass Transfer*, 7th ed., Wiley 2011, Sec. 5.2). (2) On a board that expands like the alloy itself\n",
    "the device expands freely: the displacement is exactly $\\alpha\\,\\Delta T\\,\\mathbf x$ and the\n",
    "stress vanishes (S. Timoshenko and J. N. Goodier, *Theory of Elasticity*, 3rd ed., McGraw-Hill\n",
    "1970, §150). (3) On a rigid board, a mesh study of the largest displacement."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid, PolynomialLaw\n",
    "from onesim.meshing import TetrahedralMesher, with_order\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 SparseDirect\n",
    "from onesim.physics.heat_transfer import ConvectiveHeatFlux, HeatConduction, HeatFlux\n",
    "from onesim.physics.solid_mechanics import (\n",
    "    FixedDisplacement,\n",
    "    IsotropicThermalExpansion,\n",
    "    LinearElasticity,\n",
    "    TractionFree,\n",
    ")\n",
    "from onesim.results.comparisons import convergence\n",
    "from onesim.results.integration import measure\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.field_connections import FieldCoupling\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 meander with its named faces. `TetrahedralMesher` fills the micrometre part\n",
    "with tetrahedra; `geometry_order=2` with `curver=with_order` gives them quadratic edges that\n",
    "follow the round arches. Three cell sizes serve the mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "um = 1e-6\n",
    "meander = load(\"mems_thermal_actuator_expansion.step\")\n",
    "faces = meander.boundaries\n",
    "free = faces.all - faces.base\n",
    "sizes = [6.0 * um, 4.5 * um, 3.5 * um]\n",
    "meshes = [\n",
    "    TetrahedralMesher(target_size=size, geometry_order=2, curver=with_order).generate(\n",
    "        meander\n",
    "    )\n",
    "    for size in sizes\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=22, azimuth=-60, up=\"y\")\n",
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.geometry(\n",
    "    meander,\n",
    "    selection={\"base (bonded)\": faces.base, \"front\": faces.front},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Copper-beryllium meander with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[-1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Finest mesh: {meshes[-1].cell_count} curved tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Temperature\n",
    "\n",
    "The alloy data of C17500 at 20 °C are $k=208$ W/(m K), $E=138$ GPa, $\\nu=0.30$ and\n",
    "$\\alpha=16.8\\cdot10^{-6}$ 1/K, with linear temperature laws about 293.15 K. The conductivity is\n",
    "taken at the air temperature; it has no visible effect on the temperature level, which is set by\n",
    "the convection at the surface."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "Q, h_air, T_air, T_ref, T_published = 1e8, 10.0, 298.0, 298.0, 323.67\n",
    "conductivity = PolynomialLaw((208.0, 208.0 * 2.0e-4), unit=\"W/m/K\", reference=293.15)\n",
    "modulus = PolynomialLaw((138e9, -138e9 * 3.5e-4), unit=\"Pa\", reference=293.15)\n",
    "expansion = PolynomialLaw((16.8e-6, 16.8e-6 * 2.5e-4), unit=\"1/K\", reference=293.15)\n",
    "alloy_at = lambda T: IsotropicSolid(\n",
    "    density=8830.0,\n",
    "    specific_heat_capacity=420.0,\n",
    "    poisson_ratio=0.30,\n",
    "    thermal_conductivity=float(conductivity.evaluate(temperature=T)),\n",
    "    youngs_modulus=float(modulus.evaluate(temperature=T)),\n",
    "    thermal_expansion_coefficient=float(expansion.evaluate(temperature=T)),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "heat = HeatConduction(domain=meander.volume, material=alloy_at(T_air), heating=Q)\n",
    "heating = Problem(\n",
    "    name=\"Joule-heated meander\",\n",
    "    geometry=meander,\n",
    "    physics=(heat,),\n",
    "    boundary_conditions=(\n",
    "        ConvectiveHeatFlux(\n",
    "            boundary=free,\n",
    "            physics=heat,\n",
    "            heat_transfer_coefficient=h_air,\n",
    "            ambient_temperature=T_air,\n",
    "        ),\n",
    "        HeatFlux(boundary=faces.base, physics=heat, value=0.0),\n",
    "    ),\n",
    ")\n",
    "temperatures = [\n",
    "    Simulation(problem=heating, mesh=mesh, numerics=numerics)\n",
    "    .solve_stationary()\n",
    "    .field(heat.temperature)\n",
    "    for mesh in meshes\n",
    "]\n",
    "T = temperatures[-1]\n",
    "T_nodes = np.ravel(T.evaluate(meshes[-1].coordinates))\n",
    "T_device = float(T_nodes.mean())"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Thermal expansion\n",
    "\n",
    "The elastic data are taken at the computed device temperature. The temperature field enters the\n",
    "elastic model as thermal strain through a field coupling. On the rigid board the bonded faces are\n",
    "fixed; on the matched board they follow the free expansion $\\alpha\\,\\Delta T\\,\\mathbf x$ of a\n",
    "board made of the same alloy."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "alloy = alloy_at(T_device)\n",
    "alpha, rise = alloy.thermal_expansion_coefficient, T_device - T_ref\n",
    "solid = LinearElasticity(\n",
    "    domain=meander.volume,\n",
    "    material=alloy,\n",
    "    thermal_strain=IsotropicThermalExpansion(reference_temperature=T_ref),\n",
    ")\n",
    "supports = {\n",
    "    \"rigid\": (0.0, 0.0, 0.0),\n",
    "    \"matched\": lambda x, y, z: alpha * rise * np.stack((x, y, z), axis=-1),\n",
    "}\n",
    "runs = {\n",
    "    (board, level): Simulation(\n",
    "        problem=Problem(\n",
    "            name=f\"Meander on a {board} board\",\n",
    "            geometry=meander,\n",
    "            physics=(solid,),\n",
    "            boundary_conditions=(\n",
    "                FixedDisplacement(\n",
    "                    boundary=faces.base, physics=solid, value=supports[board]\n",
    "                ),\n",
    "                TractionFree(boundary=free, physics=solid),\n",
    "            ),\n",
    "            couplings=(\n",
    "                FieldCoupling(\n",
    "                    source=temperatures[level],\n",
    "                    target=solid.temperature,\n",
    "                    transfer=FiniteElementEvaluation(),\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=meshes[level],\n",
    "        numerics=numerics,\n",
    "    ).solve_stationary()\n",
    "    for board, level in [(\"rigid\", 0), (\"rigid\", 1), (\"rigid\", 2), (\"matched\", 1)]\n",
    "}\n",
    "rigid, matched = [runs[\"rigid\", level] for level in range(3)], runs[\"matched\", 1]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Temperature against the published value and the lumped body, the heat balance, the free\n",
    "expansion on the matched board and the mesh study on the rigid board."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "V, A = measure(T), measure(T, boundary=free)\n",
    "T_lumped = T_air + Q * V / (h_air * A)\n",
    "print(\n",
    "    f\"device temperature: {T_nodes.min():.4f} K to {T_nodes.max():.4f} K, mean {T_device:.4f} K\"\n",
    ")\n",
    "print(\n",
    "    f\"published {T_published:.2f} K: deviation {T_device - T_published:+.3f} K ({100 * (T_device - T_published) / (T_published - T_air):+.2f} % of the rise)\"\n",
    ")\n",
    "print(\n",
    "    f\"lumped body T_air + QV/(hA) = {T_lumped:.4f} K (V = {V / um**3:.0f} µm³, A = {A / um**2:.0f} µm²)\"\n",
    ")\n",
    "print(\n",
    "    f\"heat balance: generated {1e6 * Q * V:.5f} µW, convected {1e6 * T.boundary_flux(free):.5f} µW\"\n",
    ")\n",
    "print(\"cell size [µm]   tetrahedra   mean temperature [K]\")\n",
    "for size, mesh, field in zip(sizes, meshes, temperatures):\n",
    "    print(\n",
    "        f\"{size / um:14.1f} {mesh.cell_count:12d} {np.mean(field.evaluate(mesh.coordinates)):20.4f}\"\n",
    "    )\n",
    "\n",
    "points = np.asarray(meshes[1].coordinates)\n",
    "u_matched = matched.field(solid.displacement).evaluate(points)\n",
    "print(\n",
    "    f\"matched board: largest deviation from alpha dT x = {np.abs(u_matched - alpha * rise * points).max() / (alpha * rise * np.abs(points).max()):.1e} \"\n",
    "    f\"of the largest displacement; largest von Mises stress = \"\n",
    "    f\"{matched.field(solid.von_mises_stress).evaluate(points).max() / (alloy.youngs_modulus * alpha * rise):.1e} E alpha dT\"\n",
    ")\n",
    "\n",
    "u_max = [\n",
    "    float(\n",
    "        np.linalg.norm(\n",
    "            result.field(solid.displacement).evaluate(mesh.coordinates), axis=1\n",
    "        ).max()\n",
    "    )\n",
    "    for result, mesh in zip(rigid, meshes)\n",
    "]\n",
    "study = convergence(u_max, sizes)\n",
    "print(\"rigid board:  cell size [µm]   largest displacement [nm]\")\n",
    "for size, value in zip(sizes, u_max):\n",
    "    print(f\"{size / um:28.1f} {1e9 * value:24.3f}\")\n",
    "print(\n",
    "    f\"change between the two finest meshes {100 * study.change:.2f} %, observed order {study.order or np.nan:.1f}, \"\n",
    "    f\"extrapolated {1e9 * (study.extrapolated or np.nan):.3f} nm; free expansion of the arch tops alpha dT y = {1e9 * alpha * rise * 100 * um:.3f} nm\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The temperature (deviation from its mean in millikelvin), the displacement on the rigid board on\n",
    "the 300 times magnified shape, the von Mises stress on the rigid board and the mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "displacement, mises = rigid[-1].field(solid.displacement), rigid[-1].field(\n",
    "    solid.von_mises_stress\n",
    ")\n",
    "fig = plots.figure(2, 2, size=(16, 11))\n",
    "plots.surface(\n",
    "    T,\n",
    "    component=lambda values, position: 1e3 * (values - T_device),\n",
    "    camera=view,\n",
    "    label=\"T - T_mean [mK]\",\n",
    "    title=f\"Temperature, mean {T_device:.2f} K\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.surface(\n",
    "    displacement,\n",
    "    component=lambda u, position: 1e9 * np.linalg.norm(u, axis=1),\n",
    "    deformation=displacement,\n",
    "    deformation_scale=300.0,\n",
    "    camera=view,\n",
    "    label=\"|u| [nm]\",\n",
    "    title=\"Displacement on the rigid board (magnified 300 times)\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.surface(\n",
    "    mises,\n",
    "    component=lambda s, position: s / 1e6,\n",
    "    limits=(0.0, 60.0),\n",
    "    camera=view,\n",
    "    label=\"von Mises stress [MPa]\",\n",
    "    title=\"Thermal stress on the rigid board\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    [size / um for size in sizes],\n",
    "    {\"rigid board\": [1e9 * value for value in u_max]},\n",
    "    markers=True,\n",
    "    hlines={\"extrapolated to zero cell size\": 1e9 * (study.extrapolated or u_max[-1])},\n",
    "    xlabel=\"cell size [µm]\",\n",
    "    ylabel=\"largest displacement [nm]\",\n",
    "    title=\"Mesh study\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Bond the meander to a glass-epoxy board with $\\alpha=18\\cdot10^{-6}$ 1/K by changing the support\n",
    "of the matched board: the board then stretches the feet and the stress concentrates at the\n",
    "joining bars. Doubling the drive current quadruples the heat source and the temperature rise,\n",
    "because the device stays in the lumped-body regime. Change the arch radii or the leg height in\n",
    "`mems_thermal_actuator_expansion_geometry.py` and write the STEP file again to compare designs."
   ]
  }
 ]
}
