{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# How quickly does heat reach the centre of an ore pellet?\n",
    "\n",
    "Hot gas at 95 °C flows over initially uniform magnetite pellets at 25 °C.\n",
    "Compare two radii, 2.5 and 5 mm, over the first ten seconds of heating.\n",
    "Constant properties and a uniform film coefficient preserve spherical symmetry.\n",
    "The only spatial coordinate is radius. The spherical finite element space supplies\n",
    "the volume measure $4\\pi r^2\\,dr$ and the outer surface area.\n",
    "\n",
    "At the centre the flux vanishes by symmetry. At the surface, heat enters at\n",
    "$q=h(T_g-T_s)$ with $h=1000$ W/(m² K). The model covers sensible heating\n",
    "before drying or oxidation changes the pellet properties."
   ],
   "id": "e6a81276ac44"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d1 import Line\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import StructuredLineMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, SphericalLineH1SpaceFactory\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.time import BDF, BackwardEuler\n",
    "from onesim.physics.heat_transfer import ConvectiveHeatFlux, 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.optimize import brentq\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "c78657435057"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Resolve each pellet on two radial meshes\n",
    "\n",
    "The thermal inputs are density 2000 kg/m³, specific heat 300 J/(kg K)\n",
    "and conductivity 0.5 W/(m K). Compare 20 and 64 quadratic radial elements with the same time step."
   ],
   "id": "564c65b70a6e"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "density, capacity, conductivity = 2000.0, 300.0, 0.5\n",
    "initial, gas, film = 298.15, 368.15, 1000.0\n",
    "ore = IsotropicSolid(\n",
    "    density=density,\n",
    "    specific_heat_capacity=capacity,\n",
    "    thermal_conductivity=conductivity,\n",
    "    youngs_modulus=1e9,\n",
    "    poisson_ratio=0.25,\n",
    "    thermal_expansion_coefficient=0,\n",
    ")\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2), provider=SphericalLineH1SpaceFactory()),\n",
    "    time_integrator=BDF(order=2, startup=BackwardEuler()),\n",
    "    linear_solver=SparseDirect(),\n",
    ")\n",
    "temperature = {}\n",
    "for radius in (0.0025, 0.005):\n",
    "    line = Line(start=(0, 0, 0), end=(radius, 0, 0))\n",
    "    heat = HeatConduction(domain=line.line, material=ore)\n",
    "    surface = ConvectiveHeatFlux(\n",
    "        physics=heat,\n",
    "        boundary=line.boundaries.end,\n",
    "        heat_transfer_coefficient=film,\n",
    "        ambient_temperature=gas,\n",
    "    )\n",
    "    symmetry = HeatFlux(physics=heat, boundary=line.boundaries.start, value=0)\n",
    "    problem = Problem(\n",
    "        name=\"Pellet heating\",\n",
    "        geometry=line,\n",
    "        physics=(heat,),\n",
    "        boundary_conditions=(surface, symmetry),\n",
    "        initial_conditions=(InitialValue(heat.temperature, initial),),\n",
    "    )\n",
    "    histories = {}\n",
    "    for cells in (20, 64):\n",
    "        mesh = StructuredLineMesher(cells=cells).generate(line)\n",
    "        field = (\n",
    "            Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "            .run(\n",
    "                start_time=0,\n",
    "                end_time=10,\n",
    "                time_step=0.05,\n",
    "            )\n",
    "            .field(heat.temperature)\n",
    "        )\n",
    "        histories[cells] = field\n",
    "        print(f\"{radius * 1000:g} mm pellet: {mesh.cell_count} elements, {len(field.space.dof_coordinates)} temperature nodes\")\n",
    "    temperature[radius] = histories[64]\n",
    "    coarse = histories[20].time_series(points=[(0, 0, 0)])[1]\n",
    "    fine = histories[64].time_series(points=[(0, 0, 0)])[1]\n",
    "    print(f\"Maximum centre-temperature change on refinement: {np.max(np.abs(fine - coarse)):.5f} K\")"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "c6cf9dbb26ce"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Check the centre temperature\n",
    "\n",
    "The exact convective sphere solution has eigenvalues satisfying\n",
    "$\\lambda\\cot\\lambda=1-\\mathrm{Bi}$, where $\\mathrm{Bi}=hR/k$.\n",
    "At the centre its modes decay as $\\exp(-\\lambda^2\\alpha t/R^2)$.\n",
    "Use the first twenty terms after 0.5 s, when the higher modes have decayed.\n",
    "Reference: H. S. Carslaw and J. C. Jaeger, *Conduction of Heat in Solids*, 2nd ed. (1959)."
   ],
   "id": "979484fad56e"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "centre, reference = {}, {}\n",
    "for radius, field in temperature.items():\n",
    "    biot = film * radius / conductivity\n",
    "    modes = np.array(\n",
    "        [\n",
    "            brentq(\n",
    "                lambda x: x * np.cos(x) + (biot - 1) * np.sin(x), (n + 0.5) * np.pi, (n + 1) * np.pi\n",
    "            )\n",
    "            for n in range(20)\n",
    "        ]\n",
    "    )\n",
    "    amplitudes = 4 * (np.sin(modes) - modes * np.cos(modes)) / (2 * modes - np.sin(2 * modes))\n",
    "    times, values = field.time_series(points=[(0, 0, 0)])\n",
    "    selected = times >= 0.5\n",
    "    decay = conductivity / (density * capacity) * (modes / radius) ** 2\n",
    "    exact = gas + (initial - gas) * (np.exp(-np.outer(times[selected], decay)) @ amplitudes)\n",
    "    key = f\"{1000 * radius:g} mm\"\n",
    "    centre[key] = (times[::5], values[::5] - 273.15)\n",
    "    reference[key] = (times[selected], exact - 273.15)\n",
    "    print(\n",
    "        f\"{key}: centre at 10 s = {values[-1] - 273.15:.2f} °C; \"\n",
    "        f\"largest centre error from 0.5 to 10 s = {np.max(np.abs(values[selected] - exact)):.3f} K\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "1e2cedb26a76"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Inside the larger pellet\n",
    "\n",
    "The surface responds first. Compare its radial temperature gradients with the\n",
    "centre histories of both pellets. The points in the right panel are finite element results."
   ],
   "id": "58ab2b17f99b"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "r = np.linspace(0, 0.005, 61)\n",
    "points = np.column_stack((r, 0 * r, 0 * r))\n",
    "profiles = {\n",
    "    f\"{t:g} s\": (1000 * r, temperature[0.005].evaluate(points, time=t) - 273.15)\n",
    "    for t in (0.5, 2, 5, 10)\n",
    "}\n",
    "fig = plots.figure(1, 2, size=(13, 4.8))\n",
    "plots.line(\n",
    "    y=profiles,\n",
    "    xlabel=\"Radius [mm]\",\n",
    "    ylabel=\"Temperature [°C]\",\n",
    "    title=\"From surface to centre · 5 mm pellet\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points=centre,\n",
    "    reference=reference,\n",
    "    xlabel=\"Time [s]\",\n",
    "    ylabel=\"Centre temperature [°C]\",\n",
    "    title=\"Effect of pellet radius\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "642066682495"
  }
 ]
}
