{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# Block 2 \u2014 Extra Exercises \u00b7 Space: Patterns, Demes & Epidemic Waves\n### Bridging the Scales \u00b7 GEFENOL Summer School 2026 \u00b7 *Noise and Space in Biological Systems*\n\n**Fresh spatial problems \u2014 not the Fisher\u2013KPP front from the slides.** Complete each **>>> TODO** and delete the guard; each exercise ends with a \u2705 **self-check**.\n\n**New systems here:** **Turing patterns** (Schnakenberg activator\u2013inhibitor \u2014 diffusion *creating* structure), neutral **stepping-stone** coarsening (the Moran walk with geography), and a spatial **SIR epidemic wave**. Answers in *Block2_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 Turing patterns \u2014 diffusion that *builds* structure\nSchnakenberg kinetics, activator $u$ (slow diffusion) and inhibitor $v$ (fast diffusion):\n$$\\partial_t u = D_u\\partial_x^2 u + a - u + u^2 v,\\qquad \\partial_t v = D_v\\partial_x^2 v + b - u^2 v.$$\nThe homogeneous state $(u_0,v_0)=(a+b,\\;b/(a+b)^2)$ is stable to well-mixed perturbations but **unstable to patterned ones** when $D_v\\gg D_u$ \u2014 Turing's insight. Complete the reaction terms and the periodic Laplacian.\n\n<details><summary>\ud83d\udca1 Hint</summary>\n\n`fu = a - u + u*u*v`, `fv = b - u*u*v`. Periodic Laplacian: `np.roll(f,-1) - 2*f + np.roll(f,1)` over `dx**2`.\n</details>"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "a, b = 0.1, 0.9\nDu, Dv = 1.0, 40.0\nnx, dx = 200, 1.0\ndt = 0.2*dx**2/Dv                       # CFL-stable for the fast species\n\ndef lap(f):\n    # >>> TODO: periodic discrete Laplacian of f\n    raise NotImplementedError\n\ndef turing(nsteps=60000, seed=0):\n    rng = np.random.default_rng(seed)\n    u = (a+b) + 0.01*rng.standard_normal(nx)\n    v = b/(a+b)**2 + 0.01*rng.standard_normal(nx)\n    for _ in range(nsteps):\n        # >>> TODO: Schnakenberg reaction terms\n        # fu = ...\n        # fv = ...\n        raise NotImplementedError\n        u = u + dt*(Du*lap(u) + fu)\n        v = v + dt*(Dv*lap(v) + fv)\n    return u, v\n\nu, v = turing()\nplt.plot(np.arange(nx)*dx, u, label='activator u')\nplt.axhline(a+b, ls='--', color='k', lw=1, label='homogeneous $u_0$')\nplt.xlabel('x'); plt.ylabel('u'); plt.legend(); plt.title('a stationary Turing pattern');"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# \u2705 self-check: a genuine pattern must emerge (large spatial contrast, finite wavelength)\ncontrast = u.max() - u.min()\nspec = np.abs(np.fft.rfft(u - u.mean()))\nkdom = np.argmax(spec)                    # dominant wavenumber index\nprint(f\"pattern contrast (max-min u) = {contrast:.2f}    dominant mode k = {kdom}\")\nassert contrast > 0.3, \"expected a strong stationary pattern, not a flat profile\"\nassert 1 <= kdom <= nx//2 - 1, \"the pattern should have a finite, non-zero wavelength\"\nprint(\"PASSED \\u2705  diffusion made structure \u2014 the Turing instability\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Exercise 2 \u00b7 Stepping-stone \u2014 the Moran walk with geography\n$V$ demes in a row, each with $N$ haploid individuals of two neutral alleles. Track $n_i$ = count of allele A in deme $i$. Each step: (1) **migration** \u2014 with probability $mig$ a deme swaps one individual with a random neighbour; (2) **local drift** \u2014 resample each deme by binomial sampling at its current frequency. With no selection, single-allele **domains coarsen** and grow.\n\nComplete the local-drift resampling.\n\n<details><summary>\ud83d\udca1 Hint</summary>\n\nLocal Wright\u2013Fisher drift: `n = rng.binomial(N, n/N)` \u2014 each deme is resampled at its own current frequency.\n</details>"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def domain_walls(n, N):\n    f = n/N\n    return np.sum(np.abs(np.sign(f[1:]-0.5) - np.sign(f[:-1]-0.5)) > 0)\n\ndef stepping_stone(V=200, N=20, mig=0.1, gens=400, seed=0):\n    rng = np.random.default_rng(seed)\n    n = rng.integers(0, N+1, V)               # random start\n    walls = [domain_walls(n, N)]\n    for _ in range(gens):\n        # migration: exchange with the right neighbour where a coin says so\n        move = rng.random(V) < mig\n        shift = np.where(move, np.roll(n, -1), n)\n        n = ((n + shift)//2).astype(int)\n        # >>> TODO: local Wright-Fisher drift \u2014 resample each deme at its frequency n/N\n        raise NotImplementedError\n        walls.append(domain_walls(n, N))\n    return n, np.array(walls)\n\nn, walls = stepping_stone(seed=3)\nplt.plot(walls); plt.xlabel('generation'); plt.ylabel('number of domain walls')\nplt.title('neutral domains coarsen: fewer, larger patches over time');"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# \u2705 self-check: the number of domain boundaries must DECREASE (patches coarsen)\nearly = walls[:20].mean()\nlate  = walls[-20:].mean()\nprint(f\"domain walls: early = {early:.1f}   late = {late:.1f}\")\nassert late < 0.6*early, \"neutral coarsening should sharply reduce the number of domains\"\nprint(\"PASSED \\u2705  drift + geography = coarsening (absorbing states with a map)\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Exercise 3 \u00b7 A spatial SIR wave \u2014 how fast does an epidemic travel?\nSIR on a 1-D lattice, infected individuals diffuse with coefficient $D$. In each voxel, densities $s,i,r$ obey $\\dot s=-\\beta s i,\\ \\dot i=\\beta s i-\\gamma i,\\ \\dot r=\\gamma i$, and $i$ diffuses. A localised seed launches a **travelling wave** of infection with speed $\\approx 2\\sqrt{D\\,(\\beta-\\gamma)}$ for $R_0=\\beta/\\gamma>1$.\n\nComplete the reaction terms and the $i$-diffusion update.\n\n<details><summary>\ud83d\udca1 Hint</summary>\n\n`ds=-beta*s*i`, `di=beta*s*i-gamma*i`, `dr=gamma*i`. Only `i` diffuses: `i += dt*D*lap(i)` on top of the reaction.\n</details>"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "nx2, dx2 = 600, 1.0\ndef lapN(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/dx2**2\n\ndef sir_wave(beta, gamma, D, nsteps=800, record=20):\n    dt = 0.2*dx2**2/D\n    s = np.ones(nx2); i = np.zeros(nx2); r = np.zeros(nx2)\n    i[:5] = 0.4; s[:5] = 0.6                 # seed on the left\n    front = []\n    for step in range(nsteps):\n        # >>> TODO: SIR reaction terms ds, di, dr\n        raise NotImplementedError\n        s = s + dt*ds\n        # >>> TODO: update i with its reaction AND diffusion\n        # i = i + dt*(di + D*lapN(i))\n        raise NotImplementedError\n        r = r + dt*dr\n        if step % record == 0:\n            idx = np.where(i > 0.05)[0]\n            front.append((step*dt, idx.max()*dx2 if len(idx) else 0.0))\n    return np.array(front)\n\nfr = sir_wave(2.0, 1.0, 1.0)\nt, pos = fr[:,0], fr[:,1]\nm = t > t.max()*0.4\nspeed = np.polyfit(t[m], pos[m], 1)[0]\nprint(f\"measured wave speed = {speed:.3f}   (theory 2*sqrt(D(beta-gamma)) = {2*np.sqrt(1.0*(2.0-1.0)):.3f})\")\nplt.plot(t, pos); plt.xlabel('time'); plt.ylabel('infection front'); plt.title('the epidemic travels as a wave');"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# \u2705 self-check: the wave advances at a finite speed, faster when beta grows\ns_slow = np.polyfit(*(lambda f:(f[f[:,0]>f[:,0].max()*0.4][:,0], f[f[:,0]>f[:,0].max()*0.4][:,1]))(sir_wave(1.5,1.0,1.0)), 1)[0]\ns_fast = np.polyfit(*(lambda f:(f[f[:,0]>f[:,0].max()*0.4][:,0], f[f[:,0]>f[:,0].max()*0.4][:,1]))(sir_wave(3.0,1.0,1.0)), 1)[0]\nprint(f\"speed(beta=1.5) = {s_slow:.3f}    speed(beta=3.0) = {s_fast:.3f}\")\nassert s_slow > 0 and s_fast > s_slow, \"a more transmissible pathogen should travel faster\"\nprint(\"PASSED \\u2705  reaction + diffusion = a travelling epidemic wave\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "---\n### Going further\n- **Turing wavelength:** sweep $D_v/D_u$ in Exercise 1 and watch the dominant mode $k$ shift \u2014 the fastest-growing wavelength sets the spacing.\n- **Coarsening law:** in Exercise 2, the typical domain size grows like $\\sqrt{t}$ (diffusive coarsening) \u2014 plot mean patch length vs generation.\n- **Stochastic wave:** put the SIR wave on a discrete lattice (Block 2 recipe) and measure the Brunet\u2013Derrida slow-down of the epidemic front.\n- All three reuse the same reaction\u2013diffusion machinery from the slides \u2014 only the reactions change."
  }
 ],
 "metadata": {
  "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},
  "language_info": {"name": "python", "version": "3.x"}
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
