TITLE: Data Analysis and Machine Learning: Introduction and Representing data AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University DATE: today !split ===== Introduction ===== Statistics, data science and machine learning form important fields of research in modern science. They describe how to learn and make predictions from data, as well allowing us to extract inportant correlations about physical process and the underlying laws of motion in large data sets. The latter, big data sets, is now more and more frequent in essentially all disciplines, from the traditional Science, Technology, Mathematics and Engineering fields to the Humanities and the Social Sciences. It has become more and more common to see research projects on big data in for example the Social Sciences. Having a solid grasp of data analysis and machine learning is thus becoming central to scientific computing in many fields. Competences and skills within the fields of machine learning and scientific computing are nowadays strongly requested by many potential employers. The latter cannot be overstated, familiarity with machine learning has almost become a prerequisite for many of the most exciting employment opportunities, whether they are in bioinformatics, life science, physics or finance, in the private or the public sector. This author has had several students or met students who have been hired recently based on their skills and competences in scientific computing and data science, often with marginal knowledge of machine learning. Machine learning is a subfield of computer science, and is closely related to computational statistics. It evolved from the study of pattern recognition in artificial intelligence (AI) research, and has made contributions to AI tasks like computer vision, natural language processing and speech recognition. Machine learning represents the science of giving computers the ability to learn without being explicitly programmed. The idea is that there exist generic algorithms which can be used to find patterns in a broad class of data sets without having to write code specifically for each problem. The algorithm will build its own logic based on the data. Machine learning is an extremely rich field, in spite of its age. The increases we have seen during the last three decades in computational capabilities have been followed by a large development in methods and techniques for analyzing and handling large date sets, relying heavily on statistics, computer science and mathematics. The field is rather new and developing rapidly. Popular software packages written in Python for machine learning like _Scikit-learn, Tensorflow and PyTorch_, all freely available at their respective GitHub sites, encompass communities of developers in the thousands. And the number of code developers and contributors keep increasing. Not all the algorithms and methods can be given a rigorous mathematical justification, opening up thereby large rooms for experimenting and trial and error. However, a solid command of linear algebra, multivariate theory, probability theory, statistical data analysis, understanding errors and Monte Carlo methods are central elements in a proper understanding of many of algorithms and methods we will discuss. !split ===== Types of Machine Learning ===== The approaches to machine learning are many, but are often split into two main categories. In *supervised learning* we know the answer to a problem, and let the computer deduce the logic behind it. On the other hand, *unsupervised learning* is a method for finding patterns and relationship in data sets without any prior knowledge of the system. Some authours also operate with a third category, namely *reinforcement learning*. This is a paradigm of learning inspired by behavioral psychology, where learning is achieved by trial-and-error, solely from rewards and punishment. Another way to categorize machine learning tasks is to consider the desired output of a system. Some of the most common tasks are: * Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is typically supervised learning. * Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values. * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning. !split ===== Different algorithms ===== The methods we cover have three main topics in common, irrespective of whether we deal with supervised or unsupervised learning. The first ingredient is normally our data set, the second is a model which is normally a function of some parameters. The last ingredient is a so-called _cost_ function which allows us to present an estimate on how good our model is in reproducing the data it is supposed to train. In this series of lectures we will build our machine learning approach on a statistical foundation, with elements from data analysis, stochastic processes etc before we proceed with the following machine learning algorithms o Linear regression and its variants, in essence polynomial regression o Decision tree algorithms, from simpler to more complex ones o Nearest neighbors models o Bayesian statistics and regression o Support vector machines and finally various variants of o Artifical neural networks and deep learning Before we proceed however, there are several practicalities with data analysis and software tools we would like to present. These tools will help us in our understanding of various machine learning algorithms. Our emphasis here is on understanding the mathematical aspects of different algorithms, however, where possible we will emphasize the importance of using available software. !split ===== Software and needed installations ===== We will make intensive use of python as programming language and the myriad of available libraries. Furthermore, you will find IPython/Jupyter notebooks invaluable in your work. You can run _R_ codes in the Jupyter/IPython notebooks, with the immediate benefit of visualizing your data. If you have Python installed (we recommend Python3) and you feel pretty familiar with installing different packages, we recommend that you install the following Python packages via _pip_ as o pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow For Python3, replace _pip_ with _pip3_. For OSX users we recommend also, after having installed Xcode, to install _brew_. Brew allows for a seamless installation of additional software via for example o brew install python3 For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution you can use _pip_ as well and simply install Python as o sudo apt-get install python3 (or python for pyhton2.7) etc etc. !split ===== Python installers ===== If you don't want to perform these operations separately, we recommend two widely used distrubutions which set up all relevant dependencies for Python, namely o "Anaconda":"https://docs.anaconda.com/" Anaconda is an open source distribution of the Python and R programming languages for large-scale data processing, predictive analytics, and scientific computing, that aims to simplify package management and deployment. Package versions are managed by the package management system _conda_ o "Enthought canopy":"https://www.enthought.com/product/canopy/" is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license. !split ===== Installing R, C++, cython or Julia ===== You will also find it convenient to utilize R. Jupyter/Ipython notebook allows you run _R_ code interactively in your browser. The software library _R_ is tuned to statistically analysis and allows for an easy usage of the tools we will discuss in these texts. To install _R_ with Jupyter notebook "following the link here":"https://mpacer.org/maths/r-kernel-for-ipython-notebook" !split ===== Installing R, C++, cython or Julia ===== For the C++ affecianodas, Jupyter/IPython notebook allows you also to install C++ and run codes written in this language interactively in the browser. Since we will emphasize writing many of the algorithms yourself, you can thus opt for either Python or C++ as programming languages. To add more entropy, _cython_ can also be used when running your notebooks. It means that Python with the Jupyter/IPython notebook setup allows you to integrate widely popular softwares and tools for scientific computing. With its versatility, including symbolic operations, Python offers a unique computational environment. Your Jupyter/IPython notebook can easily be converted into a nicely rendered _PDF_ file or a Latex file for further processing. For example, convert to latex as !bc pycod jupyter nbconvert filename.ipynb --to latex !ec If you use the light mark-up language _doconce_ you can convert a standard ascii text file into various HTML formats, ipython notebooks, latex files, pdf files etc. !split ===== Introduction to Jupyter notebook and available tools ===== !bblock !bc pycod import numpy as np import matplotlib.pyplot as plt from scipy import sparse import pandas as pd from IPython.display import display eye = np.eye(4) print(eye) sparse_mtx = sparse.csr_matrix(eye) print(sparse_mtx) x = np.linspace(-10,10,100) y = np.sin(x) plt.plot(x,y,marker='x') plt.show() data = {'Name': ["John", "Anna", "Peter", "Linda"], 'Location': ["Nairobi", "Napoli", "London", "Buenos Aires"], 'Age':[51, 21, 34, 45]} data_pandas = pd.DataFrame(data) display(data_pandas) !ec !eblock !split ===== Representing data, more examples ===== !bblock !bc pycod import numpy as np import matplotlib.pyplot as plt from scipy import sparse import pandas as pd from IPython.display import display import mglearn import sklearn from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor x, y = mglearn.datasets.make_wave(n_samples=100) line = np.linspace(-3,3,1000,endpoint=False).reshape(-1,1) reg = DecisionTreeRegressor(min_samples_split=3).fit(x,y) plt.plot(line, reg.predict(line), label="decision tree") regline = LinearRegression().fit(x,y) plt.plot(line, regline.predict(line), label= "Linear Rgression") plt.show() !ec !eblock !split ===== Predator-Prey model from ecology ===== !bblock The population dynamics of a simple predator-prey system is a classical example shown in many biology textbooks when ecological systems are discussed. The system contains all elements of the scientific method: * The set up of a specific hypothesis combined with * the experimental methods needed (one can study existing data or perform experiments) * analyzing and interpreting the data and performing further experiments if needed * trying to extract general behaviors and extract eventual laws or patterns * develop mathematical relations for the uncovered regularities/laws and test these by per forming new experiments !eblock !split ===== Case study from Hudson bay ===== !bblock Lots of data about populations of hares and lynx collected from furs in Hudson Bay, Canada, are available. It is known that the populations oscillate. Why? Here we start by o plotting the data o derive a simple model for the population dynamics o (fitting parameters in the model to the data) o using the model predict the evolution other predator-pray systems !eblock !split ===== Hudson bay data ===== !bblock Most mammalian predators rely on a variety of prey, which complicates mathematical modeling; however, a few predators have become highly specialized and seek almost exclusively a single prey species. An example of this simplified predator-prey interaction is seen in Canadian northern forests, where the populations of the lynx and the snowshoe hare are intertwined in a life and death struggle. One reason that this particular system has been so extensively studied is that the Hudson Bay company kept careful records of all furs from the early 1800s into the 1900s. The records for the furs collected by the Hudson Bay company showed distinct oscillations (approximately 12 year periods), suggesting that these species caused almost periodic fluctuations of each other's populations. The table here shows data from 1900 to 1920. |------------------------------------------------------| | Year | Hares (x1000) | Lynx (x1000)| |---------l-----------------------r--------------r------| | 1900 | 30.0 | 4.0 | | 1901 | 47.2 | 6.1 | | 1902 | 70.2 | 9.8 | | 1903 | 77.4 | 35.2 | | 1904 | 36.3 | 59.4 | | 1905 | 20.6 | 41.7 | | 1906 | 18.1 | 19.0 | | 1907 | 21.4 | 13.0 | | 1908 | 22.0 | 8.3 | | 1909 | 25.4 | 9.1 | | 1910 | 27.1 | 7.4 | | 1911 | 40.3 | 8.0 | | 1912 | 57 | 12.3 | | 1913 | 76.6 | 19.5 | | 1914 | 52.3 | 45.7 | | 1915 | 19.5 | 51.1 | | 1916 | 11.2 | 29.7 | | 1917 | 7.6 | 15.8 | | 1918 | 14.6 | 9.7 | | 1919 | 16.2 | 10.1 | | 1920 | 24.7 | 8.6 | |------------------------------------------------------| !eblock !split ===== Plotting the data ===== !bblock @@@CODE src/plot_Hudson.py !eblock !split ===== Hares and lynx in Hudson bay from 1900 to 1920 ===== FIGURE: [fig/Hudson_Bay_data, width=700 frac=0.9] !split ===== Why now create a computer model for the hare and lynx populations? ===== !bblock We see from the plot that there are indeed fluctuations. We would like to create a mathematical model that explains these population fluctuations. Ecologists have predicted that in a simple predator-prey system that a rise in prey population is followed (with a lag) by a rise in the predator population. When the predator population is sufficiently high, then the prey population begins dropping. After the prey population falls, then the predator population falls, which allows the prey population to recover and complete one cycle of this interaction. Thus, we see that qualitatively oscillations occur. Can a mathematical model predict this? What causes cycles to slow or speed up? What affects the amplitude of the oscillation or do you expect to see the oscillations damp to a stable equilibrium? The models tend to ignore factors like climate and other complicating factors. How significant are these? * We see oscillations in the data * What causes cycles to slow or speed up? * What affects the amplitude of the oscillation or do you expect to see the oscillations damp to a stable equilibrium? * With a model we can better *understand the data* * More important: we can understand the ecology dynamics of predator-pray populations !eblock !split ===== The traditional (top-down) approach ===== !bblock The classical way (in all books) is to present the Lotka-Volterra equations: !bt \begin{align*} \frac{dH}{dt} &= H(a - b L)\\ \frac{dL}{dt} &= - L(d - c H) \end{align*} !et Here, * $H$ is the number of preys * $L$ the number of predators * $a$, $b$, $d$, $c$ are parameters Most books quickly establish the model and then use considerable space on discussing the qualitative properties of this *nonlinear system of ODEs* (which cannot be solved) !eblock !split ===== Basic mathematics notation ===== !bblock * Time points: $t_0,t_1,\ldots,t_m$ * Uniform distribution of time points: $t_n=n\Delta t$ * $H^n$: population of hares at time $t_n$ * $L^n$: population of lynx at time $t_n$ * We want to model the changes in populations, $\Delta H=H^{n+1}-H^n$ and $\Delta L=L^{n+1}-L^n$ during a general time interval $[t_{n+1},t_n]$ of length $\Delta t=t_{n+1}-t_n$ !eblock !split ===== Basic dynamics of the population of hares ===== !bblock The population of hares evolves due to births and deaths exactly as a bacteria population: !bt \[ \Delta H = a \Delta t H^n \] !et However, hares have an additional loss in the population because they are eaten by lynx. All the hares and lynx can form $H\cdot L$ pairs in total. When such pairs meet during a time interval $\Delta t$, there is some small probablity that the lynx will eat the hare. So in fraction $b\Delta t HL$, the lynx eat hares. This loss of hares must be accounted for. Subtracted in the equation for hares: !bt \[ \Delta H = a\Delta t H^n - b \Delta t H^nL^n\] !et !eblock !split ===== Basic dynamics of the population of lynx ===== !bblock We assume that the primary growth for the lynx population depends on sufficient food for raising lynx kittens, which implies an adequate source of nutrients from predation on hares. Thus, the growth of the lynx population does not only depend of how many lynx there are, but on how many hares they can eat. In a time interval $\Delta t HL$ hares and lynx can meet, and in a fraction $b\Delta t HL$ the lynx eats the hare. All of this does not contribute to the growth of lynx, again just a fraction of $b\Delta t HL$ that we write as $d\Delta t HL$. In addition, lynx die just as in the population dynamics with one isolated animal population, leading to a loss $-c\Delta t L$. !eblock !bblock The accounting of lynx then looks like !bt \[ \Delta L = d\Delta t H^nL^n - c\Delta t L^n\] !et !eblock !split ===== Evolution equations ===== !bblock By writing up the definition of $\Delta H$ and $\Delta L$, and putting all assumed known terms $H^n$ and $L^n$ on the right-hand side, we have !bt \[ H^{n+1} = H^n + a\Delta t H^n - b\Delta t H^n L^n \] !et !bt \[ L^{n+1} = L^n + d\Delta t H^nL^n - c\Delta t L^n \] !et Note: * These equations are ready to be implemented! * But to start, we need $H^0$ and $L^0$ (which we can get from the data) * We also need values for $a$, $b$, $d$, $c$ !eblock !split ===== Adapt the model to the Hudson Bay case ===== !bblock * As always, models tend to be general - as here, applicable to ``all'' predator-pray systems * The critical issue is whether the *interaction* between hares and lynx is sufficiently well modeled by $\hbox{const}HL$ * The parameters $a$, $b$, $d$, and $c$ must be estimated from data * Measure time in years * $t_0=1900$, $t_m=1920$ !eblock !split ===== The program ===== !bblock @@@CODE src/Hudson_Bay.py !eblock !split ===== The plot ===== FIGURE: [fig/Hudson_Bay_sim, width=700 frac=0.9] If we perform a least-square fitting, we can find optimal values for the parameters $a$, $b$, $d$, $c$. The optimal parameters are $a=0.4807$, $b=0.02482$, $d=0.9272$ and $c=0.02756$. These parameters result in a slightly modified initial conditions, namely $H(0) = 34.91$ and $L(0)=3.857$. With these parameters we are now ready to solve the equations and plot these data together with the experimental values. !split ===== Linear regression in Python ===== !bblock !bc pycod import numpy as np import matplotlib.pyplot as plt from IPython.display import display import sklearn from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1) x = data[:,0] y = data[:,1] line = np.linspace(1900,1920,1000,endpoint=False).reshape(-1,1) reg = DecisionTreeRegressor(min_samples_split=3).fit(x.reshape(-1,1),y.reshape(-1,1)) plt.plot(line, reg.predict(line), label="decision tree") regline = LinearRegression().fit(x.reshape(-1,1),y.reshape(-1,1)) plt.plot(line, regline.predict(line), label= "Linear Regression") plt.plot(x, y, label= "Linear Regression") plt.show() !ec !eblock !split ===== Linear Least squares in R ===== !bblock !bc r HudsonBay = read.csv("src/Hudson_Bay.csv",header=T) fix(HudsonBay) dim(HudsonBay) names(HudsonBay) plot(HudsonBay$Year, HudsonBay$Hares..x1000.) attach(HudsonBay) plot(Year, Hares..x1000.) plot(Year, Hares..x1000., col="red", varwidth=T, xlab="Years", ylab="Haresx 1000") summary(HudsonBay) summary(Hares..x1000.) library(MASS) library(ISLR) scatter.smooth(x=Year, y = Hares..x1000.) linearMod = lm(Hares..x1000. ~ Year) print(linearMod) summary(linearMod) plot(linearMod) confint(linearMod) predict(linearMod,data.frame(Year=c(1910,1914,1920)),interval="confidence") !ec !eblock !split ===== Non-Linear Least squares in R ===== !bblock !bc r set.seed(1485) len = 24 x = runif(len) y = x^3+rnorm(len, 0,0.06) ds = data.frame(x = x, y = y) str(ds) plot( y ~ x, main ="Known cubic with noise") s = seq(0,1,length =100) lines(s, s^3, lty =2, col ="green") m = nls(y ~ I(x^power), data = ds, start = list(power=1), trace = T) class(m) summary(m) power = round(summary(m)$coefficients[1], 3) power.se = round(summary(m)$coefficients[2], 3) plot(y ~ x, main = "Fitted power model", sub = "Blue: fit; green: known") s = seq(0, 1, length = 100) lines(s, s^3, lty = 2, col = "green") lines(s, predict(m, list(x = s)), lty = 1, col = "blue") text(0, 0.5, paste("y =x^ (", power, " +/- ", power.se, ")", sep = ""), pos = 4) !ec !eblock !split !split ===== Example: ecoli lab experiment ===== !bnotice Typical pattern: The population grows faster and faster. "Why? Is there an underlying (general) mechanism":"http://www.zo.utexas.edu/courses/Thoc/PopGrowth.html"? !enotice !bblock o Cells divide after $T$ seconds on average (one generation) o $2N$ celles divide into twice as many new cells $\Delta N$ in a time interval $\Delta t$ as $N$ cells would: $\Delta N \propto N$ o $N$ cells result in twice as many new individuals $\Delta N$ in time $2\Delta t$ as in time $\Delta t$: $\Delta N \propto\Delta t$ o Same proportionality wrt death (repeat reasoning) o Proposed model: $\Delta N = b\Delta t N - d\Delta tN$ for some unknown constants $b$ (births) and $d$ (deaths) o Describe evolution in discrete time: $t_n=n\Delta t$ o Program-friendly notation: $N$ at $t_n$ is $N^n$ o Math model: $N^{n+1} = N^n + r\Delta t\, N$ (with $\ r=b-d$) o Program model: `N[n+1] = N[n] + r*dt*N[n]` !eblock !split ===== The program ===== !bblock Let us solve the difference equation in as simple way as possible, just to train some programming: $r=1.5$, $N^0=1$, $\Delta t=0.5$ @@@CODE ../../Programs/LifeScience/diffeq.py !eblock % if FORMAT != 'ipynb': !split ===== The output ===== !bc N[1]=1.2 N[2]=1.6 N[3]=2.0 N[4]=2.4 N[5]=3.1 N[6]=3.8 N[7]=4.8 N[8]=6.0 N[9]=7.5 N[10]=9.3 N[11]=11.6 N[12]=14.6 N[13]=18.2 N[14]=22.7 N[15]=28.4 N[16]=35.5 N[17]=44.4 N[18]=55.5 N[19]=69.4 N[20]=86.7 !ec % endif !split ===== Parameter estimation ===== !bblock * We do not know $r$ * How can we estimate $r$ from data? We can use the difference equation with the experimental data !bt \[ N^{n+1} = N^n + r\Delta t N^n\] !et Say $N^{n+1}$ and $N^n$ are known from data, solve wrt $r$: !bt \[ r = \frac{N^{n+1}-N^n}{N^n\Delta t} \] !et Use experimental data in the fraction, say $t_1=600$, $t_2=1200$, $N^1=140$, $N^2=250$: $r=0.0013$. !eblock !split ===== A program relevant for the biological problem ===== # exact r = 0.000694 !bblock @@@CODE ../../Programs/LifeScience/ecoli.py Change `r` in the program and play around to make a better fit! !eblock !split ===== We shall model a very complex phenomenon by simple math.... ===== !bblock Assumptions: * We consider a perfectly mixed population in a confined area * No spatial transport, just temporal evolution * We do not consider individuals, just a grand mix of them (cf. statistical mechanics vs thermodynamics) !eblock !bpop !bblock (small) We consider very simple models, but these can be extended to full models that are used world-wide by health authorities. Typical diseases modeled are flu, measles, swine flu, HIV, ... !eblock !epop !split ===== We keep track of 3 categories in the SIR model ===== !bblock * _S_: susceptibles - who can get the disease * _I_: infected - who have developed the disease and infect susceptibles * _R_: recovered - who have recovered and become immune !eblock !bblock Mathematical quantities: $S(t)$, $I(t)$, $R(t)$: no of people in each category !eblock !bblock Goal: Find and solve equations for $S(t)$, $I(t)$, $R(t)$ !eblock FIGURE: [fig/categories_SIR, width=400 frac=0.5] !split ===== The traditional modeling approach is very mathematical - our idea is to model, program and experiment ===== !bblock * Numerous books on mathematical biology treat the SIR model * Quick modeling step (max 2 pages) * Nonlinear differential equation model * Cannot solve the equations, so focus is on discussing stability (eigenvalues), qualitative properties, etc. * Very few extensions of the model to real-life situations !eblock !split ===== Dynamics in a time interval $\Delta t$: $\Delta t\,\beta SI$ people move from S to I ===== !bblock S-I interaction: * In a mix of S and I people, there are $SI$ possible pairs * A certain fraction $\Delta t\,\beta$ of $SI$ meet in a (small) time interval $\Delta t$, with the result that the infected ``successfully'' infects the susceptible * The loss $\Delta t\,\beta SI$ in the S catogory is a corresponding gain in the I category !eblock !bpop !bblock (small) Remark It is reasonable that the fraction depends on $\Delta t$ (twice as many infected in $2\Delta t$ as in $\Delta t$). $\beta$ is some unknown parameter we must measure, supposed to not depend on $\Delta t$, but maybe time $t$. $\beta$ lumps *a lot* of biological and sociological effects into one number. !eblock !epop !split ===== For practical calculations, we must express the S-I interaction with symbols ===== Loss in $S(t)$ from time $t$ to $t+\Delta t$: !bt \[ S(t+\Delta t) = S(t) - \Delta t\,\beta S(t)I(t)\] !et Gain in $I(t)$: !bt \[ I(t+\Delta t) = I(t) + \Delta t\,\beta S(t)I(t)\] !et !split ===== Modeling the interaction between R and I ===== !bblock R-I interaction: * After some days, the infected has recovered and moves to the R category * A simple model: in a small time $\Delta t$ (say 1 day), a fraction $\Delta t\,\nu$ of the infected are removed ($\nu$ must be measured) !eblock We must subtract this fraction in the balance equation for $I$: !bt \[ I(t+\Delta t) = I(t) + \Delta t\,\beta S(t)I(t) -\Delta t\,\nu I(t) \] !et The loss $\Delta t\,\nu I$ is a gain in $R$: !bt \[ R(t+\Delta t) = R(t) + \Delta t\,\nu I(t)\] !et !split ===== We have three equations for $S$, $I$, and $R$ ===== !bt \begin{align} S(t+\Delta t) &= S(t) - \Delta t\,\beta S(t)I(t) label{SIR1:S}\\ I(t+\Delta t) &= I(t) + \Delta t\,\beta S(t)I(t) -\Delta t\nu I(t) label{SIR1:I}\\ R(t+\Delta t) &= R(t) + \Delta t\,\nu I(t) label{SIR1:R} \end{align} !et FIGURE: [fig/categories_SIR, width=400 frac=0.5] Before we can compute with these, we must * know $\beta$ and $\nu$ * know $S(0)$ (many), $I(0)$ (few), $R(0)$ (0?) * choose $\Delta t$ !split ===== The computation involves just simple arithmetics ===== * Set $\Delta t=6$ minutes * Set $\beta =0.0013$, $\nu =0.8333$ * Set $S(0)=50$, $I(0)=1$, $R(0)=0$ !bt \begin{align*} S(\Delta t) &= S(0) - \Delta t\,\beta S(0)I(0)\approx 49.99\\ I(\Delta t) &= I(0) + \Delta t\,\beta S(0)I(0) -\Delta t\,\nu I(0)\approx 1.002\\ R(\Delta t) &= R(0) + \Delta t\,\nu I(0)\approx 0.0008333 \end{align*} !et !bpop * In reality, $S$, $I$, $R$ are integers and events are discrete (meet, get sick) * In the model, we work with real numbers and continuous events * Reasonable approximation in a not too small population !epop !split ===== And we can continue... ===== !bt \begin{align*} S(2\Delta t) &= S(\Delta t) - \Delta t\,\beta S(\Delta t)I(\Delta t)\approx 49.87\\ I(2\Delta t) &= I(\Delta t) + \Delta t\,\beta S(\Delta t)I(\Delta t) -\Delta t\,\nu I(\Delta t)\approx 1.011\\ R(2\Delta t) &= R(\Delta t) + \Delta t\,\nu I(\Delta t)\approx 0.00167 \end{align*} !et Repeat... !bt \begin{align*} S(3\Delta t) &= S(2\Delta t) - \Delta t\,\beta S(2\Delta t)I(2\Delta t)\approx 49.98\\ I(3\Delta t) &= I(2\Delta t) + \Delta t\,\beta S(2\Delta t)I(2\Delta t) -\Delta t\,\nu I(2\Delta t)\approx 1.017\\ R(3\Delta t) &= R(2\Delta t) + \Delta t\,\nu I(2\Delta t)\approx 0.0025 \end{align*} !et !bpop But this is getting boring! Let's ask a computer to do the work! !epop !split ===== First, some handy notation ===== !bt \[ S^n = S(n\Delta t),\quad I^n = I(n\Delta t),\quad R^n = R(n\Delta t)\] !et !bt \[ S^{n+1} = S((n+1)\Delta t),\quad I^{n+1} = I((n+1)\Delta t),\quad R^{n+1} = R((n+1)\Delta t)\] !et The equations can now be written more compactly (and computer friendly): !bt \begin{align} S^{n+1} &= S^n - \Delta t\,\beta S^nI^n label{SIR1:Sc}\\ I^{n+1} &= I^n + \Delta t\,\beta S^nI^n -\Delta t\,\nu I^n label{SIR1:Ic}\\ R^{n+1} &= R^n + \Delta t\,\nu I^n label{SIR1:Rc} \end{align} !et !split ===== With variables, arrays, and a loop we can program ===== Suppose we want to compute until $t=N\Delta t$, i.e., for $n=0,1,\ldots,N-1$. We can store $S^0, S^1, S^2, \ldots, S^N$ in an array (or list). Python (Matlab): !bc pycod t = linspace(0, N*dt, N+1) # all time points S = zeros(N+1) I = zeros(N+1) R = zeros(N+1) for n in range(N): S[n+1] = S[n] - dt*beta*S[n]*I[n] I[n+1] = I[n] + dt*beta*S[n]*I[n] - dt*nu*I[n] R[n+1] = R[n] + dt*nu*I[n] !ec !split ===== Here is the complete program ===== !bc pycod beta = 0.0013 nu =0.8333 dt = 0.1 # 6 min (time measured in hours) D = 30 # simulate for D days N = int(D*24/dt) # corresponding no of hours from numpy import zeros, linspace t = linspace(0, N*dt, N+1) S = zeros(N+1) I = zeros(N+1) R = zeros(N+1) for n in range(N): S[n+1] = S[n] - dt*beta*S[n]*I[n] I[n+1] = I[n] + dt*beta*S[n]*I[n] - dt*nu*I[n] R[n+1] = R[n] + dt*nu*I[n] # Plot the graphs from matplotlib.pyplot import * plot(t, S, 'k-', t, I, 'b-', t, R, 'r-') legend(['S', 'I', 'R'], loc='lower right') xlabel('hours') show() !ec !split ===== We have predicted a disease! ===== FIGURE: [fig/SIR1, width=800] !split ===== How much math and programming did we use? ===== !bblock Math: * Plain arithmetics * The concept of a graph (i.e., discrete function in time) * Units * Greek letters !eblock !bblock Programming: * Variable * Array * Loop * Plotting !eblock !split ===== Detour: The standard mathematical approach ===== We had from intuition established !bt \begin{align*} S(t+\Delta t) &= S(t) - \Delta t\,\beta S(t)I(t)\\ I(t+\Delta t) &= I(t) + \Delta t\,\beta S(t)I(t) -\Delta t\,\nu I(t)\\ R(t+\Delta t) &= R(t) + \Delta t\,\nu R(t) \end{align*} !et The mathematician will now make *differential equations*. Divide by $\Delta t$ and rearrange: !bt \begin{align*} \frac{S(t+\Delta t) - S(t)}{\Delta t} &= - \beta S(t)I(t)\\ \frac{I(t+\Delta t) - I(t)}{\Delta t} &= \beta t S(t)I(t) -\nu I(t)\\ \frac{R(t+\Delta t) - R(t)}{\Delta t} &= \nu R(t) \end{align*} !et !split ===== A derivative arises as $\Delta t\rightarrow 0$ ===== In any calculus book, the derivative of $S$ at $t$ is defined as !bt \[ S'(t) = \lim_{t\rightarrow 0}\frac{S(t+\Delta t) - S(t)}{\Delta t}\] !et If we let $\Delta t\rightarrow 0$, we get derivatives on the left-hand side: !bt \begin{align*} S'(t) &= - \beta S(t)I(t)\\ I'(t) &= \beta t S(t)I(t) -\nu I(t)\\ R'(t) &= \nu R(t) \end{align*} !et This is a 3x3 system of differential equations for the functions $S(t)$, $I(t)$, $R(t)$. For a unique solution, we need $S(0)$, $I(0)$, $R(0)$. !split ===== Bad news: we cannot solve these equations! ===== !bblock Time to ask a numerical methods expert: Replace the derivative with a *finite difference*, e.g., !bt \[ S'(t) \approx \frac{S(t+\Delta t) - S(t)}{\Delta t}\] !et which is accurate for small $\Delta t$. !eblock This brings us back to the first model, which we can solve on a computer! % if EXTRA: !split ===== SIR is an ideal model for teaching modeling ===== !bquestion ``I believe genes are important for spreading of diseases. It's not included in the model.'' !equestion % endif !split ===== Parameter estimation is needed for predictive modeling ===== * Any small $\Delta t$ will do * One can reason about $\nu$ and say that $1/\nu$ is the mean recovery time for the disease (e.g., 1 week for a flu) * $\beta$ must in some way be measured, but we don't know what it means... !bblock So, what if we don't know $\beta$? * Can still learn about the *dynamics* of diseases * Can find the sensitivity to and influence of $\beta$ * Can apply *parameter estimation* procedures to fit $\beta$ to data !eblock !split ===== Let us extend the model: no life-long immunity ===== !bblock Assumption After some time, people in the R category lose the immunity. In a small time $\Delta t$ this gives a leakage $\Delta t\,\gamma R$ to the S category. ($1/\gamma$ is the mean time for immunity.) !eblock FIGURE: [fig/categories_SIR_feedback, width=400 frac=0.5] !bt \begin{align} S^{n+1} &= S^n - \Delta t\,\beta S^nI^n + {\color{red}\Delta t\,\gamma R^n} label{SIR2:S}\\ I^{n+1} &= I^n + \Delta t\,\beta S^nI^n -\Delta t\,\nu I^n label{SIR2:I}\\ R^{n+1} &= R^n + \Delta t\,\nu R^n - {\color{red}\Delta t\,\gamma R^n} label{SIR2:R} \end{align} !et No complications in the computational model! !split ===== The effect of loss of immunity ===== $1/\gamma = 50$ days. $\beta$ reduced by 2 and 4 (left and right, resp.): FIGURE: [fig/SIR2, width=950] !split ===== What is the effect of vaccination? ===== !bblock Assumptions A fraction $p$ of the S category, per time unit, is vaccinated with success. Then in time $\Delta t$, $p\Delta t S$ will move to a vaccinated category, V. This does not affect the I and R categories. !eblock FIGURE: [fig/categories_SIRV, width=400 frac=0.3] !bt \begin{align} S^{n+1} &= S^n - \Delta t\,\beta S^nI^n + \Delta t\,\gamma R^n - {\color{red}p\Delta t S^n} label{SIR3:S}\\ V^{n+1} &= V^n + {\color{red}p\Delta t S^n} label{SIR3:V}\\ I^{n+1} &= I^n + \Delta t\,\beta S^nI^n -\Delta t\,\nu I^n label{SIR3:I}\\ R^{n+1} &= R^n + \Delta t\,\nu R^n - \Delta t\,\gamma R^n label{SIR3:R} \end{align} !et # #if FORMAT not in ("latex", "pdflatex") # Too much for Beamer... Implementation: Just add array for $V^n$ and add equation. # #endif !split ===== Many possibilities for adjusting the model... ===== The effect of vaccination decreases over time, so we may move people back to the S category (term proportional to $\Delta t V$). FIGURE: [fig/categories_SIRV_feedback, width=400 frac=0.5] !split ===== Effect of adding vaccination ===== FIGURE: [fig/SIRV1, width=800 frac=0.8] ($p=0.0005$) !split ===== What is the effect of an intensive vaccination campaign? ===== 10 times more intense vaccination for 10 days, 6 days after outbreak: !bt \begin{equation*} p(t) = \left\lbrace\begin{array}{ll} 0.005,& 6\leq t\leq 15,\\ 0,& \hbox{otherwise} \end{array}\right.\end{equation*} !et Implementation: Let $p^n$ be an array as $V^n$. Set $p^n=0.05$ for $n=6\cdot 24/0.1,\ldots, 15\cdot 24/0.1$ ($\mbox{days}\cdot 24 /\Delta t$, 24 is hours per day). FIGURE: [fig/p_discont, width=400 frac=0.5] !split ===== Effect of vaccination campaign ===== FIGURE: [fig/SIRV2, width=500 frac=0.6] Note: * Mathematicians would be scared by the cusps on the curves... * Could now let the computer run a lot of cases and find the optimal vaccination period !split ===== We can experiment with other campaigns ===== !bslidecell 00 0.3 FIGURE: [fig/disease2.jpg, width=400] !eslidecell !bslidecell 01 0.7 Wearing masks lowers $\beta$: !bt \begin{equation*} \beta(t) = \left\lbrace\begin{array}{ll} \beta_1,& 0\leq t < 5,\\ \beta_2 < \beta_1,& t \geq 5\end{array}\right. \end{equation*} !et Very easy to implement. (Used to be complicated in differential equation models...) !eslidecell !split ===== And now for something similar: zombification! ===== FIGURE: [fig/zombie1, width=900] _Zombification_: The disease that turns you into a zombie. !split ===== Zombie modeling is almost the same as SIR modeling ===== !bblock Categories o S: susceptible humans who can become zombies o I: infected humans, being bitten by zombies o Z: zombies o R: removed individuals, either conquered zombies or dead humans !eblock Mathematical quantities: $S(t)$, $I(t)$, $Z(t)$, $R(t)$ Zombie movie: *The Night of the Living Dead*, Geoerge A. Romero, 1968 !split ===== Dynamics of the zombie SIZR model ===== FIGURE: [fig/categories_SIZR, width=380 frac=0.4] !bpop o Susceptibles are infected by zombies: $-\Delta t\beta SZ$ in time $\Delta t$ (cf. the $\Delta t\,\beta SI$ term in the SIR model). o Susceptibles die naturally or get killed and then enter the removed category. The no of deaths in time $\Delta t$ is $\Delta t\delta_S S$. o We also allow new humans to enter the area with zombies (necessary in a war on zombies): $\Delta t\Sigma$ during a time $\Delta t$. o Some infected turn into zombies (Z): $\Delta t\rho I$, while others die (R): $\delta_I\Delta t I$. o Nobody from R can turn into Z (important - otherwise zombies win). o Killed zombies go to R: $\Delta t\alpha SZ$. !epop !split ===== The four equations in the SIZR model for zombification ===== !bt \begin{align*} S^{n+1} &= S^n + \Delta t\,\Sigma - \Delta t\,\beta S^nZ - \Delta t\,\delta_S S^n\\ I^{n+1} &= I^n + \Delta t\,\beta S^nZ^n - \Delta t\,\rho I^n - \Delta t\,\delta_I I^n\\ Z^{n+1} &= Z^n + \Delta t\,\rho I^n - \Delta t\,\alpha S^nZ^n\\ R^{n+1} &= R^n + \Delta t\,\delta_S S^n + \Delta t\,\delta_I I^n + \Delta t\,\alpha S^nZ^n \end{align*} !et !bblock (small) Interpretation of parameters: * $\Sigma$: no of new humans brought into the zombified area per unit time. * $\beta$: the probability that a theoretically possible human-zombie pair actually meets physically, during a unit time interval, with the result that the human is infected. * $\delta_S$: the probability that a susceptible human is killed or dies, in a unit time interval. * $\delta_I$: the probability that an infected human is killed or dies, in a unit time interval. * $\rho$: the probability that an infected human is turned into a zombie, during a unit time interval. * $\alpha$: the probability that, during a unit time interval, a theoretically possible human-zombie pair fights and the human kills the zombie. !eblock !split ===== Simulate a zombie movie! ===== !bslidecell 00 0.6 !bblock Three fundamental phases o The initial phase (4 h) o The hysteric phase (24 h) o The counter attack phase (5 h) !eblock !eslidecell !bslidecell 01 0.4 FIGURE: [fig/TNotLD, width=300] !eslidecell !bpop How do we do this? As $p$ in the vaccination campaign - the parameters take on different constant values in different time intervals. !epop !bpop H. P. Langtangen, K.-A. Mardal and P. Røtnes: Escaping the Zombie Threat by Mathematics, in A. Whelan et al.: *Zombies in the Academy - Living Death in Higher Education*, University of Chicago Press, 2013 !epop !split ===== Effective war on zombies ===== Introduce attacks on zombies at selected times $T_0, T_1, \ldots, T_m$. Model: Replace $\alpha$ by !bt \[ \alpha_0 + \omega (t),\] !et where $\alpha_0$ is constant and $\omega(t)$ is a series of Gaussian functions (peaks) in time: !bt \[ \omega(t) = a\sum_{i=0}^m \exp{\left(-\frac{1}{2}\left({t - T_i\over\sigma}\right)\right)} \] !et Must experiment with values of $a$ (strength), $\sigma$ (duration is $6\sigma$), point of attacks ($T_i$) - with proper values humans beat the zombies! !split ===== Summary ===== * A complex spreading of diseases can be modeled by intuitive, simple accounting of movement between categories * Such models are knowns as *compartment models* * Result: difference equations that are easy to simulate on a computer * (Can let $\Delta t\rightarrow 0$ and get differential equations) * Easy to add new effects (vaccination, campaigns, zombification) ===== Theoretical background and description of the system ===== The aim of this project is to simulate financial transactions among financial agents using Monte Carlo methods. The final goal is to extract a distribution of income as function of the income $m$. From Pareto's work ("V.~Pareto, 1897":"http://www.institutcoppet.org/2012/05/08/cours-deconomie-politique-1896-de-vilfredo-pareto") it is known from empirical studies that the higher end of the distribution of money follows a distribution !bt \[ w_m\propto m^{-1-\alpha}, \] !et with $\alpha\in [1,2]$. We will here follow the analysis made by "Patriarca and collaborators":"http://www.sciencedirect.com/science/article/pii/S0378437104004327". Here we will study numerically the relation between the micro-dynamic relations among financial agents and the resulting macroscopic money distribution. We assume we have $N$ agents that exchange money in pairs $(i,j)$. We assume also that all agents start with the same amount of money $m_0 > 0$. At a given 'time step', we choose randomly a pair of agents $(i,j)$ and let a transaction take place. This means that agent $i$'s money $m_i$ changes to $m_i'$ and similarly we have $m_j\rightarrow m_j'$. Money is conserved during a transaction, meaning that !bt \begin{equation} m_i+m_j=m_i'+m_j'. label{eq:conserve} \end{equation} !et The change is done via a random reassignement (a random number) $\epsilon$, meaning that !bt \begin{equation*} m_i' = \epsilon(m_i+m_j), \end{equation*} !et leading to !bt \begin{equation*} m_j'= (1-\epsilon)(m_i+m_j). \end{equation*} !et The number $\epsilon$ is extracted from a uniform distribution. In this simple model, no agents are left with a debt, that is $m\ge 0$. Due to the conservation law above, one can show that the system relaxes toward an equilibrium state given by a Gibbs distribution !bt \begin{equation*} w_m=\beta \exp{(-\beta m)}, \end{equation*} !et with !bt \begin{equation*} \beta = \frac{1}{\langle m\rangle}, \end{equation*} !et and $\langle m\rangle=\sum_i m_i/N=m_0$, the average money. It means that after equilibrium has been reached that the majority of agents is left with a small number of money, while the number of richest agents, those with $m$ larger than a specific value $m'$, exponentially decreases with $m'$. We assume that we have $N=500$ agents. In each simulation, we need a sufficiently large number of transactions, say $10^7$. Our aim is find the final equilibrium distribution $w_m$. In order to do that we would need several runs of the above simulations, at least $10^3-10^4$ runs (experiments). === Project 4a): Simulation of Transactions === Your task is to first set up an algorithm which simulates the above transactions with an initial amount $m_0$. The challenge here is to figure out a Monte Carlo simulation based on the above equations. You will in particular need to make an algorithm which sets up a histogram as function of $m$. This histogram contains the number of times a value $m$ is registered and represents $w_m\Delta m$. You will need to set up a value for the interval $\Delta m$ (typically $0.01-0.05$). That means you need to account for the number of times you register an income in the interval $m,m+\Delta m$. The number of times you register this income, represents the value that enters the histogram. You will also need to find a criterion for when the equilibrium situation has been reached. === Project 4b): Recognizing the distribution === Make thereafter a plot of $\log{(w_m)}$ as function of $m$ and see if you get a straight line. Comment the result. === Project 4c): Transactions and savings === We can then change our model to allow for a saving criterion, meaning that the agents save a fraction $\lambda$ of the money they have before the transaction is made. The final distribution will then no longer be given by Gibbs distribution. It could also include a taxation on financial transactions. The conservation law of Eq. (ref{eq:conserve}) holds, but the money to be shared in a transaction between agent $i$ and agent $j$ is now $(1-\lambda)(m_i+m_j)$. This means that we have !bt \begin{equation*} m_i' = \lambda m_i+\epsilon(1-\lambda)(m_i+m_j), \end{equation*} !et and !bt \begin{equation*} m_j' = \lambda m_j+(1-\epsilon)(1-\lambda)(m_i+m_j), \end{equation*} !et which can be written as !bt \begin{equation*} m_i'=m_i+\delta m \end{equation*} !et and !bt \begin{equation*} m_j'=m_j-\delta m, \end{equation*} !et with !bt \begin{equation*} \delta m=(1-\lambda)(\epsilon m_j-(1-\epsilon)m_i), \end{equation*} !et showing how money is conserved during a transaction. Select values of $\lambda =0.25,0.5$ and $\lambda=0.9$ and try to extract the corresponding equilibrium distributions and compare these with the Gibbs distribution. Comment your results. Extract a parametrization of the above curves, see for example "Patriarca and collaborators":"http://www.sciencedirect.com/science/article/pii/S0378437104004327" and see if you can parametrize the high-end tails of the distributions in terms of power laws. Comment your results. === Project 4d): Nearest neighbor interactions === In the rest of this project we will follow the work of "Goswami and Sen":"http://www.sciencedirect.com/science/article/pii/S0378437114006967". In the studies above the agents were selected randomly, irrespective of whether we allowed for saving or not during a transaction. What is often observed is that various agents tend to make preferences for for whom to interact with. We will now study the evolution of the distribution of wealth $w_m$ by assuming that there is a likelihood !bt \[ p_{ij} \propto \vert m_i-m_j\vert^{-\alpha}, \] !et for an interaction between agents $i$ and $j$ with respective wealths $m_i$ and $m_j$. The parameter $\alpha > 0$. For $\alpha=0$ we recover our model from part 5a). Perform the same analysis as previously with $N=500$ as well as with $N=1000$ agents and study the distribution of wealth for $\alpha =0.5$, $\alpha =1.0$, $\alpha =1.5$ and $\alpha =2.0$. You should try to reproduce Figure 1 of "Goswami and Sen":"http://www.sciencedirect.com/science/article/pii/S0378437114006967". Extract the tail of the distribution and see if it follows a Pareto distribution !bt \[ w_m\propto m^{-1-\alpha}. \] !et What happens if $\alpha \gg 1$? Perform the analysis with and without a saving $\lambda$ on each transaction and comment your results. === Project 4e): Nearest neighbors and former transactions === We add to the previous probability the possibility that two agents who interact have performed similar transactions earlier. That is, in addition to being financially close, we assume that the likelihood for interacting increases if two agents have interacted earlier. We add this feature by modifying the previous likelihood to !bt \[ p_{ij} \propto \vert m_i-m_j\vert^{-\alpha}\left(c_{ij}+1\right)^{\gamma}, \] !et where $c_{ij}$ represents the number of previous interactions that have taken place between $i$ and $j$. The factor $1$ is added in order to ensure that if they have not interacted earlier they can still interact. Perform similar studies as above with $N=1000$, $\alpha=1.0$ and $\alpha=2.0$ using $\gamma = 0.0, 1.0, 2.0, 3.0$ and $4.0$. Plot the wealth distributions for these cases and try to extract eventual power law tails with and without a saving $\lambda$ in each transaction. Comment your results and compare them with figures 5 and 6 of "Goswami and Sen":"http://www.sciencedirect.com/science/article/pii/S0378437114006967".