{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### **Course**: BIO-341 [_Dynamical systems in biology_](https://moodle.epfl.ch/course/info.php?id=14291)\n",
    "\n",
    "**Professor**: _Julian Shillcock_ & _Felix Naef_\n",
    "\n",
    "SSV, BA5, 2025\n",
    "\n",
    "Note that this document is primarily aimed at being consulted as a Jupyter notebook, the PDF rendering being not optimal."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/yf/q5hy0j9s5td1mjcljsx68fxh0000gq/T/ipykernel_45180/3074590393.py:8: DeprecationWarning: `set_matplotlib_formats` is deprecated since IPython 7.23, directly use `matplotlib_inline.backend_inline.set_matplotlib_formats()`\n",
      "  set_matplotlib_formats('png', 'pdf')\n"
     ]
    }
   ],
   "source": [
    "#import important libraries\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from ipywidgets import interact\n",
    "from scipy.integrate import odeint\n",
    "from IPython.display import set_matplotlib_formats\n",
    "from matplotlib.markers import MarkerStyle\n",
    "set_matplotlib_formats('png', 'pdf')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Insect outbreak and bifurcations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The goal of this exercise is to study a model of insect outbreak in which the solutions change qualitatively when the environment parameters are modified. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Bifurcations (Paper and pencil)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Consider the 1st-order systems\n",
    "\n",
    "1. $\\dot{x} = (x-2)(x-r)$\n",
    "\n",
    "2. $\\dot{x} = x^2 + b$\n",
    "\n",
    "**A. Discuss the fixed points and their stability in function of the parameters $r$ or $b$.**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**B. Linearize the equation for the dynamical system to obtain explicit solution near the fixed points. Linearization refers to finding the linear approximation to a function at a given point:**  $\\dot{\\eta} = \\eta \\cdot F'(x^*)$ with $\\eta(t) = x(t) - x^*$ and the solution $\\eta = \\eta_0e^{tF'(x^*)}$ "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**C. Bifurcation diagrams: Plot the position of the fixed points in function of $r$ or $b$, using a solid line for the stable branch and a dashed line for unstable branch.**\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Insect outbreak (épidémie) (paper and pencil & code)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](Choristoneura_fumiferana_larva_small.jpg \"Title\")\n",
    "\n",
    "_La tordeuse des bourgeons de l'épinette (Choristoneura fumiferana), communément appelée T.B.E., est sans contredit l'insecte ravageur le plus connu des forestiers et du grand public. Ayant été très présente dans les forêts québécoises durant les années 60 et 70, la T.B.E. ne s'est pas attirée la sympathie de la population. En effet, les dommages qui lui sont attribuables au cours de la dernière épidémie représentent plus de 235 millions de mètres cubes de bois, soit l'équivalent de dix années de récolte pour l'industrie forestière. Inutile de dire que la tordeuse des bourgeons de l'épinette a considérablement modifié le paysage forestier de plusieurs coins du Québec._\n",
    "\n",
    "\n",
    "\n",
    "During an epidemy, the spruce budworm can defoliate and kill entire forests within few years. In a simple model for the insect population $N$, the available foliage allows for a relative growth rate $r_B$ and the environment has a maximal capacity $K$ as in the logistic growth model. At the same time, insects are eaten by birds at a certain rate, which leads to the population model:\n",
    "\n",
    "$$\n",
    "\\dot N = \\dfrac{dN}{dt}= r_B N (1-\\frac{N}{K}) - p(N)\n",
    "$$\n",
    "    \n",
    "The death rate $p(N)$ is assumed to take the form:\n",
    "\n",
    "$$\n",
    "p(N) = B\\frac{N^2}{A^2 + N^2} \\; \\text{with} \\: A,B >0\n",
    "$$\n",
    "    \n",
    "This term is small when the budworms population is small and the birds seek for food elsewhere, and then saturates for larger $N$ when all birds eat as much worms as they can."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**A. Plot the function $p(N)$ and discuss the meaning of the parameters $A$ and $B$.**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**B. Discuss the fixed points and stability properties of this model in function of $r$ and $k$ by the following steps:** \n",
    "\t\t\n",
    "1) For convenience, let's first change variables: $x = \\dfrac{N}{A}, \\; r=r_B \\;\\dfrac{A}{B}, \\; k=\\dfrac{K}{A}, \\; \\tau = \\dfrac{Bt}{A}$.  \n",
    "Verify that this leads to the dimensionless form with two dimensionless parameters $r,k$. \n",
    "$$\n",
    "\\dfrac{dx}{d\\tau} = r x (1-\\frac{x}{k}) - \\frac{x^2}{1+x^2} = x(f(x) - h(x))\n",
    "$$\t\t\t\t"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2) Consider the following three qualitatively different situations and plot in each case the two terms $f(x)= r(1-\\dfrac{x}{k})$ and $h(x)= \\dfrac{x}{1+x^2}$ in function of x. Note that the intersections correspond to the fixed points (cf. the genetic switch in Chapter 2).\t\t\t\n",
    "  * intermediate $r$, intermediate $k$ (one fixed point, called the refuge)\n",
    "  * small $r$  , large $k$  (3 fixed points, called the bistable region)\n",
    "  * large $r$  , large $k$  (one fixed points, called the outbreak).\n",
    "  \n",
    "Hint: Here, small will be less than 1, intermediate will be around 1, and large will be more than 2. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "3) For each situation sketched previously (small, intermediate and large $r$), plot $\\dfrac{dx}{d\\tau}$ in function of $x$ and characterize the stability of the fixed points."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**C. Bifurcation diagram: Find the boundaries in the ($r,k$)-plane between the single and triple fixed points regions. Proceed stepwise:** \n",
    "\n",
    "1) Express mathematically the requirement that the two curves $f(x)=r(1-\\dfrac{x}{k})$ and $h(x)= \\dfrac{x}{1+x^2}$ are _tangent_. Use this requirement to express $r,k$ at the tangents in function of $x$. (Control: $r(x) = \\dfrac{2x^3}{(1+x^2)^2}$ and $k(x) = \\dfrac{-2x^3}{(1-x^2)}$ ).  \n",
    "Hint: To be tangent, the values of the curves and the derivatives must be equal at the *touching* points $x$.\n",
    "\t\t\t\n",
    "\t\t\t\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2) Plot the bifurcation diagram with Python, that means plot $(r(x^*),k(x^*))$ pairs of the tangent in the $(r,k)$ plane for $x^* \\in [1,\\infty]$. Use axis-limits $r \\in [0,1]$ and $k \\in [0,10]$.  \n",
    "\t\t\t\n",
    "**Notice**: since the capacity parameter $k$ is positive, $x$ is restricted to $x^* \\in [1,\\infty]$. That means that there are no tangential contacts between the two curves for the other values of $x^{*}$."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "3) **A biological catastrophe**: Bistability and hysteresis. Sketch what happens to a budworm population that lives in an environment where the growth rate $r$ is low, then slowly increases to high values, and finally decreases again to its low value (consider and compare the two cases $k=7$ and $k=3$). Assume that the budworm population equilibrates very fast when the environment changes (it is always at a fixed point) and that it is initially in its low (refuge) state. Use the representation of $f(x)$ and $h(x)$ similar as in B.2 to plot the results and to explain the behavior through time of the population of budworms.  \n",
    "__Hint__: Vary $r$  while keeping $k$  constant in your results of B.2\n",
    "\t\t\t\n",
    "\t\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\t\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  },
  "title": "Exercise 3: Insect outbreak and bifurcations"
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
