{
 "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 turbine stator blade\n",
    "\n",
    "The stator vanes of a gas turbine turn the hot gas from the combustor onto the rotor. The gas\n",
    "is far hotter than the alloy can bear, so the vanes are cooled from inside: air taken from the\n",
    "compressor flows through radial channels and leaves the vane cooler than the gas around it. The\n",
    "price is a steep temperature gradient through the walls, and with it **thermal stress**, which\n",
    "together with creep limits the life of the part.\n",
    "\n",
    "The vane has a cambered airfoil of 60 mm chord and 50 mm span between an inner and an outer\n",
    "platform, with three cooling channels. It comes from the CAD file\n",
    "`turbine_stator_blade_thermal_stress.step` with five named face groups; the script\n",
    "`turbine_stator_blade_thermal_stress_geometry.py` builds it with the CAD objects of\n",
    "OneSimulation.\n",
    "\n",
    "| face | heat transfer | mechanics |\n",
    "|---|---|---|\n",
    "| `airfoil` | hot gas, $h=1200$ W/(m² K), $T=1250$ K | free |\n",
    "| `gas_platforms`: platform faces in the gas path | hot gas, $h=800$ W/(m² K), $T=1250$ K | free |\n",
    "| `channels` | cooling air, $h=1500$ W/(m² K), $T=700$ K | free |\n",
    "| `inner_back`, `outer_back` | plenum air, $h=300$ W/(m² K), $T=750$ K | `outer_back` seated on a flat face: $u_z=0$, held in its plane at two corners |\n",
    "| platform edges | insulated | free |\n",
    "\n",
    "Steady heat conduction $\\nabla\\cdot(k\\nabla T)=0$ with these convective conditions gives the\n",
    "temperature field; it enters linear elasticity as the thermal strain\n",
    "$\\boldsymbol\\varepsilon_{th}=\\alpha\\,(T-T_0)\\,\\mathbf I$, stress free at $T_0=293$ K.\n",
    "\n",
    "**Reference.** The heat taken in from the gas must leave through the channels and the\n",
    "platform backs (energy balance). The vane is held on one face only, so a purely thermal load\n",
    "must produce no net force there. The peak temperature and the peak stress on the channel walls\n",
    "have no closed form; a mesh study on three meshes with Richardson extrapolation shows how far\n",
    "they are converged. Near the seat the stress depends on the details of the support, so the\n",
    "stress study takes the channel walls between 10 and 40 mm span, and as their peak the value that\n",
    "99.9 % of the wall samples stay below: a single sample in a distorted cell then does not decide it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\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 AlgebraicMultigrid, ConjugateGradient\n",
    "from onesim.physics.heat_transfer import ConvectiveHeatFlux, HeatConduction, HeatFlux\n",
    "from onesim.physics.solid_mechanics import (\n",
    "    FixedDisplacementComponents,\n",
    "    IsotropicThermalExpansion,\n",
    "    LinearElasticity,\n",
    "    TractionFree,\n",
    ")\n",
    "from onesim.results.comparisons import convergence\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 vane with its named face groups. On this part the cell size is set by the\n",
    "curved faces: the mesher lets a cell turn by at most `curvature_angle` on the airfoil and in the\n",
    "channels, so the cells there scale with that angle. Three meshes with decreasing angles form\n",
    "the mesh study; `with_order` gives them quadratic edges that follow the curved faces."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "vane = load(\"turbine_stator_blade_thermal_stress.step\")\n",
    "faces = vane.boundaries\n",
    "edges = (\n",
    "    faces.all\n",
    "    - faces.airfoil\n",
    "    - faces.gas_platforms\n",
    "    - faces.channels\n",
    "    - faces.inner_back\n",
    "    - faces.outer_back\n",
    ")\n",
    "angles = [0.6, 0.45, 0.35]\n",
    "meshes = [\n",
    "    with_order(\n",
    "        TetrahedralMesher(target_size=0.006, curvature_angle=angle).generate(vane), 2\n",
    "    )\n",
    "    for angle in angles\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=32, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(15, 6.5))\n",
    "plots.geometry(\n",
    "    vane,\n",
    "    selection={\n",
    "        \"airfoil\": faces.airfoil,\n",
    "        \"cooling channels\": faces.channels,\n",
    "        \"gas-side platforms\": faces.gas_platforms,\n",
    "        \"seated face\": faces.outer_back,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Stator vane 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": [
    "## Model\n",
    "\n",
    "A nickel-base superalloy with properties at service temperature. Both problems are symmetric\n",
    "and positive definite: conjugate gradients with algebraic multigrid solve them, for the\n",
    "mechanics with the six rigid-body motions as the coarse space of the multigrid."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "alloy = IsotropicSolid(\n",
    "    density=8100.0,\n",
    "    specific_heat_capacity=600.0,\n",
    "    thermal_conductivity=20.0,\n",
    "    youngs_modulus=170e9,\n",
    "    poisson_ratio=0.30,\n",
    "    thermal_expansion_coefficient=14e-6,\n",
    ")\n",
    "films = {\n",
    "    \"airfoil\": (1200.0, 1250.0),\n",
    "    \"gas_platforms\": (800.0, 1250.0),\n",
    "    \"channels\": (1500.0, 700.0),\n",
    "    \"inner_back\": (300.0, 750.0),\n",
    "    \"outer_back\": (300.0, 750.0),\n",
    "}\n",
    "heat = HeatConduction(domain=vane.volume, material=alloy, heating=0.0)\n",
    "thermal = Problem(\n",
    "    name=\"Vane temperature\",\n",
    "    geometry=vane,\n",
    "    physics=(heat,),\n",
    "    boundary_conditions=(\n",
    "        *(\n",
    "            ConvectiveHeatFlux(\n",
    "                boundary=getattr(faces, name),\n",
    "                physics=heat,\n",
    "                heat_transfer_coefficient=h,\n",
    "                ambient_temperature=T,\n",
    "            )\n",
    "            for name, (h, T) in films.items()\n",
    "        ),\n",
    "        HeatFlux(boundary=edges, physics=heat, value=0.0),\n",
    "    ),\n",
    ")\n",
    "solid = LinearElasticity(\n",
    "    domain=vane.volume,\n",
    "    material=alloy,\n",
    "    thermal_strain=IsotropicThermalExpansion(reference_temperature=293.15),\n",
    ")\n",
    "heat_numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=ConjugateGradient(\n",
    "        preconditioner=AlgebraicMultigrid(), relative_tolerance=1e-10\n",
    "    ),\n",
    ")\n",
    "solid_numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)),\n",
    "    linear_solver=ConjugateGradient(\n",
    "        preconditioner=AlgebraicMultigrid(near_nullspace=solid.rigid_body_modes),\n",
    "        relative_tolerance=1e-10,\n",
    "    ),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Temperature and thermal stress on three meshes\n",
    "\n",
    "On each mesh the temperature is computed first; it becomes the thermal strain of the elastic\n",
    "model on the same mesh. The peak temperature on the airfoil and the peak von Mises stress on\n",
    "the channel walls are kept for the mesh study, the fields of the finest mesh for the figures."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "peak_temperature, peak_stress = [], []\n",
    "for mesh in meshes:\n",
    "    temperature = (\n",
    "        Simulation(problem=thermal, mesh=mesh, numerics=heat_numerics)\n",
    "        .solve_stationary()\n",
    "        .field(heat.temperature)\n",
    "    )\n",
    "    result = Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"Vane thermal stress\",\n",
    "            geometry=vane,\n",
    "            physics=(solid,),\n",
    "            boundary_conditions=(\n",
    "                FixedDisplacementComponents(\n",
    "                    boundary=faces.outer_back,\n",
    "                    physics=solid,\n",
    "                    components=(\"x\", \"y\", \"z\"),\n",
    "                    where={\n",
    "                        \"x\": lambda x, y, z: np.hypot(x + 0.010, y + 0.020) < 1e-6,\n",
    "                        \"y\": lambda x, y, z: (np.abs(y + 0.020) < 1e-6)\n",
    "                        & ((np.abs(x + 0.010) < 1e-6) | (np.abs(x - 0.070) < 1e-6)),\n",
    "                    },\n",
    "                ),\n",
    "                TractionFree(boundary=faces.all - faces.outer_back, physics=solid),\n",
    "            ),\n",
    "            couplings=(\n",
    "                FieldCoupling(\n",
    "                    source=temperature,\n",
    "                    target=solid.temperature,\n",
    "                    transfer=FiniteElementEvaluation(),\n",
    "                ),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=mesh,\n",
    "        numerics=solid_numerics,\n",
    "    ).solve_stationary()\n",
    "    walls = result.field(solid.von_mises_stress).sample(\n",
    "        along=faces.channels, subdivisions=3\n",
    "    )\n",
    "    peak_temperature.append(\n",
    "        temperature.sample(along=faces.airfoil, subdivisions=3).values.max()\n",
    "    )\n",
    "    peak_stress.append(\n",
    "        np.percentile(walls.values[np.abs(walls.positions[:, 2] - 0.025) < 0.015], 99.9)\n",
    "    )\n",
    "displacement, mises = result.field(solid.displacement), result.field(\n",
    "    solid.von_mises_stress\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The heat flows through every group of faces and the reaction on the seated face on the finest\n",
    "mesh, and the mesh study: the curvature angle stands for the cell size on the curved faces. An\n",
    "observed order well below that of quadratic elements means the levels are not yet in the\n",
    "asymptotic range; the change between the two finest meshes is then the honest error estimate,\n",
    "not the Richardson value."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "flows = {name: -temperature.boundary_flux(getattr(faces, name)) for name in films}\n",
    "studies = {\n",
    "    \"temperature\": convergence(peak_temperature, angles),\n",
    "    \"stress\": convergence(peak_stress, angles),\n",
    "}\n",
    "reaction = displacement.reaction(faces.outer_back)\n",
    "\n",
    "for name, flow in flows.items():\n",
    "    print(f\"heat flow into the vane through {name:14s} {flow:9.1f} W\")\n",
    "print(\n",
    "    f\"energy balance: in {sum(f for f in flows.values() if f > 0):.1f} W, out {-sum(f for f in flows.values() if f < 0):.1f} W, \"\n",
    "    f\"imbalance {abs(sum(flows.values())) / sum(f for f in flows.values() if f > 0):.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"reaction on the seated face: ({reaction[0]:.2f}, {reaction[1]:.2f}, {reaction[2]:.2f}) N\"\n",
    ")\n",
    "print(\n",
    "    \"curvature angle [rad]  tetrahedra  peak temperature [K]  peak von Mises (99.9 %), channel walls 10-40 mm [MPa]\"\n",
    ")\n",
    "for angle, mesh, T, s in zip(angles, meshes, peak_temperature, peak_stress):\n",
    "    print(f\"{angle:21.2f} {mesh.cell_count:11d} {T:20.3f} {s / 1e6:30.1f}\")\n",
    "for name, study in studies.items():\n",
    "    scale, unit = (1.0, \"K\") if name == \"temperature\" else (1e-6, \"MPa\")\n",
    "    print(\n",
    "        f\"peak {name}: change between the two finest meshes {100 * study.change:.3f} %, \"\n",
    "        + (\n",
    "            f\"observed order {study.order:.2f}, Richardson value {study.extrapolated * scale:.1f} {unit}\"\n",
    "            if study.extrapolated is not None\n",
    "            else study.reason\n",
    "        )\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The temperature on the vane surface and across the mid-span section, the von Mises stress on\n",
    "the deformed vane (displacement magnified 5 times) and across the same section."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "megapascal = lambda s, position: s / 1e6\n",
    "mid_span = Plane(origin=(0, 0, 0.025), normal=(0, 0, 1))\n",
    "fig = plots.figure(2, 2, size=(16, 12))\n",
    "plots.surface(\n",
    "    temperature,\n",
    "    camera=view,\n",
    "    limits=(900, 1210),\n",
    "    label=\"T [K]\",\n",
    "    title=\"Surface temperature\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.section(\n",
    "    temperature,\n",
    "    plane=mid_span,\n",
    "    subdivisions=3,\n",
    "    contours=12,\n",
    "    limits=(900, 1210),\n",
    "    label=\"T [K]\",\n",
    "    title=\"Temperature at mid-span\",\n",
    "    xlimits=(-0.004, 0.064),\n",
    "    ylimits=(-0.012, 0.022),\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.surface(\n",
    "    mises,\n",
    "    component=megapascal,\n",
    "    deformation=displacement,\n",
    "    deformation_scale=5.0,\n",
    "    limits=(0, 400),\n",
    "    camera=view,\n",
    "    label=\"von Mises stress [MPa]\",\n",
    "    title=\"Thermal stress on the deformed vane (×5)\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.section(\n",
    "    mises,\n",
    "    plane=mid_span,\n",
    "    component=megapascal,\n",
    "    limits=(0, 400),\n",
    "    subdivisions=3,\n",
    "    label=\"von Mises stress [MPa]\",\n",
    "    title=\"Thermal stress at mid-span\",\n",
    "    xlimits=(-0.004, 0.064),\n",
    "    ylimits=(-0.012, 0.022),\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Move or enlarge the cooling channels in `turbine_stator_blade_thermal_stress_geometry.py`,\n",
    "write the STEP file again and compare peak temperature and stress; or add a thermal barrier\n",
    "coating on the airfoil as a second material region and see how much it lowers the metal\n",
    "temperature."
   ]
  }
 ]
}
