{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ordinary-dif-00",
   "metadata": {},
   "source": [
    "# Exponential propagation with a periodically driven input\n",
    "Integrating homogeneous decay exactly still leaves a numerical choice for the input. Compare a frozen heater signal with its exact convolution. Time is in seconds and the normalised temperature is in kelvin."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ordinary-dif-01",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "decay=.8                         # per second\n",
    "frequency=1.                     # cycles per second\n",
    "samples_per_period=1\n",
    "cycles=8\n",
    "assert .1 <= decay <= 4 and .25 <= frequency <= 4 and 1 <= samples_per_period <= 64 and 2 <= cycles <= 24\n",
    "w=2*np.pi*frequency\n",
    "h=1/(samples_per_period*frequency)\n",
    "drive=1.                         # kelvin per second\n",
    "t=np.arange(cycles*samples_per_period+1)*h\n",
    "def exact(t):\n",
    "    return drive*np.real((np.exp(1j*w*t)-np.exp(-decay*t))/(decay+1j*w))\n",
    "def freeze(t,dt):\n",
    "    out=[0.]\n",
    "    gain=-np.expm1(-decay*dt)/decay\n",
    "    for start in t[:-1]:\n",
    "        out.append(np.exp(-decay*dt)*out[-1]+gain*drive*np.cos(w*start))\n",
    "    return np.array(out)\n",
    "approx=freeze(t,h)\n",
    "continuous=exact(t)\n",
    "print(f\"Final temperature: frozen {approx[-1]:.7f}; exact {continuous[-1]:.7f} K\")\n",
    "if samples_per_period==1:\n",
    "    assert np.allclose(approx,drive*(1-np.exp(-decay*t))/decay)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ordinary-dif-02",
   "metadata": {},
   "source": [
    "## Resolve the source in time\n",
    "The homogeneous exponential factor is stable for every step shown. Use a finer time grid to see which periodic input the coarse samples missed. The convergence panel holds the final physical time fixed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ordinary-dif-03",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig,(values,refine)=plt.subplots(1,2,figsize=(10,4),layout=\"constrained\")\n",
    "tt=np.linspace(0,t[-1],801)\n",
    "values.plot(tt,exact(tt),color=\"#145c71\",label=\"exact convolution\")\n",
    "values.plot(t,approx,\"o--\",ms=3,color=\"#b94626\",label=\"frozen forcing\")\n",
    "values.set(xlabel=\"Time (s)\",ylabel=\"Temperature change (K)\",title=\"Exact decay, sampled heat input\")\n",
    "values.legend(fontsize=8)\n",
    "nn=2**np.arange(0,8)\n",
    "err=[]\n",
    "for n in nn:\n",
    "    dt=1/(frequency*n)\n",
    "    sample=np.arange(cycles*n+1)*dt\n",
    "    err.append(np.max(abs(freeze(sample,dt)-exact(sample))))\n",
    "refine.loglog(nn,err,\"o-\",color=\"#145c71\")\n",
    "refine.set(xlabel=\"Samples per forcing period\",ylabel=\"Max sampled error (K)\",title=\"Refinement restores the waveform\")\n",
    "for ax in (values,refine):ax.grid(alpha=.2)\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
