{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WuK2xG5ohjnw"
   },
   "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": 2,
   "metadata": {
    "id": "wBv_INPghjn1"
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/0n/3fx_dk3974l5gcd61jbvt2200000gr/T/ipykernel_4471/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": {
    "id": "muF1o4x8hjn3"
   },
   "source": [
    "# Linear 2D systems and random gene networks"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "KWxVioQQhjn3"
   },
   "source": [
    "The goal of this exercise is to understand the fixed points and their\n",
    "stability in linear 2D systems. This will be the basis for the analysis\n",
    "of nonlinear 2D systems. The general form of a linear system in 2D can be written as: \n",
    "\n",
    "\\begin{equation}\n",
    "x'=ax+by\n",
    "\\end{equation}\n",
    "\n",
    "\\begin{equation}\n",
    "y'=cx+dy\n",
    "\\end{equation}\n",
    "\n",
    "$ \\; a,b,c,d\\in\\mathbb{R}$\n",
    "The general solution can be written as \n",
    "$$\n",
    "\\boldsymbol{X}(t)=c_{1}\\boldsymbol{v}_{1}e^{\\lambda_{1}t}+c_{2}\\boldsymbol{v}_{2}e^{\\lambda_{2}t}\n",
    "$$\n",
    " where $\\boldsymbol{X}(t)=(x(t),y(t))$. Here, $c_{i}$ are the coefficients and\n",
    "$\\boldsymbol{v}_{i}$ are the eigenvectors of the matrix $M=\\begin{pmatrix}a & b\\\\\n",
    "c & d\n",
    "\\end{pmatrix}$ with eigenvalues $\\lambda_{i}$. Notice that the eigenvalues, eigenvectors,\n",
    "and coefficients can be complex numbers. For the notation, we use $\\tau = trace(M)$ and $\\Delta = det(M)$.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "J6bBDTdDhjn4"
   },
   "source": [
    "## An unstable fixed point in 2D (Paper and pencil & Python)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8idbSN6Ohjn4"
   },
   "source": [
    "Consider the 2-dimensional linear system\n",
    "\n",
    "$$\n",
    "\\begin{array}{c}\n",
    "x'=3x+y\\\\\n",
    "y'=2x+2y\n",
    "\\end{array}\n",
    "$$\n",
    "\n",
    "\n",
    "**1. Write this system in matrix form. Compute the eigenvalues and the corresponding eigenvectors.**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "w0DnG1I6hjn6"
   },
   "source": [
    "**2. Write down the general solution for this system.**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "pSMuyWM7hjn7"
   },
   "source": [
    "**3. Discuss the stability of the fixed point $\\left(0,0\\right)$.**\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "XF_-IcKxhjn8"
   },
   "source": [
    "**4. Compute the trajectory for the initial condition $\\left(x_{0},y_{0}\\right)=\\left(5,3\\right)$ at $t=0$.\n",
    "Discuss its properties.**\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "tBzpsjw1hjn9"
   },
   "source": [
    "**5. Sketch the vector field BY HAND for this system and represent the trajectory\n",
    "from 4. Start by sketching the eigenvectors, calculating and sketching\n",
    "the nullclines. What are the properties of a vector field along the\n",
    "nullclines? Complete the vector field using these properties.**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "vR_7QwzHhjn-"
   },
   "source": [
    "**6. Verify your sketch using the function np.quiver in conjunction with np.meshgrid (look at the Documentation)**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "0HKduyCghjoA"
   },
   "source": [
    "## Fixed point properties of random 2 genes network (Python)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "qwS5H8WphjoA"
   },
   "source": [
    "The goal of this exercise is to practice your Python programming while writing modular code that you will be able to reuse in the next sessions.\n",
    "\n",
    "Assume that the activities of genes $x$ and $y$ influence each other according to the following simplified linear model\n",
    "\n",
    "$$\n",
    "\\begin{pmatrix}\n",
    "\\dot x\\\\\n",
    "\\dot y\n",
    "\\end{pmatrix}\n",
    "=\\begin{pmatrix}a & b\\\\\n",
    "c & d\n",
    "\\end{pmatrix}\\begin{pmatrix}x\\\\\n",
    "y\n",
    "\\end{pmatrix}=M\\begin{pmatrix}x\\\\\n",
    "y\n",
    "\\end{pmatrix}\n",
    "$$\n",
    "\n",
    "in which the parameters $a,b,c,d$ are taken as random real numbers.\n",
    "Explore the stability properties\n",
    "of the fixed point $(0,0)$ in this model.\n",
    "\n",
    "_Remark_: Ignore for a while that this model may not be very realistic to describe biochemical processes.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "E9TQ-KKxhjoB"
   },
   "source": [
    "**1. Write a function named `stability` which determines, based on the interaction matrix $M$, the stability of the fixed point $(0, 0)$.**\n",
    "\n",
    "Indices:\n",
    "\n",
    "* This function should take one input argument `M` and output one argument `type_fp`. \n",
    "\n",
    "* It should compute the trace $\\tau$ and the determinant $\\Delta$ of `M`.\n",
    "\n",
    "* With control statements (if, elif, else), it should determine the stability (stable or unstable fixed points, saddle points, stable or unstable spirals) of the fixed point using the classification scheme below and return it as a string in the variable `type_fp`.\n",
    "\n",
    "* You can reduce the number of logical tests by separating the fixed points _vs_ spiral _vs_ saddle and stable _vs_ unstable decision and concatenating the two resulting strings.\n",
    "\n",
    "_Hint: use the trace and determinant of the matrix as illustrated in the figure below._\n",
    "![](trace_det_ex_4.png \"Title\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "VW4vBA6KhjoB"
   },
   "source": [
    "**2. Test your code using the matrix provided in Exercise 1 above.**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "iBuOCgu6hjoC"
   },
   "source": [
    "**3. Let's now sample randomly the possible values of $M$ and determine the proportion of each type of fixed point.**\n",
    "\n",
    "Write a script that allows you to generate N different random matrices. Your script can perform the following steps: \n",
    "1. For the matrix entries (2x2 matrix), use a uniform distribution on the interval $[-1,1]$. You can use the function  `np.random.rand()` (look at the Documentation)\n",
    "2. As an output of your result, you can generate a histogram showing the different type of fixed points found.\n",
    "3. Test your code for 200 samples. Then, increase this value. Which proportions do you find?"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "colab": {
   "collapsed_sections": [],
   "name": "Solution 4.ipynb",
   "provenance": []
  },
  "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.8.13"
  },
  "title": "Exercise 4: Linear 2D systems and random gene networks"
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
