{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# Block 1 — Exercises · Noise & the Exact SSA\n### Bridging the Scales · GEFENOL Summer School 2026 · *Noise and Space in Biological Systems*\n\n**How to use this notebook.** Code cells contain lines marked **>>> TODO** that you must complete (and a *raise NotImplementedError* guard to delete once you have). Each exercise ends with a ✅ **self-check** cell that should print **PASSED** when your code is correct — the checks compare your simulation against the exact analytic results from the slides. Hints are hidden under each task.\n\n*Worked solutions live in* **Block1_Noise_and_the_SSA.ipynb** *— try each exercise before peeking.*\n\n**By the end you will have:** implemented the Gillespie SSA from scratch (the *when?* / *which?* logic), validated it against the Poisson benchmark, and seen absorbing states, bistability and noise-driven fate with your own code."
  },
  {
   "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})"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Exercise 1 · The two questions of Gillespie\nThe birth–death process $\\varnothing \\xrightarrow{k} X \\xrightarrow{\\gamma} \\varnothing$ has propensities $a_1=k$ and $a_2=\\gamma n$, total $a_0=a_1+a_2$.\n\nEvery SSA step answers two questions:\n- **When** does the next reaction fire? Draw a waiting time $\\tau \\sim \\mathrm{Exp}(a_0)$.\n- **Which** reaction is it? Birth with probability $a_1/a_0$, otherwise death.\n\nComplete both TODOs below.\n\n<details><summary>💡 Hint</summary>\n\n- `np.random.default_rng(seed).exponential(1/a0)` gives an exponential waiting time.\n- Draw one uniform `r.random()` and compare `r.random()*a0 < a1` for the birth branch.\n</details>"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def ssa_bd(k, gamma, t_max, n0=0, seed=None):\n    r = np.random.default_rng(seed)\n    n, t = n0, 0.0\n    ts, ns = [t], [n]\n    while t < t_max:\n        a1, a2 = k, gamma*n            # propensities\n        a0 = a1 + a2\n        if a0 == 0:\n            break\n        # >>> TODO (a): draw tau ~ Exp(a0) and advance time\n        # tau = ...\n        # t  += tau\n        # >>> TODO (b): fire birth (n+1) with prob a1/a0, else death (n-1)\n        # n  += ...\n        raise NotImplementedError(\"complete TODOs (a) and (b), then delete this line\")\n        ts.append(t); ns.append(n)\n    return np.array(ts), np.array(ns)"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# ✅ self-check: the steady state must be Poisson(k/gamma) -> mean = k/gamma, Fano = 1\nk, gamma = 20.0, 1.0\ncounts = [ssa_bd(k, gamma, 40, n0=0, seed=100+s)[1][-1] for s in range(3000)]\nm, var = np.mean(counts), np.var(counts)\nprint(f\"mean = {m:.2f}  (target {k/gamma:.0f})    Fano = {var/m:.2f}  (target 1.00)\")\nassert abs(m - k/gamma) < 1.0 and abs(var/m - 1.0) < 0.15, \"distribution is not Poisson yet\"\nprint(\"PASSED \\u2705\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Exercise 2 · Discreteness is qualitative — spontaneous extinction\nRe-use your `ssa_bd`. At $\\langle n\\rangle = k/\\gamma = 20$ the count essentially never reaches 0. Lower it to **$\\langle n\\rangle = 5$** (the regime where real gene regulation lives) and a single unlucky run of degradations can drive $n$ all the way to zero.\n\nWrite a function that reports whether a trajectory **ever touched $n=0$**, then compare the extinction frequency at $\\langle n\\rangle=5$ vs $\\langle n\\rangle=20$.\n\n<details><summary>💡 Hint</summary>\n\nThe trajectory array `ns` holds every state; `ns.min() == 0` tells you if it hit zero.\n</details>"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def touched_zero(k, gamma, t_max, seed):\n    ts, ns = ssa_bd(k, gamma, t_max, n0=int(round(k/gamma)), seed=seed)\n    # >>> TODO: return True if the count ever reached 0 during the run\n    raise NotImplementedError\n\nfrac5  = np.mean([touched_zero(5,  1.0, 20, s) for s in range(400)])\nfrac20 = np.mean([touched_zero(20, 1.0, 20, s) for s in range(400)])\nprint(f\"extinction frequency:   <n>=5 -> {frac5:.2f}      <n>=20 -> {frac20:.3f}\")"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# ✅ self-check\nassert frac5 > 0.05 and frac5 > frac20, \"expected extinction to be common at <n>=5, rare at <n>=20\"\nprint(\"PASSED \\u2705  discreteness at low copy number is not cosmetic\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Exercise 3 · The bistable toggle switch — build the propensities\nTwo mutually repressing genes $u,v$. Production is **Hill-repressed** by the *other* species, degradation is linear:\n$$a^{u}_{\\text{prod}}=\\frac{\\alpha}{1+n_v^{\\beta}},\\qquad a^{v}_{\\text{prod}}=\\frac{\\alpha}{1+n_u^{\\beta}},\\qquad a_{\\text{deg}}=n.$$\nFill in the 4-element propensity list in the order **[u+, u−, v+, v−]**. The rest of the SSA loop is provided.\n\n<details><summary>💡 Hint</summary>\n\n`a = [alpha/(1+v**beta), u, alpha/(1+u**beta), v]` — note each gene is repressed by the *other* one.\n</details>"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def ssa_switch(alpha, beta, t_max, seed=None):\n    r = np.random.default_rng(seed)\n    u, v, t = 10, 0, 0.0\n    T, U, V = [t], [u], [v]\n    while t < t_max:\n        # >>> TODO: build the propensity list in order [u+, u-, v+, v-]\n        # a = [ ... , ... , ... , ... ]\n        raise NotImplementedError\n        a0 = sum(a)\n        t += r.exponential(1/a0)\n        i = r.choice(4, p=np.array(a)/a0)     # which of the 4 events?\n        u += (i == 0) - (i == 1)\n        v += (i == 2) - (i == 3)\n        T.append(t); U.append(u); V.append(v)\n    return np.array(T), np.array(U), np.array(V)\n\nT, U, V = ssa_switch(12, 3.0, 4000, seed=1)\nfig, ax = plt.subplots(1, 2, figsize=(12,4))\nax[0].step(T, U, where='post', label='u'); ax[0].step(T, V, where='post', alpha=0.7, label='v')\nax[0].legend(); ax[0].set(xlabel='time', ylabel='copies', title='anti-correlated switching')\nax[1].hist(U, bins=40, density=True, orientation='horizontal', alpha=0.6)\nax[1].set(xlabel='P(n_u)', ylabel='n_u', title='bimodal: OFF / ON')\nplt.tight_layout()"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# ✅ self-check: the switch must visit BOTH an OFF (low u) and an ON (high u) state\nlo, hi = np.mean(U < 5), np.mean(U > 15)\nprint(f\"fraction of time  OFF (u<5) = {lo:.2f}    ON (u>15) = {hi:.2f}\")\nassert lo > 0.1 and hi > 0.1, \"the trajectory should dwell in both basins\"\nprint(\"PASSED \\u2705  noise drives transitions between two stable states\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Exercise 4 · The Moran process — a conserved mean that lies\n$N$ individuals, $n$ of type A. Neutral rates $W^+=W^-=\\tfrac{n}{N}\\!\\left(1-\\tfrac{n}{N}\\right)$, so $\\mathbb{E}[\\Delta n]=0$: the deterministic law predicts a **frozen** population. The truth is the opposite — the walk is absorbed at $n=0$ or $n=N$ with probability 1, and the **fixation probability equals $n_0/N$**.\n\nComplete the neutral step (up or down with equal probability), then verify the fixation law.\n\n<details><summary>💡 Hint</summary>\n\nSymmetric walk: `n += 1 if r.random() < 0.5 else -1`. The `while 0 < n < N` condition already encodes the absorbing walls.\n</details>"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def moran(N, n0, seed=None, t_max=1e6):\n    r = np.random.default_rng(seed)\n    n, t = n0, 0.0\n    while 0 < n < N and t < t_max:\n        w = (n/N)*(1 - n/N)            # W+ = W- = w\n        t += r.exponential(1/(2*w))\n        # >>> TODO: take one symmetric step (+1 or -1 with equal probability)\n        raise NotImplementedError\n    return n                            # final state: 0 or N\n\nN = 24\nfor n0 in (6, 12, 18):\n    fix = np.mean([moran(N, n0, seed=s) == N for s in range(600)])\n    print(f\"n0/N = {n0/N:.2f}   simulated fixation = {fix:.3f}\")"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# ✅ self-check: fixation probability must match n0/N\nfor n0 in (6, 12, 18):\n    fix = np.mean([moran(N, n0, seed=1000+s) == N for s in range(600)])\n    assert abs(fix - n0/N) < 0.06, f\"fixation off at n0={n0}\"\nprint(\"PASSED \\u2705  the ensemble mean is conserved, but every single run is absorbed\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Exercise 5 · (Stretch) Stochastic logistic growth & the size of noise\nBirth $W^+ = n$, death $W^- = n^2/K$. The deterministic logistic equation has a stable carrying capacity $K$ and can **never** reach 0 — but the stochastic model has $n=0$ as a unique absorbing state.\n\nImplement the SSA and show that **extinction is common at small $K$ and rare at large $K$** — the discrepancy is set by system size, not by the model.\n\n<details><summary>💡 Hint</summary>\n\nSame two-question structure as `ssa_bd`, with `wp, wm = n, n*n/K`. Start from `n = K` and stop when `n == 0` or `t > t_max`.\n</details>"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def logistic(K, t_max, seed=None):\n    r = np.random.default_rng(seed)\n    n, t = K, 0.0\n    while t < t_max and n > 0:\n        # >>> TODO: propensities wp (birth) and wm (death); one Gillespie step\n        raise NotImplementedError\n    return n     # 0 means the population went extinct\n\nfor K in (10, 50, 100, 1000):\n    ext = np.mean([logistic(K, 60, seed=s) == 0 for s in range(300)])\n    print(f\"K = {K:>4}   extinction fraction = {ext:.3f}\")"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# ✅ self-check: extinction risk must fall as K grows\ne_small = np.mean([logistic(10,  60, seed=s) == 0 for s in range(300)])\ne_big   = np.mean([logistic(1000,60, seed=s) == 0 for s in range(300)])\nassert e_small > e_big, \"small K should go extinct more often than large K\"\nprint(f\"PASSED \\u2705   small K -> {e_small:.2f},  large K -> {e_big:.2f}   (the ODE is the K->inf limit)\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "---\n### Going further\n- **Fano factor by hand:** for the birth–death process confirm $\\sigma^2/\\langle n\\rangle \\to 1$ as you increase the run length.\n- **First-passage times:** in the toggle switch, measure the mean dwell time in one state and watch it grow as you raise $\\alpha$ (a bigger barrier).\n- **Fixation time:** in the Moran process, time each run to absorption and check the mean scales like $N^2$.\n- **Everything here is a continuous-time Markov jump process** — the same SSA powers Blocks 2 (space) and 3 (hybrid methods)."
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.x"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}