{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Block 3 — Exercises · Bridging the Scales: Hybrid Methods & Tumours\n",
    "### Bridging the Scales · GEFENOL Summer School 2026 · *Noise and Space in Biological Systems*\n",
    "\n",
    "The exact SSA is the **floor**, not the ceiling. Here you climb the approximation ladder — **$\\tau$-leaping** and the **Chemical Langevin Equation** — then build the **hybrid** scheme (deterministic PDE in the dense bulk, integer SSA at the sparse edge) and turn it on tumour growth.\n",
    "\n",
    "Complete every **>>> TODO**; the ✅ self-checks should print **PASSED**. *Worked solutions:* **Block3_Hybrid_and_Tumours.ipynb** and **Block3_All_Examples.ipynb**.\n",
    "\n",
    "**Hybrid scheme:** Alarcón, Briñas-Pascual, Calvo, Guerrero & Stepanova, *arXiv:2409.13911*."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "plt.rcParams.update({'figure.figsize':(7,4),'axes.grid':True,'grid.alpha':0.25,'font.size':11})\n",
    "\n",
    "# --- provided: the exact birth-death SSA from Block 1 (our reference) ---\n",
    "def ssa_bd(k, g, X0, T, seed=0):\n",
    "    rng = np.random.default_rng(seed)\n",
    "    t, X = 0.0, X0\n",
    "    ts, xs = [t], [X]\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",
    "        ts.append(t); xs.append(X)\n",
    "    return np.array(ts), np.array(xs)\n",
    "\n",
    "k, g = 50.0, 0.1          # steady state <X> = k/g = 500"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 1 · $\\tau$-leaping — leap over many reactions at once\n",
    "Freeze the propensities over a window $\\tau$ and fire a **Poisson** number of each reaction, $k_j\\sim\\mathrm{Poisson}(a_j\\tau)$, then update once. Far fewer steps than the exact SSA; accuracy is set by $\\tau$ (small $\\tau\\to$ exact SSA, large $\\tau\\to$ the CLE).\n",
    "\n",
    "Complete the two Poisson draws and the single state update.\n",
    "\n",
    "<details><summary>💡 Hint</summary>\n",
    "\n",
    "`births = rng.poisson(ap*tau)`, `deaths = rng.poisson(am*tau)`, then `X = max(X + births - deaths, 0)`.\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def tau_leap(k, g, X0, T, tau, seed=0):\n",
    "    rng = np.random.default_rng(seed)\n",
    "    t, X = 0.0, X0\n",
    "    ts, xs = [t], [X]\n",
    "    while t < T:\n",
    "        ap, am = k, g*X                 # frozen propensities\n",
    "        # >>> TODO: Poisson births & deaths over the window tau, then update X once\n",
    "        raise NotImplementedError\n",
    "        t += tau\n",
    "        ts.append(t); xs.append(X)\n",
    "    return np.array(ts), np.array(xs)\n",
    "\n",
    "te, xe = ssa_bd(k, g, 0, 5, seed=1)\n",
    "tt, xt = tau_leap(k, g, 0, 5, tau=0.05, seed=1)\n",
    "plt.step(te, xe, where='post', lw=1, alpha=0.5, label='exact SSA')\n",
    "plt.step(tt, xt, where='post', lw=1.6, label='tau-leap (tau=0.05)')\n",
    "plt.axhline(k/g, color='k', ls='--', lw=1)\n",
    "plt.xlabel('time'); plt.ylabel('X'); plt.legend(); plt.title('tau-leaping vs exact SSA');"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ✅ self-check: tau-leap must reach the same steady-state mean as the exact SSA\n",
    "mean_tau = np.mean([tau_leap(k, g, 500, 6, tau=0.02, seed=s)[1][-200:].mean() for s in range(20)])\n",
    "print(f\"tau-leap steady-state mean = {mean_tau:.1f}   (target {k/g:.0f})\")\n",
    "assert abs(mean_tau - k/g) < 25, \"tau-leap should relax to k/g\"\n",
    "print(\"PASSED \\u2705  far fewer steps, same statistics\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 2 · The Chemical Langevin Equation\n",
    "When every channel fires many times, $\\mathrm{Poisson}(a_j\\tau)\\to\\mathcal N(a_j\\tau,\\,a_j\\tau)$ and the leap becomes the SDE\n",
    "$$\\mathrm{d}X=\\underbrace{\\textstyle\\sum_j\\nu_j a_j\\,\\mathrm{d}t}_{\\text{drift = ODE}}+\\underbrace{\\textstyle\\sum_j\\nu_j\\sqrt{a_j}\\,\\mathrm{d}W_j}_{\\text{noise}}.$$\n",
    "Integrate with **Euler–Maruyama**. For birth–death the drift is $(a_+ - a_-)\\,\\mathrm{d}t$ and the noise is $\\sqrt{a_+}\\,\\mathrm{d}W_1-\\sqrt{a_-}\\,\\mathrm{d}W_2$. Complete the drift and noise terms.\n",
    "\n",
    "<details><summary>💡 Hint</summary>\n",
    "\n",
    "`dW1, dW2 = rng.normal(size=2)*np.sqrt(dt)`; note the two reactions get **independent** Wiener increments.\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def cle(k, g, X0, T, dt, seed=0):\n",
    "    rng = np.random.default_rng(seed)\n",
    "    steps = int(T/dt)\n",
    "    X = np.empty(steps); X[0] = X0\n",
    "    for i in range(1, steps):\n",
    "        ap, am = k, g*X[i-1]                     # birth, death propensities\n",
    "        # >>> TODO (a): drift term  (sum nu_j a_j) * dt\n",
    "        # drift = ...\n",
    "        dW1, dW2 = rng.normal(size=2)*np.sqrt(dt)\n",
    "        # >>> TODO (b): noise term  sqrt(ap)*dW1 - sqrt(am)*dW2\n",
    "        # noise = ...\n",
    "        raise NotImplementedError\n",
    "        X[i] = max(X[i-1] + drift + noise, 0)\n",
    "    return np.linspace(0, T, steps), X\n",
    "\n",
    "te, xe = ssa_bd(k, g, 500, 5, seed=2)\n",
    "tc, xc = cle(k, g, 500, 5, dt=0.005, seed=2)\n",
    "plt.step(te, xe, where='post', lw=1, alpha=0.5, label='exact SSA')\n",
    "plt.plot(tc, xc, lw=1.3, label='CLE (Euler-Maruyama)')\n",
    "plt.axhline(k/g, color='k', ls='--', lw=1)\n",
    "plt.xlabel('time'); plt.ylabel('X'); plt.legend(); plt.title('CLE tracks the SSA at <X>=500');"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ✅ self-check: at high copy number CLE relative noise ~ 1/sqrt(N) matches Poisson\n",
    "tails = np.concatenate([cle(k, g, 500, 8, dt=0.005, seed=s)[1][-400:] for s in range(8)])\n",
    "cv = tails.std()/tails.mean()\n",
    "print(f\"CLE coeff. of variation = {cv:.3f}    (Poisson target 1/sqrt(500) = {1/np.sqrt(500):.3f})\")\n",
    "assert abs(cv - 1/np.sqrt(500)) < 0.02, \"CLE noise amplitude is off\"\n",
    "print(\"PASSED \\u2705  continuous noise, exact-SSA statistics at high N\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 3 · The hybrid front — PDE bulk + SSA edge\n",
    "A Fisher–KPP front: the dense **back** obeys the deterministic PDE, the sparse **front** (a few cells) needs the SSA. The rule: a box with count $n \\ge \\theta$ is deterministic, $n<\\theta$ is stochastic. Diffusion runs **everywhere** (that is the flux coupling across the interface), and the stochastic boxes are **renormalised** back to integers each step.\n",
    "\n",
    "Complete the abundance split and the renormalisation. Setting $\\theta=\\infty$ makes every box stochastic — the full SSA — so you can check the hybrid recovers the *stochastic* speed, not the mean-field one.\n",
    "\n",
    "<details><summary>💡 Hint</summary>\n",
    "\n",
    "- Masks: `det = m >= theta`, `sto = ~det`.\n",
    "- Deterministic growth: `m[det] += dt*gr[det]`; stochastic: `m[sto] += rng.poisson(np.clip(gr[sto],0,None)*dt)`.\n",
    "- Renormalise: `frac = m[sto]-np.floor(m[sto]); m[sto] = np.floor(m[sto]) + (rng.random(sto.sum()) < frac)`.\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nx, h, r, D = 400, 1.0, 1.0, 1.0\n",
    "Ninf, dt = 100, 0.1\n",
    "\n",
    "def laplacian(f):\n",
    "    L = np.roll(f,-1) - 2*f + np.roll(f,1)\n",
    "    L[0], L[-1] = f[1]-f[0], f[-2]-f[-1]     # no-flux ends\n",
    "    return L\n",
    "\n",
    "def front_position(u, level=0.5):\n",
    "    idx = np.where(u >= level)[0]\n",
    "    return idx.max()*h if len(idx) else 0.0\n",
    "\n",
    "def run_hybrid(T, theta=10, seed=0):\n",
    "    rng = np.random.default_rng(seed)\n",
    "    m = np.zeros(nx); m[:5] = Ninf           # counts per box\n",
    "    pos = []\n",
    "    for _ in range(int(T/dt)):\n",
    "        m = m + dt*D/h**2*laplacian(m)        # diffusion = flux coupling at the interface\n",
    "        gr = r*m*(1 - m/Ninf)\n",
    "        # >>> TODO (a): masks det / sto by comparing m to theta\n",
    "        # >>> TODO (b): deterministic growth on det boxes, Poisson growth on sto boxes\n",
    "        # >>> TODO (c): renormalise the sto boxes back to integer counts\n",
    "        raise NotImplementedError\n",
    "        m = np.clip(m, 0, None)\n",
    "        pos.append(front_position(m/Ninf))\n",
    "    return np.array(pos)\n",
    "\n",
    "T = 30; t = np.arange(int(T/dt))*dt\n",
    "p_ssa = run_hybrid(T, theta=np.inf, seed=1)   # theta=inf -> every box stochastic = full SSA\n",
    "p_hyb = run_hybrid(T, theta=10,     seed=1)\n",
    "vstar = 2*np.sqrt(r*D)\n",
    "plt.plot(t, p_ssa, label='full SSA (theta=inf)')\n",
    "plt.plot(t, p_hyb, '--', label='hybrid (theta=10)')\n",
    "plt.plot(t, vstar*t + p_ssa[0], ':', color='gray', label=f'mean-field v*={vstar:.2f}')\n",
    "plt.xlabel('time'); plt.ylabel('front position'); plt.legend(); plt.title('hybrid recovers the stochastic speed');"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ✅ self-check: hybrid speed should match the full SSA and stay BELOW v*\n",
    "def speed(p):\n",
    "    m = t > t.max()*0.5\n",
    "    return np.polyfit(t[m], p[m], 1)[0]\n",
    "v_ssa, v_hyb = speed(p_ssa), speed(p_hyb)\n",
    "print(f\"v_SSA = {v_ssa:.2f}   v_hybrid = {v_hyb:.2f}   v* = {vstar:.2f}\")\n",
    "assert v_hyb < vstar and abs(v_hyb - v_ssa) < 0.35, \"hybrid should track v_N, not v*\"\n",
    "print(\"PASSED \\u2705  SSA accuracy at PDE cost\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 4 · Tumours — invasion vs. latency (bistable Allee SSA)\n",
    "Cooperative (Allee) birth $b(n)=r\\,n\\frac{n}{A+n}$ with crowding death $d(n)=n\\!\\left(1+\\frac{n}{K}\\right)$ makes growth **bistable**: a dormant/cleared state and an invasive state. Identical lesions reach **different fates** — only noise separates them (the Block 1 toggle switch, now with clinical stakes).\n",
    "\n",
    "Complete the birth and death rates, then measure the cleared fraction over many identical seeds.\n",
    "\n",
    "<details><summary>💡 Hint</summary>\n",
    "\n",
    "`b = n*(n/(A+n))` (take $r=1$), `dth = n*(1 + n/K)`; step exactly like `ssa_bd` with `n += 1 if rng.random()*a0 < b else -1`.\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def tumour(seed, n0=5, r=3.0, A=6, K=60, T=40):\n",
    "    rng = np.random.default_rng(seed)\n",
    "    n, t = n0, 0.0\n",
    "    ts, ns = [t], [n]\n",
    "    while t < T and n > 0:\n",
    "        # >>> TODO: cooperative birth b and crowding death dth, then one Gillespie step\n",
    "        raise NotImplementedError\n",
    "        ts.append(t); ns.append(n)\n",
    "    return np.array(ts), np.array(ns)\n",
    "\n",
    "for s in range(16):                              # 16 identical lesions, different noise\n",
    "    ts, ns = tumour(s)\n",
    "    plt.step(ts, ns, where='post', lw=1, alpha=0.75)\n",
    "plt.xlabel('time'); plt.ylabel('n (cells)'); plt.title('Allee tumour: invasion vs latency');\n",
    "cleared = np.mean([tumour(s)[1][-1] == 0 for s in range(500)])\n",
    "print(f\"cleared fraction = {cleared:.2f}   (the rest escape to invasion)\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ✅ self-check: outcomes must be genuinely bimodal (some cleared, some invade)\n",
    "finals = np.array([tumour(s)[1][-1] for s in range(500)])\n",
    "frac_cleared = np.mean(finals == 0)\n",
    "frac_invaded = np.mean(finals > 30)\n",
    "print(f\"cleared = {frac_cleared:.2f}   invaded = {frac_invaded:.2f}\")\n",
    "assert frac_cleared > 0.1 and frac_invaded > 0.1, \"expected two clusters of fates\"\n",
    "print(\"PASSED \\u2705  identical lesions, divergent fates -- the escape PROBABILITY is what matters\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 5 · Rare events — the WKB law for extinction time\n",
    "Escape/extinction is exponentially rare: WKB / large-deviation theory predicts $\\langle T\\rangle\\sim e^{K S_0}$, i.e. $\\ln\\langle T\\rangle$ grows **linearly** in system size $K$, with slope the action $S_0$. Use the stochastic-logistic model ($W^+=n$, $W^-=n^2/K$), time each run to extinction, and fit the line.\n",
    "\n",
    "Complete the extinction-time loop.\n",
    "\n",
    "<details><summary>💡 Hint</summary>\n",
    "\n",
    "Start at `n = K`, `wp, wm = n, n*n/K`, advance `t += rng.exponential(1/(wp+wm))`, step up/down, and return `t` when `n` hits 0.\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def ext_time(K, seed):\n",
    "    rng = np.random.default_rng(seed)\n",
    "    n, t = K, 0.0\n",
    "    while n > 0:\n",
    "        # >>> TODO: birth wp, death wm; advance time; take one Gillespie step\n",
    "        raise NotImplementedError\n",
    "    return t\n",
    "\n",
    "Ks  = [20, 40, 60, 80]\n",
    "lnT = [np.log(np.mean([ext_time(K, s) for s in range(200)])) for K in Ks]\n",
    "slope = np.polyfit(Ks, lnT, 1)[0]\n",
    "plt.plot(Ks, lnT, 'o-')\n",
    "plt.xlabel('system size K'); plt.ylabel('ln<T>')\n",
    "plt.title(f'WKB law: ln<T> is linear in K   (slope S0 = {slope:.3f})');"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ✅ self-check: ln<T> must increase roughly linearly with K (positive action)\n",
    "assert np.all(np.diff(lnT) > 0) and slope > 0, \"larger systems should be exponentially longer-lived\"\n",
    "r2 = np.corrcoef(Ks, lnT)[0,1]**2\n",
    "print(f\"slope S0 = {slope:.3f},  linear fit R^2 = {r2:.3f}\")\n",
    "assert r2 > 0.95, \"expected a clean straight line\"\n",
    "print(\"PASSED \\u2705  bigger systems are exponentially more stable\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "### Going further\n",
    "- **Spatial hybrid competition:** two cell types invade for one shared diffusing nutrient (Monod kinetics), each running its own abundance partition — see **Block3_All_Examples.ipynb**, section 7. With identical founders only $V_1>V_2$ decides the winner; shrink the founders and a **stochastic founder effect** can flip the outcome.\n",
    "- **Choosing $\\tau$ safely:** implement the leap condition $|\\Delta a_j|\\le\\epsilon a_0$ and adaptive $\\tau$; watch out for the negativity trap (binomial $\\tau$-leaping).\n",
    "- **The arc of the course:** Block 1 (noise & exact SSA) → Block 2 (space & fronts) → Block 3 (bridge the scales, apply to tumours)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.x"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
