{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "language": "python",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "fundamentals": {
   "title": "Put a thermometer on a bounded spin spectrum",
   "lead": "A collection of identical two-level degrees of freedom has both a lowest and a highest energy. Count the accessible states at each energy and determine from adjacent entropy differences which way energy flows when two systems are brought into weak thermal contact.",
   "unit_slug": "negative-temperatures-in-a-bounded-spin-system"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d1f3c809fc19",
   "metadata": {},
   "source": [
    "# Put a thermometer on a bounded spin spectrum\n",
    "\n",
    "A collection of identical two-level degrees of freedom has both a lowest and a highest energy. Count the accessible states at each energy and determine from adjacent entropy differences which way energy flows when two systems are brought into weak thermal contact."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa14fc0ee301",
   "metadata": {
    "fundamentals": {
     "section": "derive-the-model"
    }
   },
   "source": [
    "## Differentiate an entropy measured in counts\n",
    "\n",
    "Let $N$ distinguishable, weakly coupled sites each carry energy zero or $\\varepsilon$. A state with $n$ excitations has $E_n=n\\varepsilon$. The multiplicity of the narrow, fixed-energy shell equals the number of ways to place the excitations, $W_n={N\\choose n}$. Use the Boltzmann shell entropy $S_n=k_B\\ln W_n$. The temperature inferred from the population of two adjacent shells samples the derivative at an energy midway between them. Dividing their multiplicities before taking a logarithm gives an exact finite-system expression,\n",
    "\n",
    "$$\\beta_{n+1/2}\\varepsilon=\\frac{S_{n+1}-S_n}{k_B}=\\ln\\frac{N-n}{n+1},\\qquad \\beta=\\frac{1}{k_BT}.$$\n",
    "\n",
    "Adding an excitation near the bottom initially opens more arrangements. Beyond the middle, it closes them. The decreasing entropy on this upper branch assigns a negative inverse temperature to the population. In the limit of large $N$ at fixed excitation fraction $p$, the slope becomes $\\ln[(1-p)/p]$. The same relationship follows from $p/(1-p)=\\exp(-\\beta\\varepsilon)$ for a canonical two-level system.\n",
    "\n",
    "The upper energy bound allows a distribution weighted towards high energy to normalise. In experiment the degrees of freedom considered must also equilibrate amongst themselves on a timescale shorter than their relaxation into ordinary, effectively unbounded environmental modes. This calculation describes the spin subsystem during that interval."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8c50117ccea",
   "metadata": {
    "fundamentals": {
     "section": "worked-prediction"
    }
   },
   "source": [
    "## Predict the direction of an exchange\n",
    "\n",
    "Take $N=20$ and examine the transition from 15 to 16 excitations. The multiplicity ratio is $5/16$, the dimensionless inverse temperature is −1.1632, and $k_BT/\\varepsilon$ is approximately −0.860. The reflected transition from 4 to 5 has ratio $16/5$ and the opposite slope. The same number of possible arrangements at energies reflected about the midpoint gives opposite entropy gradients.\n",
    "\n",
    "Suppose system A initially has 16 excitations and the same-sized system B has 4. Moving one quantum from A to B multiplies the product of their multiplicities by $(16/5)^2=10.24$. A weak contact that samples the available microstates favours transfer out of the inverted specimen. More generally, when A gives up a small positive energy $q$, the entropy change is $\\Delta S/k_B\\simeq(\\beta_B-\\beta_A)q$. An inverted subsystem therefore gives up heat to an ordinary positive-temperature subsystem when the coupling permits energy exchange."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7831a52cc00c",
   "metadata": {
    "fundamentals": {
     "section": "choose-inputs",
     "notebook_only": true
    }
   },
   "source": [
    "## Set the experimental inputs\n",
    "\n",
    "Edit these values, then run the calculation and both figures again."
   ]
  },
  {
   "cell_type": "code",
   "id": "d36d77302ff5",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "teal, orange, blue = \"#19596a\", \"#aa462a\", \"#3868a0\"\n",
    "def axes(xlabel, ylabel):\n",
    "    fig, ax = plt.subplots(figsize=(7, 4), constrained_layout=True)\n",
    "    ax.set(xlabel=xlabel, ylabel=ylabel)\n",
    "    ax.grid(alpha=0.2)\n",
    "    return fig, ax"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "25b753dc0939",
   "metadata": {},
   "source": [
    "sites = 20\n",
    "lower_excitation = 15"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "326cec7a6004",
   "metadata": {},
   "source": [
    "from math import lgamma\n",
    "assert isinstance(sites,int) and sites >= 2\n",
    "assert isinstance(lower_excitation,int) and 0 <= lower_excitation < sites\n",
    "n = np.arange(sites+1)\n",
    "log_count = np.array([lgamma(sites+1)-lgamma(int(j)+1)-lgamma(sites-int(j)+1) for j in n])\n",
    "midpoint = (n[:-1]+.5)/sites\n",
    "slope = np.log((sites-n[:-1])/(n[:-1]+1))\n",
    "assert np.allclose(np.diff(log_count), slope)\n",
    "assert np.allclose(slope, -slope[::-1])\n",
    "print(f\"Midpoint inverse temperature βε: {slope[lower_excitation]:.5f}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "f39c3a02c273",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "thermodynamics-statistical-physics-statistical-mechanics-1.png",
      "alt": "The shell entropy rises from zero to a maximum near half excitation and falls back to zero at full inversion.",
      "caption": "The segment joining the two highlighted shells measures the entropy difference used in the finite-system inverse temperature."
     }
    }
   },
   "source": [
    "fig,ax = axes(\"Fraction of sites excited\", \"Shell entropy per site (in units of kB)\")\n",
    "ax.plot(n/sites,log_count/sites,\".-\",color=teal)\n",
    "i=lower_excitation\n",
    "ax.plot(n[i:i+2]/sites,log_count[i:i+2]/sites,\"o-\",color=orange,lw=3,label=\"Selected adjacent shells\")\n",
    "ax.legend()\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "008dc4ce92ce",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "The segment joining the two highlighted shells measures the entropy difference used in the finite-system inverse temperature."
   ]
  },
  {
   "cell_type": "code",
   "id": "d0672eeb7b4b",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "thermodynamics-statistical-physics-statistical-mechanics-2.png",
      "alt": "Exact adjacent-shell inverse temperatures are compared with a smooth large-system curve which changes sign at half excitation.",
      "caption": "The discrete slope belongs between neighbouring energies. Compare finite sizes at the same fractional position to see where the large-system approximation converges first."
     }
    }
   },
   "source": [
    "p = np.linspace(.015,.985,351)\n",
    "fig,ax = axes(\"Excitation fraction at the energy midpoint\", \"Inverse temperature βε\")\n",
    "ax.plot(p,np.log((1-p)/p),\"--\",color=blue,label=\"Large-system curve\")\n",
    "ax.plot(midpoint,slope,\".\",color=teal,label=\"Finite shell differences\")\n",
    "ax.plot(midpoint[i],slope[i],\"o\",color=orange)\n",
    "ax.axhline(0,color=\"grey\",lw=.8);ax.legend()\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "f0b995e65cd9",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "The discrete slope belongs between neighbouring energies. Compare finite sizes at the same fractional position to see where the large-system approximation converges first."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1fbac94ad9cd",
   "metadata": {
    "fundamentals": {
     "section": "problem-1"
    }
   },
   "source": [
    "## Exercise · the temperature halfway up an odd spectrum\n",
    "\n",
    "For eleven sites find the adjacent shells with exactly zero inverse temperature. What site occupation does this represent in the canonical description?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f9aae885949",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "Setting $11-n=n+1$ gives $n=5$. Five and six excitations have the same multiplicity, giving zero entropy slope at $E=5.5\\varepsilon$. In the canonical ensemble $\\beta=0$ gives equal probabilities for both site energies. The average excitation number is 5.5 although individual measurements return integers."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b614fa49ffdf",
   "metadata": {
    "fundamentals": {
     "section": "problem-2"
    }
   },
   "source": [
    "## Exercise · infer a population inversion\n",
    "\n",
    "A spin measurement yields three excited sites for every site in the lower state, in a sample large enough to neglect finite-size corrections. Calculate the inverse temperature and the mean energy of 100 equivalent sites."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8cdb1c8d6ba6",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "Here $p=3/4$. The Boltzmann ratio gives $\\beta\\varepsilon=-\\ln3\\simeq-1.099$, and the mean energy is\n",
    "\n",
    "$$\n",
    "100p\\varepsilon=75\\varepsilon.\n",
    "$$\n",
    "\n",
    "At the positive inverse temperature $+\\ln3/\\varepsilon$ the mean falls to $25\\varepsilon$. The two occupations have the same binary mixing entropy and opposite response to an infinitesimal energy exchange."
   ]
  }
 ]
}
