{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Heat exchange between two thermal masses\n",
    "\n",
    "Two compact bodies with heat capacities $C_1$ and $C_2$ are connected by a\n",
    "thermal conductance $G$ (for example a short metal bridge) and are otherwise\n",
    "perfectly insulated. Each body is small enough to stay uniform in temperature,\n",
    "so two lumped balances describe the system:\n",
    "\n",
    "$$C_1\\,\\frac{dT_1}{dt}=-G\\,(T_1-T_2),\\qquad C_2\\,\\frac{dT_2}{dt}=-G\\,(T_2-T_1).$$\n",
    "\n",
    "In OneSimulation each body is a lumped thermal capacitance whose \"ambient\"\n",
    "input is fed by the other body's temperature. The two models are coupled\n",
    "monolithically and integrated with the classical fourth-order Runge-Kutta method.\n",
    "\n",
    "**Reference.** Adding the two balances shows that the total stored energy is\n",
    "conserved, so the capacity-weighted mean temperature\n",
    "\n",
    "$$\\bar T=\\frac{C_1 T_1+C_2 T_2}{C_1+C_2}$$\n",
    "\n",
    "stays constant, while the temperature difference decays exponentially,\n",
    "\n",
    "$$T_1(t)-T_2(t)=(T_{1,0}-T_{2,0})\\,e^{-G\\,(1/C_1+1/C_2)\\,t}.$$\n",
    "\n",
    "Both statements are checked at every stored time."
   ]
  },
  {
   "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.coupled_systems import MonolithicCoupling\n",
    "from onesim.numerics.discretization import LumpedParameters\n",
    "from onesim.numerics.field_transfer import GlobalValueTransfer\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.field_connections import FieldCoupling\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 formulas below stay valid as long as\n",
    "the two heat capacities and the conductance are constant and no heat leaves the\n",
    "pair. The values describe a hot 1.3 kg copper block bolted to a cooler 1.7 kg\n",
    "aluminium block through a thin bridge."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "heat_capacity_1 = 500.0\n",
    "heat_capacity_2 = 1500.0\n",
    "conductance = 2.0\n",
    "initial_temperature_1 = 360.0\n",
    "initial_temperature_2 = 300.0\n",
    "\n",
    "decay_rate = conductance * (1.0 / heat_capacity_1 + 1.0 / heat_capacity_2)\n",
    "time_constant = 1.0 / decay_rate\n",
    "mean_temperature = (\n",
    "    heat_capacity_1 * initial_temperature_1 + heat_capacity_2 * initial_temperature_2\n",
    ") / (heat_capacity_1 + heat_capacity_2)\n",
    "end_time = 4.0 * time_constant\n",
    "time_step = 0.02 * time_constant\n",
    "print(\n",
    "    f\"time constant 1/(G(1/C1+1/C2)) = {time_constant:.1f} s,  final temperature = {mean_temperature:.2f} K\"\n",
    ")\n",
    "\n",
    "domain = LumpedDomain()\n",
    "body_1 = ThermalCapacitance(\n",
    "    domain=domain.system,\n",
    "    heat_capacity=heat_capacity_1,\n",
    "    conductance=conductance,\n",
    "    ambient_temperature=None,\n",
    "    heating=0.0,\n",
    ")\n",
    "body_2 = ThermalCapacitance(\n",
    "    domain=domain.system,\n",
    "    heat_capacity=heat_capacity_2,\n",
    "    conductance=conductance,\n",
    "    ambient_temperature=None,\n",
    "    heating=0.0,\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Two thermal masses exchanging heat\",\n",
    "    geometry=domain,\n",
    "    physics=(body_1, body_2),\n",
    "    initial_conditions=(\n",
    "        InitialValue(body_1.temperature, initial_temperature_1),\n",
    "        InitialValue(body_2.temperature, initial_temperature_2),\n",
    "    ),\n",
    "    couplings=(\n",
    "        FieldCoupling(\n",
    "            source=body_2.temperature,\n",
    "            target=body_1.ambient,\n",
    "            transfer=GlobalValueTransfer(),\n",
    "        ),\n",
    "        FieldCoupling(\n",
    "            source=body_1.temperature,\n",
    "            target=body_2.ambient,\n",
    "            transfer=GlobalValueTransfer(),\n",
    "        ),\n",
    "    ),\n",
    ")\n",
    "numerics = Numerics(spatial=LumpedParameters())\n",
    "simulation = Simulation(\n",
    "    problem=problem,\n",
    "    mesh={body_1: LumpedMesh(domain), body_2: LumpedMesh(domain)},\n",
    "    numerics={body_1: numerics, body_2: numerics},\n",
    "    coupling_solver=MonolithicCoupling(\n",
    "        transient_systems=(body_1, body_2),\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(\n",
    "        fields=(body_1.temperature, body_2.temperature),\n",
    "        interval=time_step,\n",
    "        sink=sink,\n",
    "    ),\n",
    ")\n",
    "times = sink.times\n",
    "\n",
    "\n",
    "temperatures_1 = sink.time_series(body_1.temperature)[1]\n",
    "temperatures_2 = sink.time_series(body_2.temperature)[1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed-form solution\n",
    "\n",
    "We check the exponential decay of the temperature difference and the constancy\n",
    "of the capacity-weighted mean at every stored time. A passing check shows that\n",
    "this numerical example agrees with the two-node balance; it is not a measurement\n",
    "of real blocks."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "difference = temperatures_1 - temperatures_2\n",
    "reference_difference = (initial_temperature_1 - initial_temperature_2) * np.exp(\n",
    "    -decay_rate * times\n",
    ")\n",
    "max_difference_error = float(np.max(np.abs(difference - reference_difference)))\n",
    "weighted_mean = (\n",
    "    heat_capacity_1 * temperatures_1 + heat_capacity_2 * temperatures_2\n",
    ") / (heat_capacity_1 + heat_capacity_2)\n",
    "max_mean_drift = float(np.max(np.abs(weighted_mean - mean_temperature)))\n",
    "print(f\"Maximum error of the temperature difference: {max_difference_error:.3e} K\")\n",
    "print(f\"Maximum drift of the capacity-weighted mean:  {max_mean_drift:.3e} K\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each temperature individually follows from the two invariants.\n",
    "Recover the decay rate from the log-slope of the difference."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "fitted_rate = -np.polyfit(times, np.log(difference), 1)[0]\n",
    "print(\n",
    "    f\"Decay rate: fitted {fitted_rate:.6f} 1/s, exact G(1/C1+1/C2) = {decay_rate:.6f} 1/s\"\n",
    ")"
   ]
  },
  {
   "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",
    "dense_diff = (initial_temperature_1 - initial_temperature_2) * np.exp(\n",
    "    -decay_rate * dense_t\n",
    ")\n",
    "total_capacity = heat_capacity_1 + heat_capacity_2\n",
    "fig = plots.figure(2, 1, size=(8, 7))\n",
    "plots.line(\n",
    "    points={\n",
    "        \"body 1\": (times[::4], temperatures_1[::4]),\n",
    "        \"body 2\": (times[::4], temperatures_2[::4]),\n",
    "    },\n",
    "    reference={\n",
    "        \"body 1\": (\n",
    "            dense_t,\n",
    "            mean_temperature + heat_capacity_2 / total_capacity * dense_diff,\n",
    "        ),\n",
    "        \"body 2\": (\n",
    "            dense_t,\n",
    "            mean_temperature - heat_capacity_1 / total_capacity * dense_diff,\n",
    "        ),\n",
    "    },\n",
    "    hlines={\"capacity-weighted mean\": mean_temperature},\n",
    "    ylabel=\"temperature [K]\",\n",
    "    title=\"Two thermal masses: OneSimulation (markers) and closed form (dashed)\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\"OneSimulation T_1 - T_2\": (times[::4], difference[::4])},\n",
    "    reference={\"exponential decay\": (dense_t, dense_diff)},\n",
    "    scale=\"logy\",\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"temperature difference [K]\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the two heat capacities equal and confirm that the final temperature is\n",
    "the arithmetic mean. Give one body a constant `heating` power and the pair\n",
    "then warms without bound at the rate $P/(C_1+C_2)$ on top of the decaying\n",
    "difference; or add a third body to build a small thermal network. In each case\n",
    "write down the new reference before changing the checks."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
