{
 "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": [
    "# Axisymmetric steady conduction in a thick ring\n",
    "\n",
    "A thick-walled ring (bore radius 20 mm, outer radius 100 mm, height 140 mm) is heated over a band\n",
    "of its bore and cooled on its other faces. Everything is symmetric about the axis, so the\n",
    "temperature depends on the radius $r$ and the height $z$ only:\n",
    "\n",
    "$$\\frac{1}{r}\\frac{\\partial}{\\partial r}\\Big(k\\,r\\,\\frac{\\partial T}{\\partial r}\\Big)\n",
    "  +\\frac{\\partial}{\\partial z}\\Big(k\\,\\frac{\\partial T}{\\partial z}\\Big)=0,\\qquad k=52\\ \\mathrm{W/(m\\,K)}.$$\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `heated`: bore $r=20$ mm, $40\\le z\\le100$ mm | heat flux $q=5\\times10^5$ W/m² into the ring |\n",
    "| `bore_below`, `bore_above`: rest of the bore | insulated |\n",
    "| `bottom` $z=0$, `outer` $r=100$ mm, `top` $z=140$ mm | fixed temperature 0 °C (273.15 K) |\n",
    "\n",
    "The flux jumps from zero to its full value at the ends of the heated band, so the temperature\n",
    "has steep gradients there.\n",
    "\n",
    "The ring comes from the CAD file `axisymmetric_ring_steady_conduction.step`, half a solid of\n",
    "revolution; the script `axisymmetric_ring_steady_conduction_geometry.py` builds it with the CAD\n",
    "objects of OneSimulation and names the faces. The model is its meridian plane: $x$ is the radius\n",
    "and $y$ the height.\n",
    "\n",
    "**Reference.** A. D. Cameron, J. A. Casey, G. B. Simpson, *NAFEMS Benchmark Tests for Thermal\n",
    "Analysis (Summary)*, NAFEMS, 1986: the temperature at $r=40$ mm, $z=40$ mm is **332.97 K**\n",
    "(59.82 °C). In addition, the heat leaving through the cooled faces must equal the heat supplied,\n",
    "$q\\cdot2\\pi r_i\\,(z_2-z_1)=3769.9$ W."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, RevolvedH1SpaceFactory\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.heat_transfer import FixedTemperature, HeatConduction, HeatFlux\n",
    "from onesim.results.comparisons import convergence\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the half ring with its named faces; `section` with the plane $y=0$ returns the\n",
    "meridian plane, whose sides keep the names of the faces they were cut from. Three triangular\n",
    "meshes halve the cell size from one to the next and are finer along the heated band."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "ring = load(\"axisymmetric_ring_steady_conduction.step\")\n",
    "faces = ring.boundaries\n",
    "plane = ring.section((0, 1, 0))\n",
    "sides = plane.boundaries\n",
    "sizes = [0.01, 0.005, 0.0025]\n",
    "meshes = [\n",
    "    TriangularMesher(\n",
    "        target_size=size, grading=0.25, local_sizes={\"heated\": size / 3}\n",
    "    ).generate(plane)\n",
    "    for size in sizes\n",
    "]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    ring,\n",
    "    selection={\n",
    "        \"heated band\": faces.heated,\n",
    "        \"insulated bore\": faces.bore_below | faces.bore_above,\n",
    "        \"0 °C\": faces.bottom | faces.outer | faces.top,\n",
    "    },\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=25, azimuth=-150),\n",
    "    title=\"Half ring with its named faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian plane, middle mesh: {meshes[1].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`RevolvedH1SpaceFactory` turns the quadratic Lagrange space of the meridian plane into an\n",
    "axisymmetric one (integration weight $2\\pi r$). A positive `HeatFlux` leaves the body, so the\n",
    "heating enters with a negative sign."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "steel = IsotropicSolid(\n",
    "    density=7850.0,\n",
    "    specific_heat_capacity=460.0,\n",
    "    thermal_conductivity=52.0,\n",
    "    youngs_modulus=2.1e11,\n",
    "    poisson_ratio=0.3,\n",
    "    thermal_expansion_coefficient=1.2e-5,\n",
    ")\n",
    "model = HeatConduction(domain=plane.domain(), material=steel, heating=0.0)\n",
    "problem = Problem(\n",
    "    name=\"Axisymmetric ring\",\n",
    "    geometry=plane,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedTemperature(\n",
    "            boundary=sides.bottom | sides.outer | sides.top, physics=model, value=273.15\n",
    "        ),\n",
    "        HeatFlux(boundary=sides.heated, physics=model, value=-5e5),\n",
    "        HeatFlux(\n",
    "            boundary=sides.bore_below | sides.bore_above, physics=model, value=0.0\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2), provider=RevolvedH1SpaceFactory()),\n",
    "    linear_solver=SparseDirect(),\n",
    ")\n",
    "fields = [\n",
    "    Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "    .solve_stationary()\n",
    "    .field(model.temperature)\n",
    "    for mesh in meshes\n",
    "]\n",
    "field = fields[-1]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The temperature at the benchmark point on each mesh with the Richardson estimate, and the heat\n",
    "balance of the whole ring."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "target = [float(f.evaluate([[0.04, 0.04]])[0]) for f in fields]\n",
    "study = convergence(target, sizes)\n",
    "supplied = 5e5 * 2 * np.pi * 0.02 * 0.06\n",
    "print(\"mesh size [mm]   triangles   T(40 mm, 40 mm) [K]   deviation from 332.97 K\")\n",
    "for size, mesh, value in zip(sizes, meshes, target):\n",
    "    print(\n",
    "        f\"{1e3 * size:14.1f} {mesh.cell_count:11d} {value:21.4f} {value - 332.97:+16.4f} K\"\n",
    "    )\n",
    "print(\n",
    "    f\"observed order {study.order:.2f}, Richardson estimate {study.extrapolated:.4f} K\"\n",
    ")\n",
    "print(\n",
    "    f\"heat supplied {supplied:.2f} W, heat entering at the band {-field.boundary_flux(sides.heated):.2f} W, \"\n",
    "    f\"heat leaving through the cooled faces {field.boundary_flux(sides.bottom | sides.outer | sides.top):.2f} W\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The temperature in the meridian plane, the temperature along the bore and along the line\n",
    "$z=40$ mm through the benchmark point, and the mesh study."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "z = np.linspace(0, 0.14, 281)\n",
    "r = np.linspace(0.02, 0.1, 161)\n",
    "fig = plots.figure(1, 3, size=(19, 6))\n",
    "plots.surface(\n",
    "    field,\n",
    "    component=lambda T, position: T - 273.15,\n",
    "    limits=(0, 210),\n",
    "    contours=15,\n",
    "    subdivisions=3,\n",
    "    xlabel=\"radius r [m]\",\n",
    "    ylabel=\"height z [m]\",\n",
    "    label=\"T [°C]\",\n",
    "    title=\"Temperature in the meridian plane\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        \"along the bore r = 20 mm, over z\": (\n",
    "            1e3 * z,\n",
    "            field.evaluate(np.column_stack((np.full_like(z, 0.02), z))).ravel()\n",
    "            - 273.15,\n",
    "        ),\n",
    "        \"along z = 40 mm, over r\": (\n",
    "            1e3 * r,\n",
    "            field.evaluate(np.column_stack((r, np.full_like(r, 0.04)))).ravel()\n",
    "            - 273.15,\n",
    "        ),\n",
    "    },\n",
    "    points={\"NAFEMS target 59.82 °C\": ([40.0], [59.82])},\n",
    "    vlines={\"ends of the heated band\": 40.0, \"\": 100.0},\n",
    "    xlabel=\"z or r [mm]\",\n",
    "    ylabel=\"T [°C]\",\n",
    "    title=\"Temperature along two lines\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        \"quadratic triangles\": (\n",
    "            1e3 * np.array(sizes),\n",
    "            [value - 332.97 for value in target],\n",
    "        )\n",
    "    },\n",
    "    hlines={\n",
    "        \"NAFEMS target\": 0.0,\n",
    "        f\"Richardson estimate {study.extrapolated:.3f} K\": study.extrapolated - 332.97,\n",
    "    },\n",
    "    markers=True,\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"mesh size [mm]\",\n",
    "    ylabel=\"T(40 mm, 40 mm) - 332.97 K [K]\",\n",
    "    title=\"Mesh study at the benchmark point\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Move or widen the heated band in `axisymmetric_ring_steady_conduction_geometry.py` and write the\n",
    "STEP file again, or replace the fixed outer temperature by a convective condition\n",
    "(`ConvectiveHeatFlux`) and watch the whole ring warm up."
   ]
  }
 ]
}
