{
 "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": [
    "# Curvature of a prestressed micromirror\n",
    "\n",
    "Thin films deposited on a substrate are rarely free of stress. A metal film plated onto a\n",
    "micromirror tries to contract, the plate resists, and the pair bends into a spherical bowl. In\n",
    "MEMS this is both a nuisance (mirrors that should be flat) and a tool (curled actuators and\n",
    "springs).\n",
    "\n",
    "The mirror is a square polysilicon plate, 1 mm wide and $t_s=10$ µm thick, with a gold film of\n",
    "$t_f=0.5$ µm on its upper face. The residual stress comes from the film being deposited 63.3 K\n",
    "above the operating temperature: with the thermal expansion coefficients of gold and\n",
    "polysilicon the misfit strain is $\\varepsilon^*=(\\alpha_f-\\alpha_s)\\,\\Delta T=-7.34\\cdot10^{-4}$,\n",
    "which in a film held flat is an equibiaxial tension of\n",
    "$\\sigma_f=-E_f\\varepsilon^*/(1-\\nu_f)=100$ MPa.\n",
    "\n",
    "| layer | $E$ [GPa] | $\\nu$ | $\\alpha$ [1/K] |\n",
    "|---|---|---|---|\n",
    "| polysilicon plate | 160 | 0.22 | $2.6\\cdot10^{-6}$ |\n",
    "| gold film | 79 | 0.42 | $14.2\\cdot10^{-6}$ |\n",
    "\n",
    "Only a quarter is modelled: the planes $x=0$ and $y=0$ through the centre are symmetry planes,\n",
    "and the centre line is held vertically. The stack comes from\n",
    "`prestressed_micromirror_curvature.step`, the film region from\n",
    "`prestressed_micromirror_curvature_film.step`; the script\n",
    "`prestressed_micromirror_curvature_geometry.py` builds both with the CAD objects of\n",
    "OneSimulation.\n",
    "\n",
    "**Reference.** With the biaxial moduli $E'=E/(1-\\nu)$, $m=t_f/t_s$, $n=E_f'/E_s'$ and\n",
    "$h=t_f+t_s$, the bilayer formula of Timoshenko (J. Opt. Soc. Am. 11 (1925) 233) gives the\n",
    "curvature\n",
    "\n",
    "$$\\kappa=\\frac{6\\,|\\varepsilon^*|\\,(1+m)^2}{h\\,\\big[3(1+m)^2+(1+mn)(m^2+1/(mn))\\big]},$$\n",
    "\n",
    "and for a very thin film it reduces to Stoney's formula (Proc. R. Soc. London A 82 (1909) 172),\n",
    "$\\kappa=6\\sigma_f t_f/(E_s' t_s^2)$, see L. B. Freund and S. Suresh, *Thin Film Materials*,\n",
    "Cambridge University Press (2003), Ch. 2."
   ]
  },
  {
   "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 Piecewise, StructuredHexahedralMesher, Uniform\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 FixedTemperature, HeatConduction\n",
    "from onesim.physics.solid_mechanics import (\n",
    "    FixedDisplacementComponents,\n",
    "    IsotropicThermalExpansion,\n",
    "    LinearElasticity,\n",
    "    TractionFree,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation, regionwise\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",
    "Quadratic hexahedra: 16 x 16 across the quarter, three layers through the plate and one through\n",
    "the film."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mirror, film = load(\"prestressed_micromirror_curvature.step\"), load(\n",
    "    \"prestressed_micromirror_curvature_film.step\"\n",
    ")\n",
    "faces = mirror.boundaries\n",
    "half_side, _, total = mirror.size\n",
    "film_thickness = film.size[2]\n",
    "plate_thickness = total - film_thickness\n",
    "mesh = StructuredHexahedralMesher(\n",
    "    cells=(16, 16, 4),\n",
    "    grading=(\n",
    "        Uniform(16),\n",
    "        Uniform(16),\n",
    "        Piecewise(((plate_thickness, Uniform(3)), (film_thickness, Uniform(1)))),\n",
    "    ),\n",
    ").generate(mirror)\n",
    "\n",
    "view = plots.Camera(elevation=35, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(15, 5.5))\n",
    "plots.geometry(\n",
    "    [mirror.named(\"polysilicon plate\"), film.named(\"gold film\")],\n",
    "    camera=view,\n",
    "    title=\"Quarter mirror and its film\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{mesh.cell_count} quadratic hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The properties of the two layers are given region by region. A heat-conduction solve with the\n",
    "operating temperature on all faces provides the temperature field, which enters the elastic\n",
    "model as thermal strain relative to the deposition temperature."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "layers = {\"plate\": (160e9, 0.22, 2.6e-6), \"film\": (79e9, 0.42, 14.2e-6)}\n",
    "deposition, cooling = 358.15, 63.3\n",
    "layered = lambda index, unit: regionwise(\n",
    "    ((film, layers[\"film\"][index]),), default=layers[\"plate\"][index], unit=unit\n",
    ")\n",
    "material = replace(\n",
    "    IsotropicSolid(\n",
    "        density=2330.0,\n",
    "        specific_heat_capacity=700.0,\n",
    "        thermal_conductivity=100.0,\n",
    "        youngs_modulus=1e9,\n",
    "        poisson_ratio=0.3,\n",
    "        thermal_expansion_coefficient=1e-6,\n",
    "    ),\n",
    "    youngs_modulus=layered(0, \"Pa\"),\n",
    "    poisson_ratio=layered(1, \"1\"),\n",
    "    thermal_expansion_coefficient=layered(2, \"1/K\"),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "heat = HeatConduction(domain=mirror.volume, material=material)\n",
    "operating = Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Operating temperature\",\n",
    "        geometry=mirror,\n",
    "        physics=(heat,),\n",
    "        boundary_conditions=(\n",
    "            FixedTemperature(\n",
    "                boundary=faces.all, physics=heat, value=deposition - cooling\n",
    "            ),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=mesh,\n",
    "    numerics=numerics,\n",
    ").solve_stationary()\n",
    "\n",
    "solid = LinearElasticity(\n",
    "    domain=mirror.volume,\n",
    "    material=material,\n",
    "    thermal_strain=IsotropicThermalExpansion(reference_temperature=deposition),\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Prestressed micromirror\",\n",
    "    geometry=mirror,\n",
    "    physics=(solid,),\n",
    "    boundary_conditions=(\n",
    "        FixedDisplacementComponents(\n",
    "            boundary=faces.x_min,\n",
    "            physics=solid,\n",
    "            components=(\"x\", \"z\"),\n",
    "            where={\"z\": lambda x, y, z: y < 1e-12},\n",
    "        ),\n",
    "        FixedDisplacementComponents(\n",
    "            boundary=faces.y_min, physics=solid, components=(\"y\",)\n",
    "        ),\n",
    "        TractionFree(\n",
    "            boundary=faces.x_max | faces.y_max | faces.z_min | faces.z_max,\n",
    "            physics=solid,\n",
    "        ),\n",
    "    ),\n",
    "    couplings=(\n",
    "        FieldCoupling(\n",
    "            source=operating.field(heat.temperature),\n",
    "            target=solid.temperature,\n",
    "            transfer=FiniteElementEvaluation(),\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "result = Simulation(problem=problem, mesh=mesh, numerics=numerics).solve_stationary()\n",
    "displacement, stress = result.field(solid.displacement), result.field(solid.stress)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The curvature follows from a parabola $w=\\kappa r^2/2$ fitted to the deflection of the mid-plane\n",
    "along the two symmetry lines; the film stress is read in the middle of the film near the centre."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "(Es, nus, alphas), (Ef, nuf, alphaf) = layers[\"plate\"], layers[\"film\"]\n",
    "misfit = (alphaf - alphas) * cooling\n",
    "m, n = film_thickness / plate_thickness, (Ef / (1 - nuf)) / (Es / (1 - nus))\n",
    "bilayer = (\n",
    "    6\n",
    "    * misfit\n",
    "    * (1 + m) ** 2\n",
    "    / (total * (3 * (1 + m) ** 2 + (1 + m * n) * (m**2 + 1 / (m * n))))\n",
    ")\n",
    "stoney = (\n",
    "    6\n",
    "    * (Ef / (1 - nuf) * misfit)\n",
    "    * film_thickness\n",
    "    / (Es / (1 - nus) * plate_thickness**2)\n",
    ")\n",
    "r = np.linspace(0.0, 0.95 * half_side, 40)\n",
    "along_x = displacement.evaluate(\n",
    "    np.column_stack((r, 0 * r, np.full_like(r, plate_thickness / 2)))\n",
    ")[:, 2]\n",
    "along_y = displacement.evaluate(\n",
    "    np.column_stack((0 * r, r, np.full_like(r, plate_thickness / 2)))\n",
    ")[:, 2]\n",
    "curvature = 2 * np.polyfit(np.r_[r, r] ** 2, np.r_[along_x, along_y], 1)[0]\n",
    "film_stress = stress.evaluate(\n",
    "    [[0.1 * half_side, 0.1 * half_side, plate_thickness + film_thickness / 2]]\n",
    ")[0]\n",
    "\n",
    "print(\n",
    "    f\"curvature: simulation {curvature:.3f} 1/m, bilayer formula {bilayer:.3f} 1/m ({100 * (curvature / bilayer - 1):+.2f} %), \"\n",
    "    f\"Stoney {stoney:.3f} 1/m ({100 * (curvature / stoney - 1):+.2f} %)\"\n",
    ")\n",
    "print(\n",
    "    f\"radius of the bowl {1 / curvature * 100:.2f} cm, rise of the mirror corner {1e6 * displacement.evaluate([[half_side, half_side, total]])[0, 2]:.3f} µm\"\n",
    ")\n",
    "print(\n",
    "    f\"film stress near the centre: σ_xx {film_stress[0] / 1e6:.1f} MPa, σ_yy {film_stress[1] / 1e6:.1f} MPa \"\n",
    "    f\"(flat film: {Ef / (1 - nuf) * misfit / 1e6:.1f} MPa, less the share relieved by the bending)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The vertical displacement of the mirror (magnified 50 times), the deflection along the two\n",
    "symmetry lines against the bilayer and the Stoney parabolas, and the stress $\\sigma_{xx}$\n",
    "through the thickness at the centre."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "z = np.linspace(1e-9, total - 1e-9, 60)\n",
    "through = stress.evaluate(\n",
    "    np.column_stack(\n",
    "        (np.full_like(z, 0.1 * half_side), np.full_like(z, 0.1 * half_side), z)\n",
    "    )\n",
    ")[:, 0]\n",
    "fig = plots.figure(1, 3, size=(19, 5.5))\n",
    "plots.surface(\n",
    "    displacement,\n",
    "    component=lambda u, position: 1e6 * u[:, 2],\n",
    "    deformation=displacement,\n",
    "    deformation_scale=50.0,\n",
    "    symmetry={\"planes\": [((1, 0, 0), (0, 0, 0)), ((0, 1, 0), (0, 0, 0))]},\n",
    "    camera=view,\n",
    "    label=\"u_z [µm]\",\n",
    "    title=\"Bowl of the mirror, magnified 50 times\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"along x\": (1e3 * r[::2], 1e6 * along_x[::2]),\n",
    "        \"along y\": (1e3 * r[1::2], 1e6 * along_y[1::2]),\n",
    "    },\n",
    "    reference={\n",
    "        \"bilayer formula\": (1e3 * r, 1e6 * bilayer * r**2 / 2),\n",
    "        \"Stoney\": (1e3 * r, 1e6 * stoney * r**2 / 2),\n",
    "    },\n",
    "    xlabel=\"distance from the centre [mm]\",\n",
    "    ylabel=\"deflection of the mid-plane [µm]\",\n",
    "    title=\"Deflection along the symmetry lines\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (through / 1e6, 1e6 * z)},\n",
    "    hlines={\"film\": 1e6 * plate_thickness},\n",
    "    xlabel=\"σ_xx [MPa]\",\n",
    "    ylabel=\"height above the lower face [µm]\",\n",
    "    title=\"Stress through the thickness\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the film thicker in `prestressed_micromirror_curvature_geometry.py` and write the STEP files\n",
    "again: Stoney's formula drifts away while the bilayer formula follows. Pattern the film into\n",
    "strips to give the mirror a cylindrical instead of a spherical shape."
   ]
  }
 ]
}
