{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Convective cooling of a lumped thermal mass\n",
    "\n",
    "A compact body with total heat capacity $C$ sits in a still environment at\n",
    "temperature $T_\\infty$ and loses heat through its surface by convection. When the\n",
    "body is small enough that its interior stays nearly uniform (the lumped-capacitance\n",
    "limit), a single temperature $T(t)$ describes it and Newton's law of cooling holds:\n",
    "\n",
    "$$C\\,\\frac{dT}{dt}=-h\\,A\\,(T-T_\\infty).$$\n",
    "\n",
    "Here $h$ is the convective heat-transfer coefficient and $A$ the exposed area; the\n",
    "product $hA$ is the thermal conductance to the surroundings. OneSimulation treats\n",
    "this as a zero-dimensional (lumped) model and integrates it in time with the\n",
    "classical fourth-order Runge-Kutta method.\n",
    "\n",
    "**Reference.** Separating variables gives the exponential decay towards the\n",
    "ambient temperature,\n",
    "\n",
    "$$T(t)=T_\\infty+(T_0-T_\\infty)\\,e^{-hA\\,t/C},$$\n",
    "\n",
    "with time constant $\\tau=C/(hA)$. We compare every stored time against this\n",
    "expression."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from onesim.cad.geometry import LumpedDomain\n",
    "from onesim.meshing import LumpedMesh\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.discretization import LumpedParameters\n",
    "from onesim.numerics.time import ClassicalRungeKutta4\n",
    "from onesim.physics.systems import ThermalCapacitance\n",
    "from onesim.results.storage import MemoryOutputSink, Output\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parameters and model\n",
    "\n",
    "The parameters can be changed. The reference formula below stays valid as long as\n",
    "the heat capacity, area, heat-transfer coefficient and ambient temperature are\n",
    "constant. The values describe a small metal part cooling in quiet air."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "heat_capacity = 900.0\n",
    "heat_transfer_coefficient = 15.0\n",
    "area = 0.06\n",
    "ambient_temperature = 300.0\n",
    "initial_temperature = 350.0\n",
    "\n",
    "conductance = heat_transfer_coefficient * area\n",
    "time_constant = heat_capacity / conductance\n",
    "end_time = 3.0 * time_constant\n",
    "time_step = 0.05 * time_constant\n",
    "print(\n",
    "    f\"conductance hA = {conductance:.3f} W/K,  time constant C/(hA) = {time_constant:.1f} s\"\n",
    ")\n",
    "\n",
    "domain = LumpedDomain()\n",
    "model = ThermalCapacitance(\n",
    "    domain=domain.system,\n",
    "    heat_capacity=heat_capacity,\n",
    "    conductance=conductance,\n",
    "    ambient_temperature=ambient_temperature,\n",
    "    heating=0.0,\n",
    ")\n",
    "simulation = Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"Convective cooling of a lumped thermal mass\",\n",
    "        geometry=domain,\n",
    "        physics=(model,),\n",
    "        initial_conditions=(InitialValue(model.temperature, initial_temperature),),\n",
    "    ),\n",
    "    mesh=LumpedMesh(domain),\n",
    "    numerics=Numerics(\n",
    "        spatial=LumpedParameters(),\n",
    "        time_integrator=ClassicalRungeKutta4(),\n",
    "    ),\n",
    ")\n",
    "simulation.validate().require_valid()\n",
    "\n",
    "sink = MemoryOutputSink()\n",
    "result = simulation.run(\n",
    "    start_time=0.0,\n",
    "    end_time=end_time,\n",
    "    time_step=time_step,\n",
    "    output=Output(fields=(model.temperature,), interval=time_step, sink=sink),\n",
    ")\n",
    "times, temperatures = sink.time_series(model.temperature)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed-form solution\n",
    "\n",
    "We evaluate the exponential reference at every stored time. A passing check shows\n",
    "that this numerical example agrees with Newton's law of cooling; it is not an\n",
    "experimental validation of a real object."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "reference = ambient_temperature + (initial_temperature - ambient_temperature) * np.exp(\n",
    "    -conductance * times / heat_capacity\n",
    ")\n",
    "max_abs_error = float(np.max(np.abs(temperatures - reference)))\n",
    "print(\"Error per stored time (K):\")\n",
    "for t, err in zip(times, np.abs(temperatures - reference)):\n",
    "    print(f\"  t={t:7.1f} s  |dT|={err:.3e} K\")\n",
    "print(f\"Maximum absolute error against the exponential: {max_abs_error:.3e} K\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "dense_t = np.linspace(0.0, end_time, 400)\n",
    "plots.line(\n",
    "    points={\"OneSimulation RK4\": (times, temperatures)},\n",
    "    reference={\n",
    "        \"Newton's law of cooling\": (\n",
    "            dense_t,\n",
    "            ambient_temperature\n",
    "            + (initial_temperature - ambient_temperature)\n",
    "            * np.exp(-conductance * dense_t / heat_capacity),\n",
    "        )\n",
    "    },\n",
    "    hlines={\"ambient\": ambient_temperature},\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"temperature [K]\",\n",
    "    title=\"Convective cooling of a lumped thermal mass\",\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Halve the time step and confirm that the error against the exponential shrinks\n",
    "as expected for a fourth-order method. Then vary the conductance $hA$ or the heat\n",
    "capacity $C$ and relate the change in the time constant $\\tau=C/(hA)$ to the\n",
    "equation. Adding a constant internal power through the `heating` input turns the\n",
    "body towards a shifted steady state $T_\\infty+P/(hA)$ instead of the ambient\n",
    "temperature; replace the reference accordingly before studying that case."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
