{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "heat_conduction_finite_slab-1",
   "source": [
    "# Cooling a finite slab from both faces\n",
    "\n",
    "A hot slab touches two cold surfaces at once. How long does the core stay warm? The coordinate $x$ runs from −1 to 1 in units of the half-thickness $b$. Temperature $\\\\theta=(T-T_s)/(T_i-T_s)$ starts at one. Time is measured by the Fourier number $\\\\tau=\\\\alpha t/b^2$, giving $\\\\partial_\\\\tau\\\\theta=\\\\partial_x^2\\\\theta$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "heat_conduction_finite_slab-2",
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d1 import Line\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import NonuniformLineMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.numerics.time import AdaptiveTimeStep, BackwardEuler, BDF\n",
    "from onesim.physics.heat_transfer import FixedTemperature, HeatConduction\n",
    "from onesim.simulation import Problem, Simulation, smooth_step\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "heat_conduction_finite_slab-3",
   "source": [
    "## Cooling through the faces\n",
    "\n",
    "A smooth step lowers both boundary temperatures from one to zero over the first $2\\\\times10^{-6}$ units of time. The line elements are shorter near the surfaces, where the early temperature gradients are steepest. Adaptive BDF2 steps follow the cooling transient."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "heat_conduction_finite_slab-4",
   "source": [
    "slab = Line(start=(-1, 0, 0), end=(1, 0, 0))\n",
    "solid = IsotropicSolid(density=1, specific_heat_capacity=1, thermal_conductivity=1,\n",
    "                       youngs_modulus=1, poisson_ratio=0.3, thermal_expansion_coefficient=0)\n",
    "heat = HeatConduction(domain=slab.line, material=solid)\n",
    "wall = smooth_step(0, 2e-6, low=1, high=0)\n",
    "problem = Problem(name=\"Slab cooling\", geometry=slab, physics=(heat,),\n",
    "    initial_conditions=(InitialValue(heat.temperature, 1),),\n",
    "    boundary_conditions=tuple(FixedTemperature(physics=heat, boundary=face, value=wall)\n",
    "                              for face in (slab.boundaries.start, slab.boundaries.end)))\n",
    "method = Numerics(spatial=FiniteElement(element=Lagrange(order=1)),\n",
    "                  time_integrator=BDF(order=2, startup=BackwardEuler()), linear_solver=SparseDirect())"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "heat_conduction_finite_slab-5",
   "source": [
    "## Check the full temperature profile\n",
    "\n",
    "For an instantaneous change at both faces, Bird, Stewart and Lightfoot give the exact cosine series in *Transport Phenomena*, 2nd ed., Eq. 12.1-31. Its modes have wave numbers $q_n=(n+\\\\tfrac12)\\\\pi$ and decay at rates $q_n^2$. Compare the profiles at six times on three meshes, using the relative $L^2$ error over the whole slab."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "heat_conduction_finite_slab-6",
   "source": [
    "times = np.array([0.01, 0.04, 0.1, 0.2, 0.4, 0.6])\n",
    "x = np.linspace(-1, 1, 201)\n",
    "probes = np.column_stack((x, np.zeros((len(x), 2))))\n",
    "n = np.arange(50)\n",
    "q = (n + 0.5) * np.pi\n",
    "modes = (2 * (-1.)**n / q)[:, None] * np.cos(q[:, None] * x)\n",
    "reference = np.exp(-times[:, None] * q**2) @ modes\n",
    "errors = {}\n",
    "for cells in (64, 128, 512):\n",
    "    faces = 1 - np.cos(np.linspace(0, np.pi, cells + 1))\n",
    "    mesh = NonuniformLineMesher(arclength_faces=tuple(faces)).generate(slab)\n",
    "    steps = AdaptiveTimeStep(initial=2e-7, minimum=1e-10, maximum=0.005,\n",
    "                             relative_tolerance=0, absolute_tolerance=0.00002 * 64 / cells)\n",
    "    result = Simulation(problem=problem, mesh=mesh, numerics=method).run(start_time=0, end_time=0.6, time_step=steps)\n",
    "    history = result.field(heat.temperature).time_interpolant()\n",
    "    profile = np.array([history(probes, t) for t in times])\n",
    "    errors[cells] = np.linalg.norm(profile-reference, axis=1) / np.linalg.norm(reference, axis=1)\n",
    "    print(f\"{len(mesh.faces)} nodes, {cells} cells: maximum relative profile error {errors[cells].max():.3%}\")\n",
    "print(f\"Core at τ = 0.6: computed {profile[-1, len(x)//2]:.5f}, series {reference[-1, len(x)//2]:.5f}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "heat_conduction_finite_slab-7",
   "source": [
    "fig = plots.figure(1, 2, size=(11.5, 4.8))\n",
    "plots.line(x, {f\"τ = {t:g}\": row for t, row in zip(times, profile)},\n",
    "           title=\"Cooling moves inward\", xlabel=\"Position / half-thickness\", ylabel=\"Reduced temperature\", legend=\"lower center\", ax=fig[0])\n",
    "plots.line(times, {f\"{cells} cells\": 100*error for cells, error in errors.items()}, markers=True,\n",
    "           title=\"Agreement with the cosine series\", xlabel=\"Fourier number\", ylabel=\"Relative profile error [%]\",\n",
    "           scale=\"loglog\", ax=fig[1])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
