{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "260ad9a20d16",
   "metadata": {},
   "source": [
    "# Designing a two-level thermometer\n",
    "A thermometer estimates a bath temperature by counting excitations of a small system with a calibrated gap. Select a gap, generate a repeatable data set and determine whether a count of zero means zero temperature."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7f2748e788eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "temperature_K = 4.0\n",
    "gap_K = 9.60       # gap energy divided by Boltzmann's constant\n",
    "trials = 400\n",
    "seed = 21\n",
    "assert temperature_K>0 and gap_K>0 and trials>=10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6725209bfcd6",
   "metadata": {},
   "source": [
    "## Derive the likelihood from the canonical occupations\n",
    "For independent preparations the event count follows a binomial law. We use a stable logarithm for each outcome to compare temperatures, including when one outcome was never recorded."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "53c65db129ab",
   "metadata": {},
   "outputs": [],
   "source": [
    "def excited(x):\n",
    "    w=np.exp(-np.asarray(x))\n",
    "    return w/(1+w)\n",
    "x=gap_K/temperature_K\n",
    "p=excited(x); k=np.random.default_rng(seed).binomial(trials,p)\n",
    "def loglik(T):\n",
    "    u=gap_K/np.asarray(T)\n",
    "    return -k*u-trials*np.logaddexp(0,-u)\n",
    "lower=1/(x*np.sqrt(trials*p*(1-p))) if p>0 else np.inf\n",
    "estimate=gap_K/np.log((trials-k)/k) if 0<k<trials/2 else (0. if k==0 else np.inf)\n",
    "print(f\"Excited fraction {p:.5f}, observed {k}/{trials}, positive-temperature MLE {estimate:.5g} K\")\n",
    "print(f\"Local relative standard-error bound {lower:.4g}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f661ee6db41",
   "metadata": {},
   "source": [
    "## Compare the probability, thermal response and experimental likelihood\n",
    "The sensitivity of an energy reading is governed by its variance together with the rate at which its mean changes. A gap that is very large gives almost identical readings on every trial. A very small gap produces many transitions but their probability barely changes with temperature."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6cd063d3d54d",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig,ax=plt.subplots(1,2,figsize=(9,3.9),layout=\"constrained\")\n",
    "u=np.linspace(.01,max(8,1.1*x),400); probs=excited(u)\n",
    "ax[0].plot(u,probs,color=\"#375b9a\",label=\"Excited probability\")\n",
    "ax[0].plot(u,u*u*probs*(1-probs),color=\"#175868\",label=\"C / kB\")\n",
    "ax[0].axvline(x,ls=\":\",color=\"#a23d21\",label=\"Selected gap\")\n",
    "ax[0].set(xlabel=\"Gap / kBT\",ylabel=\"Dimensionless response\",title=\"Choose a gap near the peak\");ax[0].legend(fontsize=8)\n",
    "T=np.geomspace(temperature_K*.25,temperature_K*4,350); ll=loglik(T)\n",
    "ax[1].semilogx(T,np.exp(ll-ll.max()),color=\"#175868\")\n",
    "ax[1].axvline(temperature_K,ls=\":\",color=\"#375b9a\",label=\"Preparation temperature\")\n",
    "if np.isfinite(estimate) and estimate>0: ax[1].axvline(estimate,color=\"#a23d21\",ls=\"--\",label=\"Fitted temperature\")\n",
    "ax[1].set(xlabel=\"Trial temperature (K)\",ylabel=\"Likelihood / maximum on grid\",title=f\"One record with {k} excited sites\");ax[1].legend(fontsize=8)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cece56f45930",
   "metadata": {},
   "source": [
    "## Find the optimum and inspect a boundary outcome\n",
    "The optimum solves x tanh(x/2) = 2. Bisection uses the monotonicity on the positive axis. If no excitations were seen, calculate an exact one-sided 95% upper limit on the excitation probability, then invert it if that limit lies below one half."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e5c8e8eb7528",
   "metadata": {},
   "outputs": [],
   "source": [
    "a,b=1.,4.\n",
    "for _ in range(50):\n",
    "    m=(a+b)/2\n",
    "    if m*np.tanh(m/2)>2:b=m\n",
    "    else:a=m\n",
    "opt=(a+b)/2\n",
    "p95=-np.expm1(np.log(.05)/trials)\n",
    "T95=gap_K/np.log((1-p95)/p95) if p95<.5 else np.inf\n",
    "print(f\"Optimal gap/kBT {opt:.6f}. For zero successes an upper confidence limit is {T95:.5g} K.\")\n",
    "assert np.isclose(opt,2.39935728,rtol=1e-7)\n",
    "assert np.isclose((1-p95)**trials,.05)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
