{
 "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 transient heating of a cylinder\n",
    "\n",
    "A solid steel cylinder, 0.3 m in radius and 0.4 m high, is at 0 °C. At $t=0$ its whole surface\n",
    "is brought to 1000 °C and held there. Heat diffuses inwards; the temperature depends on the\n",
    "radius $r$ and the height $z$:\n",
    "\n",
    "$$\\rho c_p\\,\\frac{\\partial T}{\\partial t}=\\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),$$\n",
    "\n",
    "with $k=52$ W/(m K), $\\rho=7850$ kg/m³ and $c_p=460$ J/(kg K).\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `bottom` $z=0$, `outer` $r=0.3$ m, `top` $z=0.4$ m | $T=1000$ °C for $t>0$ |\n",
    "| axis $r=0$ | symmetry |\n",
    "| initial state | $T=0$ °C |\n",
    "\n",
    "The cylinder comes from the CAD file `axisymmetric_cylinder_transient_heating.step`, half a solid\n",
    "of revolution; the script `axisymmetric_cylinder_transient_heating_geometry.py` builds it with the\n",
    "CAD objects of OneSimulation. The model is its meridian plane ($x$ the radius, $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: **186.5 °C** at $r=0.1$ m, $z=0.3$ m after 190 s. The\n",
    "finite cylinder with a uniform surface temperature also has an exact solution, the product of\n",
    "the solutions for an infinite cylinder and an infinite slab (Carslaw and Jaeger, *Conduction of\n",
    "Heat in Solids*, 1959):\n",
    "\n",
    "$$\\frac{T_s-T}{T_s-T_0}=\\sum_n\\frac{2\\,J_0(\\lambda_n r/R)}{\\lambda_n J_1(\\lambda_n)}e^{-\\lambda_n^2\\alpha t/R^2}\n",
    "  \\cdot\\sum_{m\\ \\mathrm{odd}}\\frac{4}{m\\pi}\\sin\\frac{m\\pi z}{H}\\,e^{-(m\\pi/H)^2\\alpha t},$$\n",
    "\n",
    "where $\\lambda_n$ are the roots of $J_0$ and $\\alpha=k/(\\rho c_p)$."
   ]
  },
  {
   "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.numerics.time import BDF, BackwardEuler\n",
    "from onesim.physics.heat_transfer import FixedTemperature, HeatConduction, HeatFlux\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.special import j0, j1, jn_zeros\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the half cylinder with its named faces; `section` with the plane $y=0$ returns the\n",
    "meridian plane. Its side on the axis is cut from the flat face `start` of the half solid. The\n",
    "triangles are 2 cm in size and shrink to 7 mm along the heated faces, where the temperature\n",
    "changes fastest after the jump."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "cylinder = load(\"axisymmetric_cylinder_transient_heating.step\")\n",
    "faces = cylinder.boundaries\n",
    "plane = cylinder.section((0, 1, 0))\n",
    "sides = plane.boundaries\n",
    "radius, height = plane.size[:2]\n",
    "mesh = TriangularMesher(\n",
    "    target_size=0.02,\n",
    "    grading=0.25,\n",
    "    local_sizes={\"bottom\": 0.007, \"outer\": 0.007, \"top\": 0.007},\n",
    ").generate(plane)\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    cylinder,\n",
    "    selection={\"heated to 1000 °C\": faces.bottom | faces.outer | faces.top},\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=25, azimuth=-150),\n",
    "    title=\"Half cylinder with its heated faces\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    title=f\"Meridian plane: {mesh.cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Quadratic axisymmetric elements (`RevolvedH1SpaceFactory`) and the second-order BDF integrator\n",
    "with 100 steps of 1.9 s; the first step is a backward Euler step."
   ]
  },
  {
   "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 transient heating\",\n",
    "    geometry=plane,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedTemperature(\n",
    "            boundary=sides.bottom | sides.outer | sides.top, physics=model, value=1000.0\n",
    "        ),\n",
    "        HeatFlux(boundary=sides.start, physics=model, value=0.0),\n",
    "    ),\n",
    "    initial_conditions=(InitialValue(model.temperature, 0.0),),\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2), provider=RevolvedH1SpaceFactory()),\n",
    "    linear_solver=SparseDirect(),\n",
    "    time_integrator=BDF(order=2, startup=BackwardEuler()),\n",
    ")\n",
    "temperature = (\n",
    "    Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "    .run(start_time=0.0, end_time=190.0, time_step=1.9)\n",
    "    .field(model.temperature)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The temperature at the benchmark point against the NAFEMS value and the exact product solution,\n",
    "at several times."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "diffusivity = steel.thermal_conductivity / (\n",
    "    steel.density * steel.specific_heat_capacity\n",
    ")\n",
    "roots, odd = jn_zeros(0, 200), np.arange(1, 800, 2)\n",
    "exact = lambda r, z, t: 1000.0 * (\n",
    "    1\n",
    "    - np.sum(\n",
    "        2\n",
    "        * j0(np.outer(r, roots) / radius)\n",
    "        / (roots * j1(roots))\n",
    "        * np.exp(-(roots**2) * diffusivity * t / radius**2),\n",
    "        axis=1,\n",
    "    )\n",
    "    * np.sum(\n",
    "        4\n",
    "        / (odd * np.pi)\n",
    "        * np.sin(np.outer(z, odd) * np.pi / height)\n",
    "        * np.exp(-((odd * np.pi / height) ** 2) * diffusivity * t),\n",
    "        axis=1,\n",
    "    )\n",
    ")\n",
    "times, history = temperature.time_series([[0.1, 0.3]])\n",
    "history = history.ravel()\n",
    "print(\"time [s]   simulation [°C]   exact [°C]   deviation [K]\")\n",
    "for index in (10, 25, 50, 75, 100):\n",
    "    print(\n",
    "        f\"{times[index]:8.1f} {history[index]:17.3f} {exact([0.1], [0.3], times[index])[0]:12.3f} \"\n",
    "        f\"{history[index] - exact([0.1], [0.3], times[index])[0]:+14.3f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"at 190 s: simulation {history[-1]:.2f} °C, NAFEMS 186.5 °C ({history[-1] - 186.5:+.2f} K), \"\n",
    "    f\"exact {exact([0.1], [0.3], 190.0)[0]:.2f} °C\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The temperature in the meridian plane after 190 s, the heating history at the benchmark point,\n",
    "and the temperature along the radius $z=0.3$ m at three times."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "r = np.linspace(0, radius, 121)\n",
    "fig = plots.figure(1, 3, size=(19, 6))\n",
    "plots.surface(\n",
    "    temperature,\n",
    "    time=190.0,\n",
    "    limits=(0, 1000),\n",
    "    contours=11,\n",
    "    subdivisions=3,\n",
    "    xlabel=\"radius r [m]\",\n",
    "    ylabel=\"height z [m]\",\n",
    "    label=\"T [°C]\",\n",
    "    title=\"Temperature after 190 s\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"simulation\": (times[::4], history[::4])},\n",
    "    reference={\n",
    "        \"exact product solution\": (\n",
    "            times[1:],\n",
    "            exact([0.1], [0.3], times[1:, None]).ravel(),\n",
    "        )\n",
    "    },\n",
    "    hlines={\"NAFEMS 186.5 °C at 190 s\": 186.5},\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"T at r = 0.1 m, z = 0.3 m [°C]\",\n",
    "    title=\"Heating of the benchmark point\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"t = {t:.0f} s\": (\n",
    "            r,\n",
    "            temperature.evaluate(\n",
    "                np.column_stack((r, np.full_like(r, 0.3))), time=t\n",
    "            ).ravel(),\n",
    "        )\n",
    "        for t in (38.0, 95.0, 190.0)\n",
    "    },\n",
    "    reference={\n",
    "        f\"t = {t:.0f} s\": (r, exact(r, np.full_like(r, 0.3), t))\n",
    "        for t in (38.0, 95.0, 190.0)\n",
    "    },\n",
    "    xlabel=\"radius r [m]\",\n",
    "    ylabel=\"T [°C]\",\n",
    "    title=\"Along z = 0.3 m (exact solution underneath)\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "After 190 s, switch the surface to insulated and follow how the temperature evens out; the mean\n",
    "temperature then stays constant, a check of the energy balance. Or change the cylinder in\n",
    "`axisymmetric_cylinder_transient_heating_geometry.py` and write the STEP file again."
   ]
  }
 ]
}
