{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# Block 1 \u2014 Extra Exercises \u00b7 Noise & the Exact SSA\n### Bridging the Scales \u00b7 GEFENOL Summer School 2026 \u00b7 *Noise and Space in Biological Systems*\n\n**Fresh problems \u2014 not the ones from the slides.** Same toolbox (the *when? / which?* Gillespie SSA), new biology. Complete each **>>> TODO** and delete the *raise NotImplementedError* guard; every exercise ends with a \u2705 **self-check** that should print **PASSED**.\n\n**New systems here:** transcriptional **bursting** (two-stage gene expression, Fano > 1), a stochastic **SIR outbreak** (fizzle vs epidemic), and **negative autoregulation** as a noise-suppressor. Worked answers in *Block1_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})"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Exercise 1 \u00b7 Transcriptional bursting \u2014 why proteins are noisier than Poisson\nTwo-stage gene expression with **four** reactions:\n$$\\varnothing\\xrightarrow{k_m} m,\\quad m\\xrightarrow{\\gamma_m}\\varnothing,\\quad m\\xrightarrow{k_p} m+p,\\quad p\\xrightarrow{\\gamma_p}\\varnothing.$$\nEach mRNA is translated many times before it decays, so proteins arrive in **bursts**. The protein Fano factor is $\\;F_p = 1 + \\dfrac{k_p}{\\gamma_m+\\gamma_p} > 1\\;$ \u2014 super-Poissonian.\n\nBuild the 4-element propensity list in order **[m+, m\u2212, p+, p\u2212]**.\n\n<details><summary>\ud83d\udca1 Hint</summary>\n\n`a = [k_m, gm*m, kp*m, gp*p]`. Translation `p+` fires at rate proportional to the *current* mRNA count `m`.\n</details>"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def ssa_gene(k_m, gm, kp, gp, t_max, seed=None):\n    r = np.random.default_rng(seed)\n    m, p, t = 0, 0, 0.0\n    T, M, P = [t], [m], [p]\n    while t < t_max:\n        # >>> TODO: propensity list in order [m+, m-, p+, p-]\n        # a = [ ... , ... , ... , ... ]\n        raise NotImplementedError(\"build the 4 propensities, then delete this line\")\n        a0 = sum(a)\n        if a0 == 0:\n            break\n        t += r.exponential(1/a0)\n        i = r.choice(4, p=np.array(a)/a0)\n        m += (i == 0) - (i == 1)\n        p += (i == 2) - (i == 3)\n        T.append(t); M.append(m); P.append(p)\n    return np.array(T), np.array(M), np.array(P)\n\nT, M, P = ssa_gene(2.0, 1.0, 8.0, 1.0, 4000, seed=1)\nplt.step(T, M, where='post', label='mRNA m'); plt.step(T, P, where='post', alpha=0.7, label='protein p')\nplt.xlabel('time'); plt.ylabel('copies'); plt.legend(); plt.title('bursty protein production');"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# \u2705 self-check: protein Fano factor must exceed 1 (bursting), and match 1 + kp/(gm+gp)\nk_m, gm, kp, gp = 2.0, 1.0, 8.0, 1.0\ntails = []\nfor s in range(40):\n    _, _, P = ssa_gene(k_m, gm, kp, gp, 300, seed=s)\n    tails.append(P[len(P)//2:])          # discard the transient\np = np.concatenate(tails)\nfano = p.var()/p.mean()\npred = 1 + kp/(gm+gp)\nprint(f\"protein Fano = {fano:.2f}   (theory 1 + kp/(gm+gp) = {pred:.2f})\")\nassert fano > 1.5, \"proteins should be clearly super-Poissonian\"\nprint(\"PASSED \\u2705  bursting makes the protein noisier than any Poisson source\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Exercise 2 \u00b7 Stochastic SIR \u2014 the same $R_0$, two destinies\nA closed population of $N$ with $S+I+R=N$. Two reactions:\n$$S+I\\xrightarrow{\\beta/N} 2I \\quad(a_{\\text{inf}}=\\tfrac{\\beta}{N}SI),\\qquad I\\xrightarrow{\\gamma} R \\quad(a_{\\text{rec}}=\\gamma I).$$\nStart from a **single** infected. Even with $R_0=\\beta/\\gamma>1$, many outbreaks *fizzle* (the first case recovers before infecting anyone); the rest explode. The final size $R(\\infty)$ is **bimodal**.\n\nComplete the two propensities and the state updates.\n\n<details><summary>\ud83d\udca1 Hint</summary>\n\nInfection: `S-=1; I+=1`. Recovery: `I-=1; R+=1`. Stop when `I==0`. Probability of a *major* outbreak from one case is $1-1/R_0$.\n</details>"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def ssa_sir(N, beta, gamma, I0=1, seed=None):\n    r = np.random.default_rng(seed)\n    S, I, R = N - I0, I0, 0\n    while I > 0:\n        # >>> TODO: infection and recovery propensities\n        # a_inf = ...\n        # a_rec = ...\n        raise NotImplementedError\n        a0 = a_inf + a_rec\n        if r.random()*a0 < a_inf:\n            S -= 1; I += 1     # infection\n        else:\n            I -= 1; R += 1     # recovery\n    return R                   # final epidemic size\n\nN, beta, gamma = 400, 3.0, 1.0     # R0 = 3\nsizes = np.array([ssa_sir(N, beta, gamma, seed=s) for s in range(2000)])\nplt.hist(sizes, bins=40); plt.xlabel('final size R(inf)'); plt.ylabel('runs')\nplt.title(f'bimodal outcomes, R0 = {beta/gamma:.0f}');"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# \u2705 self-check: outcomes are bimodal, and P(major outbreak) approx 1 - 1/R0\nR0 = beta/gamma\nfrac_major = np.mean(sizes > 0.1*N)\nfrac_fizzle = np.mean(sizes < 10)\nprint(f\"major outbreaks = {frac_major:.2f}   (theory 1-1/R0 = {1-1/R0:.2f})    fizzles = {frac_fizzle:.2f}\")\nassert frac_major > 0.1 and frac_fizzle > 0.1, \"expected BOTH fizzles and major outbreaks\"\nassert abs(frac_major - (1-1/R0)) < 0.1, \"major-outbreak probability should be near 1 - 1/R0\"\nprint(\"PASSED \\u2705  same parameters, discrete chance decides fizzle vs epidemic\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Exercise 3 \u00b7 Negative autoregulation suppresses noise\nA protein that **represses its own gene** reacts faster to fluctuations. Compare two circuits at the *same mean*:\n- **constitutive:** production $\\alpha$, degradation $n$;\n- **autoregulated:** production $\\dfrac{\\alpha_0}{1+(n/K)^h}$, degradation $n$.\n\nImplement one generic SSA that takes a **production-rate function** `prod(n)` and returns the trajectory; then compare Fano factors.\n\n<details><summary>\ud83d\udca1 Hint</summary>\n\nTwo reactions only: birth at `prod(n)`, death at `n`. `a0 = prod(n) + n`; birth if `r.random()*a0 < prod(n)`.\n</details>"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def ssa_feedback(prod, t_max, n0=10, seed=None):\n    r = np.random.default_rng(seed)\n    n, t = n0, 0.0\n    ns, ts = [n], [t]\n    while t < t_max:\n        birth = prod(n)\n        death = n\n        a0 = birth + death\n        if a0 == 0:\n            break\n        # >>> TODO: advance time by Exp(a0), then birth (+1) with prob birth/a0 else death (-1)\n        raise NotImplementedError\n        ns.append(n); ts.append(t)\n    return np.array(ts), np.array(ns)\n\n# constitutive tuned to mean ~ 20; autoregulated tuned to the SAME mean\nconst  = lambda n: 20.0\nauto   = lambda n: 60.0/(1 + (n/18.0)**4)\n\ndef fano_of(prod):\n    tails = []\n    for s in range(30):\n        _, n = ssa_feedback(prod, 400, seed=s)\n        tails.append(n[len(n)//2:])\n    x = np.concatenate(tails)\n    return x.mean(), x.var()/x.mean()\n\nm_c, f_c = fano_of(const)\nm_a, f_a = fano_of(auto)\nprint(f\"constitutive:  mean={m_c:.1f}  Fano={f_c:.2f}\")\nprint(f\"autoregulated: mean={m_a:.1f}  Fano={f_a:.2f}\")"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# \u2705 self-check: at matched mean, negative feedback must LOWER the Fano factor\nassert abs(m_c - m_a) < 4, \"means should be comparable for a fair test\"\nassert f_a < f_c, \"autoregulation should reduce the noise\"\nprint(f\"PASSED \\u2705  feedback cuts Fano from {f_c:.2f} to {f_a:.2f} at the same mean\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "---\n### Going further\n- **Burst-size distribution:** in Exercise 1, count how many `p+` events happen per mRNA lifetime \u2014 it is geometric with mean $k_p/\\gamma_m$.\n- **Outbreak threshold:** sweep $R_0$ in Exercise 2 across 1 and watch the major-outbreak branch appear exactly at $R_0=1$.\n- **Hill coefficient:** raise $h$ in Exercise 3 and see the noise drop further \u2014 stronger feedback, tighter control.\n- All three are continuous-time Markov jump processes \u2014 the same engine as Blocks 2 and 3."
  }
 ],
 "metadata": {
  "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},
  "language_info": {"name": "python", "version": "3.x"}
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
