{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "fce81389",
   "metadata": {},
   "source": [
    "# Where a thermoelectric cooler rejects its heat\n",
    "\n",
    "A temperature-controlled sensor is colder than its laboratory surroundings. Increase the current in a thermoelectric module and predict how the available cooling capacity changes. The model treats the effective properties of the entire module as constant. Edit the inputs and rerun the notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "27caf209",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "Tc, Ta = 288., 298.       # cold plate and ambient, K\n",
    "alpha = .05               # module Seebeck coefficient, V/K\n",
    "R, K = 2.0, .60           # electrical resistance (ohm), thermal conductance (W/K)\n",
    "Rs = .45                  # sink-to-air thermal resistance, K/W\n",
    "selected = 2.5            # operating current, A\n",
    "assert min(Tc,Ta,alpha,R,K,selected)>0 and Rs >= 0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96a77791",
   "metadata": {},
   "source": [
    "## Close the hot-side balance before computing cold-side capacity\n",
    "Use the convective sink relation $T_h=T_a+R_s Q_h$ to eliminate $Q_h$. Heat transport at the hot face contains Peltier heat, half of the electrical dissipation and heat conducted back toward the cold plate. Current is positive in the cooling direction."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "694f5db2",
   "metadata": {},
   "outputs": [],
   "source": [
    "def operating(I, sink):\n",
    "    denom = 1+sink*(K-alpha*I)\n",
    "    if np.any(denom <= 0):\n",
    "        raise ValueError(\"The chosen hot-side equilibrium is outside the stable constant-property branch.\")\n",
    "    Th = (Ta+sink*(K*Tc + .5*R*I**2))/denom\n",
    "    Qc = alpha*Tc*I - .5*R*I**2 - K*(Th-Tc)\n",
    "    volts = R*I + alpha*(Th-Tc)\n",
    "    Qh = alpha*Th*I + .5*R*I**2 - K*(Th-Tc)\n",
    "    return Th,Qc,volts,Qh\n",
    "\n",
    "Th,Qc,V,Qh = operating(selected,Rs)\n",
    "print(f\"Hot face {Th:.2f} K; cold-side capacity {Qc:.2f} W; supply {V:.3f} V; hot-side load {Qh:.2f} W\")\n",
    "print(\"Cooling COP:\", round(Qc/(V*selected),3) if Qc>0 else \"no net cooling\")\n",
    "assert np.isclose(Qh-Qc,selected*V)\n",
    "assert np.isclose(Th-Ta,Rs*Qh)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "534d0767",
   "metadata": {},
   "source": [
    "## Compare the current sweep for two heat sinks\n",
    "The coefficient of performance is plotted only where the module removes heat and consumes positive electrical power. A passive thermal leak at zero current can therefore appear below zero on the capacity panel."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5ca5a6ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "amps = np.linspace(0,8.,420)\n",
    "fig, ax = plt.subplots(1,2,figsize=(9,3.5),layout=\"constrained\")\n",
    "for resistance,style in [(0.,\"--\"),(Rs,\"-\")]:\n",
    "    t,q,v,qh = operating(amps,resistance)\n",
    "    power = amps*v\n",
    "    cop = np.divide(q,power,out=np.full_like(q,np.nan),where=(q>0)&(power>0))\n",
    "    ax[0].plot(amps,q,style,label=f\"Sink {resistance:.2f} K/W\")\n",
    "    ax[1].plot(amps,cop,style,label=f\"Sink {resistance:.2f} K/W\")\n",
    "    best = np.argmax(q)\n",
    "    print(f\"In this sweep, sink {resistance:.2f} K/W: capacity peaks near {amps[best]:.2f} A\")\n",
    "ax[0].set(xlabel=\"Current (A)\",ylabel=\"Heat removed at cold plate (W)\",title=\"Cooling capacity\")\n",
    "ax[1].set(xlabel=\"Current (A)\",ylabel=\"Cooling COP\",title=\"Cooling per unit electrical input\")\n",
    "for a in ax:\n",
    "    a.axvline(selected,color=\"0.5\",ls=\":\",lw=1); a.grid(alpha=.22); a.legend(fontsize=8)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2e04f07",
   "metadata": {},
   "source": [
    "## Decide which operating point serves the measurement\n",
    "Suppose the sensor dissipates 15 W. Use the arrays to find its lowest feasible drive current on the grid and compare the cooling margin with the point of maximum capacity. Repeat with an ambient temperature 5 K higher. Check whether the hot-face temperature remains within the range where your assumed constant properties are credible."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6d7d176a",
   "metadata": {},
   "outputs": [],
   "source": [
    "target = 15.0\n",
    "_,capacity,_,_ = operating(amps,Rs)\n",
    "indices = np.flatnonzero(capacity >= target)\n",
    "print(f\"First current in sweep supplying {target:g} W: {amps[indices[0]]:.3f} A\" if len(indices) else \"Target unavailable in this sweep\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3a969852",
   "metadata": {},
   "source": [
    "## Resolve a cooling threshold between sweep points\n",
    "A sampled current sweep can miss the exact point at which a heat load is first served. Use the rising flank as a bracket for a scalar solve and check the remaining heat-balance error. A local OneSimulation installation supplies its monotone inverse. The browser performs bisection with the same limits."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7a67dfd0",
   "metadata": {},
   "outputs": [],
   "source": [
    "if len(indices) and indices[0] > 0:\n",
    "    first = indices[0]\n",
    "    lower, upper = amps[first - 1], amps[first]\n",
    "    def cooling(current):\n",
    "        return operating(current, Rs)[1]\n",
    "\n",
    "    try:\n",
    "        from onesim.numerics.nonlinear.kernels.local_solvers.inversion.bracketed_inverse import bisect_increasing\n",
    "    except ImportError:\n",
    "        for _ in range(50):\n",
    "            centre = (lower + upper) / 2\n",
    "            if cooling(centre) < target:\n",
    "                lower = centre\n",
    "            else:\n",
    "                upper = centre\n",
    "        threshold = (lower + upper) / 2\n",
    "        method = \"Notebook bisection\"\n",
    "    else:\n",
    "        threshold = float(bisect_increasing(cooling, target, lower, upper))\n",
    "        method = \"OneSimulation bracketed inverse\"\n",
    "\n",
    "    print(f\"{method}: lower load threshold {threshold:.6f} A\")\n",
    "    assert np.isclose(cooling(threshold), target)\n",
    "else:\n",
    "    print(\"No interior lower crossing for this load and current range.\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
