{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "partial-diff-00",
   "metadata": {},
   "source": [
    "# The first instant of thermal contact\n",
    "Two long solids, initially at different uniform temperatures, touch at x = 0. Compare the interface temperature determined by thermal effusivity with whole temperature profiles, then check heat conservation. The experiment uses SI units and assumes perfect contact and short observation times."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "partial-diff-01",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "k_left, k_right=4.,1.            # W/(m K)\n",
    "capacity_left,capacity_right=1e6,1e6  # volumetric heat capacities, J/(m³ K)\n",
    "time=2.                           # seconds\n",
    "TL,TR=80.,20.                     # degrees Celsius\n",
    "assert min(k_left,k_right,capacity_left,capacity_right,time)>0\n",
    "al,ar=k_left/capacity_left,k_right/capacity_right\n",
    "el,er=np.sqrt(k_left*capacity_left),np.sqrt(k_right*capacity_right)\n",
    "contact=(el*TL+er*TR)/(el+er)\n",
    "erf=np.vectorize(math.erf,otypes=[float])\n",
    "def temperature(x,t):\n",
    "    return np.where(x<=0,contact+(TL-contact)*erf(-x/(2*np.sqrt(al*t))),\n",
    "                    contact+(TR-contact)*erf(x/(2*np.sqrt(ar*t))))\n",
    "def q(t):\n",
    "    return el*er/(el+er)*(TL-TR)/np.sqrt(np.pi*t)\n",
    "Q=2*q(time)*time\n",
    "print(f\"Interface {contact:.3f} °C; flux at t = {time:g} s: {q(time):.2f} W/m²; transferred {Q:.2f} J/m²\")\n",
    "assert np.isclose(el*(TL-contact),er*(contact-TR))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "partial-diff-02",
   "metadata": {},
   "source": [
    "## Inspect both half-spaces and the early flux\n",
    "The semi-infinite approximation requires the penetration distances to be small compared with specimen length. The flux diverges as time approaches zero, yet its time integral is finite. Change the right material's heat capacity at fixed conductivity."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "partial-diff-03",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig,(profile,flux)=plt.subplots(1,2,figsize=(10,4),layout=\"constrained\")\n",
    "width=5*np.sqrt(max(al,ar)*time)\n",
    "x=np.linspace(-width,width,501)\n",
    "for t,c in [(time/4,\"#b94626\"),(time,\"#145c71\")]:\n",
    "    profile.plot(1000*x,temperature(x,t),color=c,label=f\"{t:g} s\")\n",
    "profile.axvline(0,color=\"grey\",ls=\":\")\n",
    "profile.set(xlabel=\"Position (mm)\",ylabel=\"Temperature (°C)\",title=\"Continuity at the contact\")\n",
    "profile.legend()\n",
    "tt=np.geomspace(.01*time,3*time,150)\n",
    "flux.plot(tt,q(tt),color=\"#145c71\")\n",
    "flux.set_xscale(\"log\")\n",
    "if TL != TR: flux.set_yscale(\"symlog\",linthresh=np.min(abs(q(tt)))/4)\n",
    "flux.set(xlabel=\"Time (s)\",ylabel=\"Left-to-right flux (W/m²)\",title=\"Initially singular but integrable flux\")\n",
    "for ax in (profile,flux):ax.grid(alpha=.2)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "partial-diff-04",
   "metadata": {},
   "source": [
    "## Independently integrate the energy in each body\n",
    "Temperature deficits and excesses integrated normal to the contact, and multiplied by volumetric heat capacity, are energies per unit area. Both should agree with the integral of the interface flux."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "partial-diff-05",
   "metadata": {},
   "outputs": [],
   "source": [
    "l=np.linspace(-12*np.sqrt(al*time),0,3001)\n",
    "r=np.linspace(0,12*np.sqrt(ar*time),3001)\n",
    "def trapezoid(values,grid):\n",
    "    return np.sum((values[:-1]+values[1:])*np.diff(grid)/2)\n",
    "lost=capacity_left*trapezoid(TL-temperature(l,time),l)\n",
    "gained=capacity_right*trapezoid(temperature(r,time)-TR,r)\n",
    "assert np.isclose(lost,Q,rtol=1e-6) and np.isclose(gained,Q,rtol=1e-6)\n",
    "print(\"Spatial energy integrals:\",lost,gained,\"J/m²\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
