{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# Block 3 — Extra Exercises · Bridging the Scales\n### Bridging the Scales · GEFENOL Summer School 2026 · *Noise and Space in Biological Systems*\n\n**Fresh multiscale problems — not the tumour/WKB examples from the slides.** Complete each **>>> TODO** and delete the guard; each exercise ends with a ✅ **self-check**.\n\n**New systems here:** **adaptive $\\tau$-leaping** (let the step size choose itself), the **SIS endemic–extinction** time and its exponential dependence on system size, and **competitive exclusion** of two species on one shared nutrient. Answers in *Block3_Extra_Exercises_Solutions.ipynb*."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "import numpy as np\nimport matplotlib.pyplot as plt\nplt.rcParams.update({'figure.figsize':(7,4),'axes.grid':True,'grid.alpha':0.25,'font.size':11})\n\n# --- provided: the exact birth-death SSA (our reference), from Block 1 ---\ndef ssa_bd(k, g, X0, T, seed=0):\n    rng = np.random.default_rng(seed)\n    t, X, steps = 0.0, X0, 0\n    while t < T:\n        ap, am = k, g*X\n        a0 = ap + am\n        if a0 == 0: break\n        t += rng.exponential(1/a0)\n        X += 1 if rng.random()*a0 < ap else -1\n        steps += 1\n    return X, steps\n\nk, g = 50.0, 0.1     # steady state <X> = 500"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Exercise 1 · Adaptive $\\tau$-leaping — let the step choose itself\nA fixed $\\tau$ is wasteful when propensities are flat and dangerous when they change fast. The Cao–Gillespie–Petzold rule bounds the fractional change of the varying propensity $a_2=\\gamma X$ using both its mean drift and its variance:\n$$\\tau = \\min\\!\\left(\\frac{\\varepsilon\\,a_2}{|\\mu|},\\ \\frac{(\\varepsilon\\,a_2)^2}{\\sigma^2}\\right),\\qquad \\mu = g\\,(a_+-a_-),\\quad \\sigma^2 = g^2\\,(a_+ + a_-).$$\nNear steady state $\\mu\\to0$ so the mean term diverges and the variance term takes over — you still leap far, but never recklessly.\n\nComplete the adaptive step size and the Poisson updates.\n\n<details><summary>💡 Hint</summary>\n\n`mu=g*(ap-am)`, `sig2=g*g*(ap+am)`, `a2=am`. Then `tau = min(eps*a2/abs(mu), (eps*a2)**2/sig2)` — guard the zero cases and fall back to `1/a0`. Fire `rng.poisson(ap*tau)` births and `rng.poisson(am*tau)` deaths.\n</details>"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def adaptive_tau(k, g, X0, T, eps=0.03, seed=0):\n    rng = np.random.default_rng(seed)\n    t, X, steps = 0.0, X0, 0\n    while t < T:\n        ap, am = k, g*X\n        a0 = ap + am\n        if a0 == 0: break\n        denom = abs(g*(ap - am))\n        # >>> TODO: two-term adaptive step size tau = min(mean-term, variance-term)\n        #          mu = g*(ap-am);  sig2 = g*g*(ap+am);  a2 = am\n        #          guard mu==0 and sig2==0 with np.inf, and fall back to 1/a0 if tau is not finite\n        # tau = ...\n        raise NotImplementedError\n        # >>> TODO: Poisson births and deaths over tau, then update X once\n        # X = max(X + ... - ..., 0)\n        raise NotImplementedError\n        t += tau; steps += 1\n    return X, steps\n\nXa, na = adaptive_tau(k, g, 0, 60, seed=1)\nXe, ne = ssa_bd(k, g, 0, 60, seed=1)\nprint(f\"adaptive: final X = {Xa}, steps = {na}\")\nprint(f\"exact SSA: final X = {Xe}, steps = {ne}\")"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# ✅ self-check: same steady-state mean as exact SSA, at a fraction of the steps\nmean_adapt = np.mean([adaptive_tau(k, g, 500, 40, seed=s)[0] for s in range(60)])\nsteps_adapt = np.mean([adaptive_tau(k, g, 500, 40, seed=s)[1] for s in range(10)])\nsteps_exact = np.mean([ssa_bd(k, g, 500, 40, seed=s)[1] for s in range(10)])\nprint(f\"adaptive mean = {mean_adapt:.1f} (target {k/g:.0f})   steps: adaptive={steps_adapt:.0f} vs exact={steps_exact:.0f}\")\nassert abs(mean_adapt - k/g) < 25, \"adaptive leap should relax to k/g\"\nassert steps_adapt < 0.5*steps_exact, \"adaptive leaping should use far fewer steps\"\nprint(\"PASSED \\u2705  the step size adapts — accuracy of the SSA, cost of a leap\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Exercise 2 · SIS endemic state — extinction time explodes with system size\nSIS in a population of $N$: $S+I\\xrightarrow{\\beta/N}2I$, $I\\xrightarrow{\\gamma}S$ (recovered become susceptible again). For $R_0=\\beta/\\gamma>1$ the disease settles into an **endemic** quasi-stationary state, but $I=0$ is the only true absorbing state — sooner or later a fluctuation clears it. Large-deviation theory: the mean time to extinction grows **exponentially** in $N$, so $\\ln\\langle T\\rangle$ is linear in $N$.\n\nComplete the SIS Gillespie step and stop at $I=0$.\n\n<details><summary>💡 Hint</summary>\n\n`a_inf = beta/N*S*I`, `a_rec = gamma*I`. Infection: `S-=1; I+=1`; recovery: `S+=1; I-=1`. Loop `while I>0`.\n</details>"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def sis_extinction_time(N, beta, gamma, seed=0):\n    rng = np.random.default_rng(seed)\n    I = int(round(N*(1 - gamma/beta)))     # start near the endemic level\n    S = N - I\n    t = 0.0\n    while I > 0:\n        # >>> TODO: propensities, advance time, one Gillespie step (infection or recovery)\n        raise NotImplementedError\n    return t\n\nbeta, gamma = 1.5, 1.0     # R0 = 1.5\nNs  = [20, 30, 40, 50, 60]\nlnT = [np.log(np.mean([sis_extinction_time(N, beta, gamma, seed=s) for s in range(80)])) for N in Ns]\nslope = np.polyfit(Ns, lnT, 1)[0]\nplt.plot(Ns, lnT, 'o-'); plt.xlabel('population N'); plt.ylabel('ln<T_extinction>')\nplt.title(f'endemic lifetime is exponential in N   (slope = {slope:.3f})');"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# ✅ self-check: ln<T> rises roughly linearly with N (positive large-deviation action)\nassert np.all(np.diff(lnT) > 0) and slope > 0, \"bigger populations should persist exponentially longer\"\nr2 = np.corrcoef(Ns, lnT)[0,1]**2\nprint(f\"slope = {slope:.3f}   linear-fit R^2 = {r2:.3f}\")\nassert r2 > 0.9, \"expected a clean straight line in ln<T> vs N\"\nprint(\"PASSED \\u2705  the endemic state is metastable — stability is exponential in system size\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Exercise 3 · Competitive exclusion on a shared nutrient\nTwo species $n_1,n_2$ feed on one nutrient $S$ (supplied at rate $\\sigma$, decaying at $\\delta$). Monod growth $\\mu_i(S)=\\mu_i\\frac{S}{K_i+S}$, common death $d$. The species with the lower **break-even nutrient** $R^*_i=\\dfrac{K_i\\,d}{\\mu_i-d}$ wins — it can grow at a nutrient level where the other cannot. A $\\tau$-leaping simulation should show one species drive the other extinct.\n\nComplete the per-species growth propensities.\n\n<details><summary>💡 Hint</summary>\n\n`growth_i = mu_i * S/(K_i+S) * n_i`. Nutrient is consumed in proportion to total growth; each species also dies at rate `d*n_i`.\n</details>"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def Rstar(mu, K, d):\n    return K*d/(mu - d)\n\ndef chemostat(mu1, K1, mu2, K2, d=0.3, sigma=90.0, delta=0.1, T=400, dt=0.02, seed=0):\n    rng = np.random.default_rng(seed)\n    n1, n2, S = 40.0, 40.0, 30.0\n    hist = []\n    for _ in range(int(T/dt)):\n        # >>> TODO: Monod growth propensities for each species\n        # g1 = ...\n        # g2 = ...\n        raise NotImplementedError\n        n1 += rng.poisson(max(g1,0)*dt) - rng.poisson(d*n1*dt)\n        n2 += rng.poisson(max(g2,0)*dt) - rng.poisson(d*n2*dt)\n        S  += (sigma - delta*S)*dt - (g1+g2)*dt      # supply, decay, consumption\n        n1, n2, S = max(n1,0), max(n2,0), max(S,0)\n        hist.append((n1, n2))\n    return np.array(hist)\n\nmu1, K1 = 1.0, 4.0      # species 1\nmu2, K2 = 1.0, 12.0     # species 2 (needs more nutrient -> higher R*)\nprint(f\"R*1 = {Rstar(mu1,K1,0.3):.2f}   R*2 = {Rstar(mu2,K2,0.3):.2f}\")\nH = chemostat(mu1, K1, mu2, K2, seed=2)\nplt.plot(H[:,0], label='species 1 (low R*)'); plt.plot(H[:,1], label='species 2 (high R*)')\nplt.xlabel('step'); plt.ylabel('population'); plt.legend(); plt.title('competitive exclusion');"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# ✅ self-check: the species with the LOWER R* must win (the other is driven to extinction)\nwin1 = 0\nfor s in range(12):\n    H = chemostat(mu1, K1, mu2, K2, seed=s)\n    if H[-1,0] > H[-1,1]:\n        win1 += 1\nprint(f\"species 1 (lower R*) wins in {win1}/12 runs\")\nassert Rstar(mu1,K1,0.3) < Rstar(mu2,K2,0.3), \"species 1 should have the lower R*\"\nassert win1 >= 10, \"the lower-R* competitor should reliably exclude the other\"\nprint(\"PASSED \\u2705  R* rule: the best nutrient-scavenger wins, even with noise\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "---\n### Going further\n- **Adaptive vs fixed:** overlay the adaptive trajectory on a fine fixed-$\\tau$ leap and the exact SSA — accuracy should match while step count drops.\n- **$R_0$ threshold:** in Exercise 2, lower $\\beta$ toward $\\gamma$ and watch the extinction time collapse as $R_0\\to1$.\n- **Coexistence:** give the two species *two* limiting nutrients in Exercise 3 and the exclusion principle relaxes — both can persist.\n- The through-line of the school: single molecules (Block 1) → space (Block 2) → bridge the scales and apply (Block 3)."
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.x"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}