Files
FYS-STK4155/doc/pub/How2ReadData/ipynb/How2ReadData.ipynb
T
2018-05-21 10:59:37 -04:00

1461 lines
50 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- dom:TITLE: Data Analysis and Machine Learning: Getting started, our first data and Machine Learning encounters -->\n",
"# Data Analysis and Machine Learning: Getting started, our first data and Machine Learning encounters\n",
"<!-- dom:AUTHOR: Morten Hjorth-Jensen at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University -->\n",
"<!-- Author: --> \n",
"**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n",
"\n",
"Date: **May 21, 2018**\n",
"\n",
"Copyright 1999-2018, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
"\n",
"\n",
"\n",
"\n",
"## Introduction\n",
"\n",
"Before we proceed there are several practicalities with data\n",
"analysis and software tools we would like to present. These tools will\n",
"help us in our understanding of various machine learning algorithms.\n",
"\n",
"Our emphasis here is on understanding the mathematical aspects of\n",
"different algorithms, however, where possible we will emphasize the\n",
"importance of using available software. We start thus with a hands-on\n",
"and top-down approach machine learning. The aim is thus to start with\n",
"relevant data and use these to introduce statistical data analysis\n",
"concepts and machine learning algorithms before we delve into the\n",
"algorithms themselves. The examples we will use start with a simple\n",
"third-order polynomial with random noise added, and using the Python\n",
"software package [Scikit-learn](http://scikit-learn.org/stable/) we\n",
"will introduce various machine learning algorithm s to make fits of\n",
"the data data and predictions. We move thereafter to more interesting\n",
"cases such as the simulation of financial transactions or disease\n",
"models. These are examples where we can easily set up the data and\n",
"then use machine learning algorithms using included in for example **scikit-learn**. Another model we\n",
"will consider is the so-called Ising model. Here we will use this\n",
"model to produce data for selected spin configurations and attempt to classify the data. \n",
"Finally, our last example consists of economic data from the OECD. \n",
"\n",
"\n",
"## Software and needed installations\n",
"\n",
"We will make intensive use of python as programming language and the myriad of available libraries. \n",
"Furthermore, you will find IPython/Jupyter notebooks invaluable in your work. \n",
"You can run **R** codes in the Jupyter/IPython notebooks, with the immediate benefit of visualizing your data.\n",
"\n",
"\n",
"If you have Python installed (we recommend Python3) and you feel pretty familiar with installing different packages, \n",
"we recommend that you install the following Python packages via **pip** as\n",
"1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow\n",
"\n",
"For Python3, replace **pip** with **pip3**.\n",
"\n",
"For OSX users we recommend also, after having installed Xcode, to install **brew**. Brew allows \n",
"for a seamless installation of additional software via for example\n",
"1. brew install python3\n",
"\n",
"For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution\n",
"you can use **pip** as well and simply install Python as \n",
"1. sudo apt-get install python3 (or python for pyhton2.7)\n",
"\n",
"etc etc. \n",
"\n",
"## Python installers\n",
"If you don't want to perform these operations separately, we recommend two widely used distrubutions which set up \n",
"all relevant dependencies for Python, namely\n",
"1. [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**\n",
"\n",
"2. [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.\n",
"\n",
"## Installing R, C++, cython or Julia\n",
"\n",
"You will also find it convenient to utilize R. \n",
"Jupyter/Ipython notebook allows you run **R** code interactively in your browser. The software library **R** is \n",
"tuned to statistically analysis and allows for an easy usage of the tools we will discuss in these texts.\n",
"\n",
"To install **R** with Jupyter notebook [following the link here](https://mpacer.org/maths/r-kernel-for-ipython-notebook)\n",
"\n",
"\n",
"\n",
"## Installing R, C++, cython or Julia\n",
"\n",
"\n",
"For the C++ aficionados, Jupyter/IPython notebook allows you also to install C++ and run codes written in this language \n",
"interactively in the browser. Since we will emphasize writing many of the algorithms yourself, you can thus opt for\n",
"either Python or C++ as programming languages. \n",
"\n",
"To add more entropy, **cython** can also be used when running your notebooks. It means that Python with the Jupyter/IPython notebook \n",
"setup allows you to integrate widely popular softwares and tools for scientific computing. With its versatility, \n",
"including symbolic operations, Python offers a unique computational environment. Your Jupyter/IPython notebook \n",
"can easily be converted into a nicely rendered **PDF** file or a Latex file for further processing. For example, convert to latex as"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"jupyter nbconvert filename.ipynb --to latex"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you use the light mark-up language **doconce** you can convert a standard ascii text file into various HTML \n",
"formats, ipython notebooks, latex files, pdf files etc. \n",
"\n",
"\n",
"\n",
"## Introduction to Jupyter notebook and available tools"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from scipy import sparse\n",
"import pandas as pd\n",
"from IPython.display import display\n",
"eye = np.eye(4)\n",
"print(eye)\n",
"sparse_mtx = sparse.csr_matrix(eye)\n",
"print(sparse_mtx)\n",
"x = np.linspace(-10,10,100)\n",
"y = np.sin(x)\n",
"plt.plot(x,y,marker='x')\n",
"plt.show()\n",
"data = {'Name': [\"John\", \"Anna\", \"Peter\", \"Linda\"], 'Location': [\"Nairobi\", \"Napoli\", \"London\", \"Buenos Aires\"], 'Age':[51, 21, 34, 45]}\n",
"data_pandas = pd.DataFrame(data)\n",
"display(data_pandas)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Representing data, more examples"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from scipy import sparse\n",
"import pandas as pd\n",
"from IPython.display import display\n",
"import mglearn\n",
"import sklearn\n",
"from sklearn.linear_model import LinearRegression\n",
"from sklearn.tree import DecisionTreeRegressor\n",
"x, y = mglearn.datasets.make_wave(n_samples=100)\n",
"line = np.linspace(-3,3,1000,endpoint=False).reshape(-1,1)\n",
"reg = DecisionTreeRegressor(min_samples_split=3).fit(x,y)\n",
"plt.plot(line, reg.predict(line), label=\"decision tree\")\n",
"regline = LinearRegression().fit(x,y)\n",
"plt.plot(line, regline.predict(line), label= \"Linear Regression\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Simple regression model\n",
"Add info about the equations"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Importing various packages\n",
"from random import random, seed\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"x = 2*np.random.rand(100,1)\n",
"y = 4+3*x+np.random.randn(100,1)\n",
"\n",
"xb = np.c_[np.ones((100,1)), x]\n",
"theta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n",
"xnew = np.array([[0],[2]])\n",
"xbnew = np.c_[np.ones((2,1)), xnew]\n",
"ypredict = xbnew.dot(theta)\n",
"\n",
"plt.plot(xnew, ypredict, \"r-\")\n",
"plt.plot(x, y ,'ro')\n",
"plt.axis([0,2.0,0, 15.0])\n",
"plt.xlabel(r'$x$')\n",
"plt.ylabel(r'$y$')\n",
"plt.title(r'Linear Regression')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Simple regression model, now using **scikit-learn**\n",
"Add info about the equations"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Importing various packages\n",
"from random import random, seed\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.linear_model import LinearRegression\n",
"\n",
"x = 2*np.random.rand(100,1)\n",
"y = 4+3*x+np.random.randn(100,1)\n",
"linreg = LinearRegression()\n",
"linreg.fit(x,y)\n",
"xnew = np.array([[0],[2]])\n",
"ypredict = linreg.predict(xnew)\n",
"\n",
"plt.plot(xnew, ypredict, \"r-\")\n",
"plt.plot(x, y ,'ro')\n",
"plt.axis([0,2.0,0, 15.0])\n",
"plt.xlabel(r'$x$')\n",
"plt.ylabel(r'$y$')\n",
"plt.title(r'Random numbers ')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Simple regression model with gradient descent\n",
"Add info about the equations, play around with different learning rates"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Importing various packages\n",
"from math import exp, sqrt\n",
"from random import random, seed\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"x = 2*np.random.rand(100,1)\n",
"y = 4+3*x+np.random.randn(100,1)\n",
"\n",
"xb = np.c_[np.ones((100,1)), x]\n",
"theta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n",
"print(theta_linreg)\n",
"theta = np.random.randn(2,1)\n",
"\n",
"eta = 0.1\n",
"Niterations = 1000\n",
"m = 100\n",
"\n",
"for iter in range(Niterations):\n",
" gradients = 2.0/m*xb.T.dot(xb.dot(theta)-y)\n",
" theta -= eta*gradients\n",
"\n",
"print(theta)\n",
"xnew = np.array([[0],[2]])\n",
"xbnew = np.c_[np.ones((2,1)), xnew]\n",
"ypredict = xbnew.dot(theta)\n",
"ypredict2 = xbnew.dot(theta_linreg)\n",
"plt.plot(xnew, ypredict, \"r-\")\n",
"plt.plot(xnew, ypredict2, \"b-\")\n",
"plt.plot(x, y ,'ro')\n",
"plt.axis([0,2.0,0, 15.0])\n",
"plt.xlabel(r'$x$')\n",
"plt.ylabel(r'$y$')\n",
"plt.title(r'Random numbers ')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Simple regression model with stochastic gradient descent\n",
"Add info about the equations, play around with different learning rates"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Importing various packages\n",
"from math import exp, sqrt\n",
"from random import random, seed\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.linear_model import SGDRegressor\n",
"\n",
"x = 2*np.random.rand(100,1)\n",
"y = 4+3*x+np.random.randn(100,1)\n",
"\n",
"xb = np.c_[np.ones((100,1)), x]\n",
"theta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n",
"print(theta_linreg)\n",
"sgdreg = SGDRegressor(n_iter = 50, penalty=None, eta0=0.1)\n",
"sgdreg.fit(x,y.ravel())\n",
"print(sgdreg.intercept_, sgdreg.coef_)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Polynomial regression"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Predator-Prey model from ecology\n",
"\n",
"The population dynamics of a simple predator-prey system is a\n",
"classical example shown in many biology textbooks when ecological\n",
"systems are discussed. The system contains all elements of the\n",
"scientific method:\n",
"\n",
" * The set up of a specific hypothesis combined with\n",
"\n",
" * the experimental methods needed (one can study existing data or perform experiments)\n",
"\n",
" * analyzing and interpreting the data and performing further experiments if needed\n",
"\n",
" * trying to extract general behaviors and extract eventual laws or patterns\n",
"\n",
" * develop mathematical relations for the uncovered regularities/laws and test these by per forming new experiments\n",
"\n",
"\n",
"\n",
"\n",
"## Case study from Hudson bay\n",
"\n",
"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?\n",
"Here we start by\n",
"\n",
"1. plotting the data\n",
"\n",
"2. derive a simple model for the population dynamics\n",
"\n",
"3. (fitting parameters in the model to the data)\n",
"\n",
"4. using the model predict the evolution other predator-pray systems\n",
"\n",
"\n",
"\n",
"## Hudson bay data\n",
"\n",
"\n",
"\n",
"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.\n",
"\n",
"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.\n",
"\n",
"\n",
"<table border=\"1\">\n",
"<thead>\n",
"<tr><th align=\"center\">Year</th> <th align=\"center\">Hares (x1000)</th> <th align=\"center\">Lynx (x1000)</th> </tr>\n",
"</thead>\n",
"<tbody>\n",
"<tr><td align=\"left\"> 1900 </td> <td align=\"right\"> 30.0 </td> <td align=\"right\"> 4.0 </td> </tr>\n",
"<tr><td align=\"left\"> 1901 </td> <td align=\"right\"> 47.2 </td> <td align=\"right\"> 6.1 </td> </tr>\n",
"<tr><td align=\"left\"> 1902 </td> <td align=\"right\"> 70.2 </td> <td align=\"right\"> 9.8 </td> </tr>\n",
"<tr><td align=\"left\"> 1903 </td> <td align=\"right\"> 77.4 </td> <td align=\"right\"> 35.2 </td> </tr>\n",
"<tr><td align=\"left\"> 1904 </td> <td align=\"right\"> 36.3 </td> <td align=\"right\"> 59.4 </td> </tr>\n",
"<tr><td align=\"left\"> 1905 </td> <td align=\"right\"> 20.6 </td> <td align=\"right\"> 41.7 </td> </tr>\n",
"<tr><td align=\"left\"> 1906 </td> <td align=\"right\"> 18.1 </td> <td align=\"right\"> 19.0 </td> </tr>\n",
"<tr><td align=\"left\"> 1907 </td> <td align=\"right\"> 21.4 </td> <td align=\"right\"> 13.0 </td> </tr>\n",
"<tr><td align=\"left\"> 1908 </td> <td align=\"right\"> 22.0 </td> <td align=\"right\"> 8.3 </td> </tr>\n",
"<tr><td align=\"left\"> 1909 </td> <td align=\"right\"> 25.4 </td> <td align=\"right\"> 9.1 </td> </tr>\n",
"<tr><td align=\"left\"> 1910 </td> <td align=\"right\"> 27.1 </td> <td align=\"right\"> 7.4 </td> </tr>\n",
"<tr><td align=\"left\"> 1911 </td> <td align=\"right\"> 40.3 </td> <td align=\"right\"> 8.0 </td> </tr>\n",
"<tr><td align=\"left\"> 1912 </td> <td align=\"right\"> 57 </td> <td align=\"right\"> 12.3 </td> </tr>\n",
"<tr><td align=\"left\"> 1913 </td> <td align=\"right\"> 76.6 </td> <td align=\"right\"> 19.5 </td> </tr>\n",
"<tr><td align=\"left\"> 1914 </td> <td align=\"right\"> 52.3 </td> <td align=\"right\"> 45.7 </td> </tr>\n",
"<tr><td align=\"left\"> 1915 </td> <td align=\"right\"> 19.5 </td> <td align=\"right\"> 51.1 </td> </tr>\n",
"<tr><td align=\"left\"> 1916 </td> <td align=\"right\"> 11.2 </td> <td align=\"right\"> 29.7 </td> </tr>\n",
"<tr><td align=\"left\"> 1917 </td> <td align=\"right\"> 7.6 </td> <td align=\"right\"> 15.8 </td> </tr>\n",
"<tr><td align=\"left\"> 1918 </td> <td align=\"right\"> 14.6 </td> <td align=\"right\"> 9.7 </td> </tr>\n",
"<tr><td align=\"left\"> 1919 </td> <td align=\"right\"> 16.2 </td> <td align=\"right\"> 10.1 </td> </tr>\n",
"<tr><td align=\"left\"> 1920 </td> <td align=\"right\"> 24.7 </td> <td align=\"right\"> 8.6 </td> </tr>\n",
"</tbody>\n",
"</table>\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Plotting the data"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"from matplotlib import pyplot as plt\n",
"\n",
"# Load in data file\n",
"data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)\n",
"# Make arrays containing x-axis and hares and lynx populations\n",
"year = data[:,0]\n",
"hares = data[:,1]\n",
"lynx = data[:,2]\n",
"\n",
"plt.plot(year, hares ,'b-+', year, lynx, 'r-o')\n",
"plt.axis([1900,1920,0, 100.0])\n",
"plt.xlabel(r'Year')\n",
"plt.ylabel(r'Numbers of hares and lynx ')\n",
"plt.legend(('Hares','Lynx'), loc='upper right')\n",
"plt.title(r'Population of hares and lynx from 1900-1920 (x1000)}')\n",
"plt.savefig('Hudson_Bay_data.pdf')\n",
"plt.savefig('Hudson_Bay_data.png')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Hares and lynx in Hudson bay from 1900 to 1920\n",
"\n",
"<!-- dom:FIGURE: [fig/Hudson_Bay_data.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<p></p>\n",
"<img src=\"fig/Hudson_Bay_data.png\" width=700>\n",
"\n",
"<!-- end figure -->\n",
"\n",
"\n",
"\n",
"\n",
"## Why now create a computer model for the hare and lynx populations?\n",
"We see from the plot that there are indeed fluctuations.\n",
"We would like to create a mathematical model that explains these\n",
"population fluctuations. Ecologists have predicted that in a simple\n",
"predator-prey system that a rise in prey population is followed (with\n",
"a lag) by a rise in the predator population. When the predator\n",
"population is sufficiently high, then the prey population begins\n",
"dropping. After the prey population falls, then the predator\n",
"population falls, which allows the prey population to recover and\n",
"complete one cycle of this interaction. Thus, we see that\n",
"qualitatively oscillations occur. Can a mathematical model predict\n",
"this? What causes cycles to slow or speed up? What affects the\n",
"amplitude of the oscillation or do you expect to see the oscillations\n",
"damp to a stable equilibrium? The models tend to ignore factors like\n",
"climate and other complicating factors. How significant are these?\n",
"\n",
" * We see oscillations in the data\n",
"\n",
" * What causes cycles to slow or speed up?\n",
"\n",
" * What affects the amplitude of the oscillation or do you expect to see the oscillations damp to a stable equilibrium?\n",
"\n",
" * With a model we can better *understand the data*\n",
"\n",
" * More important: we can understand the ecology dynamics of\n",
" predator-pray populations\n",
"\n",
"\n",
"\n",
"\n",
"## The traditional (top-down) approach\n",
"\n",
"The classical way (in all books) is to present the Lotka-Volterra equations:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{align*}\n",
"\\frac{dH}{dt} &= H(a - b L)\\\\\n",
"\\frac{dL}{dt} &= - L(d - c H)\n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here,\n",
"\n",
" * $H$ is the number of preys\n",
"\n",
" * $L$ the number of predators\n",
"\n",
" * $a$, $b$, $d$, $c$ are parameters\n",
"\n",
"Most books quickly establish the model and then use considerable space on\n",
"discussing the qualitative properties of this *nonlinear system of\n",
"ODEs* (which cannot be solved)\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Basic mathematics notation\n",
" * Time points: $t_0,t_1,\\ldots,t_m$\n",
"\n",
" * Uniform distribution of time points: $t_n=n\\Delta t$\n",
"\n",
" * $H^n$: population of hares at time $t_n$\n",
"\n",
" * $L^n$: population of lynx at time $t_n$\n",
"\n",
" * We want to model the changes in populations, $\\Delta H=H^{n+1}-H^n$\n",
" and $\\Delta L=L^{n+1}-L^n$ during a general time interval $[t_{n+1},t_n]$\n",
" of length $\\Delta t=t_{n+1}-t_n$\n",
"\n",
"\n",
"\n",
"## Basic dynamics of the population of hares\n",
"\n",
"The population of hares evolves due to births and deaths exactly as a bacteria population:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\Delta H = a \\Delta t H^n\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"However, hares have an additional loss in the population because\n",
"they are eaten by lynx.\n",
"All the hares and lynx can form\n",
"$H\\cdot L$ pairs in total. When such pairs meet during a time\n",
"interval $\\Delta t$, there is some\n",
"small probablity that the lynx will eat the hare.\n",
"So in fraction $b\\Delta t HL$, the lynx eat hares. This\n",
"loss of hares must be accounted for. Subtracted in the equation for hares:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\Delta H = a\\Delta t H^n - b \\Delta t H^nL^n\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Basic dynamics of the population of lynx\n",
"\n",
"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.\n",
"In a time interval $\\Delta t HL$ hares and lynx can meet, and in a\n",
"fraction $b\\Delta t HL$ the lynx eats the hare. All of this does not\n",
"contribute to the growth of lynx, again just a fraction of\n",
"$b\\Delta t HL$ that we write as\n",
"$d\\Delta t HL$. In addition, lynx die just as in the population\n",
"dynamics with one isolated animal population, leading to a loss\n",
"$-c\\Delta t L$.\n",
"\n",
"\n",
"\n",
"The accounting of lynx then looks like"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\Delta L = d\\Delta t H^nL^n - c\\Delta t L^n\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Evolution equations\n",
"\n",
"By writing up the definition of $\\Delta H$ and $\\Delta L$, and putting\n",
"all assumed known terms $H^n$ and $L^n$ on the right-hand side, we have"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"H^{n+1} = H^n + a\\Delta t H^n - b\\Delta t H^n L^n\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"L^{n+1} = L^n + d\\Delta t H^nL^n - c\\Delta t L^n\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note:\n",
"\n",
" * These equations are ready to be implemented!\n",
"\n",
" * But to start, we need $H^0$ and $L^0$ \n",
" (which we can get from the data)\n",
"\n",
" * We also need values for $a$, $b$, $d$, $c$\n",
"\n",
"\n",
"\n",
"## Adapt the model to the Hudson Bay case\n",
"\n",
" * As always, models tend to be general - as here, applicable\n",
" to \"all\" predator-pray systems\n",
"\n",
" * The critical issue is whether the *interaction* between hares and lynx\n",
" is sufficiently well modeled by $\\hbox{const}HL$\n",
"\n",
" * The parameters $a$, $b$, $d$, and $c$ must be\n",
" estimated from data\n",
"\n",
" * Measure time in years\n",
"\n",
" * $t_0=1900$, $t_m=1920$\n",
"\n",
"\n",
"\n",
"## The program"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"def solver(m, H0, L0, dt, a, b, c, d, t0):\n",
" \"\"\"Solve the difference equations for H and L over m years\n",
" with time step dt (measured in years.\"\"\"\n",
"\n",
" num_intervals = int(m/float(dt))\n",
" t = np.linspace(t0, t0 + m, num_intervals+1)\n",
" H = np.zeros(t.size)\n",
" L = np.zeros(t.size)\n",
"\n",
" print('Init:', H0, L0, dt)\n",
" H[0] = H0\n",
" L[0] = L0\n",
"\n",
" for n in range(0, len(t)-1):\n",
" H[n+1] = H[n] + a*dt*H[n] - b*dt*H[n]*L[n]\n",
" L[n+1] = L[n] + d*dt*H[n]*L[n] - c*dt*L[n]\n",
" return H, L, t\n",
"\n",
"# Load in data file\n",
"data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)\n",
"# Make arrays containing x-axis and hares and lynx populations\n",
"t_e = data[:,0]\n",
"H_e = data[:,1]\n",
"L_e = data[:,2]\n",
"\n",
"# Simulate using the model\n",
"H, L, t = solver(m=20, H0=34.91, L0=3.857, dt=0.1,\n",
" a=0.4807, b=0.02482, c=0.9272, d=0.02756,\n",
" t0=1900)\n",
"\n",
"# Visualize simulations and data\n",
"plt.plot(t_e, H_e, 'b-+', t_e, L_e, 'r-o', t, H, 'm--', t, L, 'k--')\n",
"plt.xlabel('Year')\n",
"plt.ylabel('Numbers of hares and lynx')\n",
"plt.axis([1900, 1920, 0, 140])\n",
"plt.title(r'Population of hares and lynx 1900-1920 (x1000)')\n",
"plt.legend(('H_e', 'L_e', 'H', 'L'), loc='upper left')\n",
"plt.savefig('Hudson_Bay_sim.pdf')\n",
"plt.savefig('Hudson_Bay_sim.png')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The plot\n",
"\n",
"<!-- dom:FIGURE: [fig/Hudson_Bay_sim.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<p></p>\n",
"<img src=\"fig/Hudson_Bay_sim.png\" width=700>\n",
"\n",
"<!-- end figure -->\n",
"\n",
"\n",
"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.\n",
"\n",
"\n",
"## Linear regression in Python"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from IPython.display import display\n",
"import sklearn\n",
"from sklearn.linear_model import LinearRegression\n",
"from sklearn.tree import DecisionTreeRegressor\n",
"\n",
"\n",
"data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)\n",
"x = data[:,0]\n",
"y = data[:,1]\n",
"line = np.linspace(1900,1920,1000,endpoint=False).reshape(-1,1)\n",
"reg = DecisionTreeRegressor(min_samples_split=3).fit(x.reshape(-1,1),y.reshape(-1,1))\n",
"plt.plot(line, reg.predict(line), label=\"decision tree\")\n",
"regline = LinearRegression().fit(x.reshape(-1,1),y.reshape(-1,1))\n",
"plt.plot(line, regline.predict(line), label= \"Linear Regression\")\n",
"plt.plot(x, y, label= \"Linear Regression\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Linear Least squares in R"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" HudsonBay = read.csv(\"src/Hudson_Bay.csv\",header=T)\n",
" fix(HudsonBay)\n",
" dim(HudsonBay)\n",
" names(HudsonBay)\n",
" plot(HudsonBay$Year, HudsonBay$Hares..x1000.)\n",
" attach(HudsonBay)\n",
" plot(Year, Hares..x1000.)\n",
" plot(Year, Hares..x1000., col=\"red\", varwidth=T, xlab=\"Years\", ylab=\"Haresx 1000\")\n",
" summary(HudsonBay)\n",
" summary(Hares..x1000.)\n",
" library(MASS)\n",
" library(ISLR)\n",
" scatter.smooth(x=Year, y = Hares..x1000.)\n",
" linearMod = lm(Hares..x1000. ~ Year)\n",
" print(linearMod)\n",
" summary(linearMod)\n",
" plot(linearMod)\n",
" confint(linearMod)\n",
" predict(linearMod,data.frame(Year=c(1910,1914,1920)),interval=\"confidence\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Non-Linear Least squares in R"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" set.seed(1485)\n",
" len = 24\n",
" x = runif(len)\n",
" y = x^3+rnorm(len, 0,0.06)\n",
" ds = data.frame(x = x, y = y)\n",
" str(ds)\n",
" plot( y ~ x, main =\"Known cubic with noise\")\n",
" s = seq(0,1,length =100)\n",
" lines(s, s^3, lty =2, col =\"green\")\n",
" m = nls(y ~ I(x^power), data = ds, start = list(power=1), trace = T)\n",
" class(m)\n",
" summary(m)\n",
" power = round(summary(m)$coefficients[1], 3)\n",
" power.se = round(summary(m)$coefficients[2], 3)\n",
" plot(y ~ x, main = \"Fitted power model\", sub = \"Blue: fit; green: known\")\n",
" s = seq(0, 1, length = 100)\n",
" lines(s, s^3, lty = 2, col = \"green\")\n",
" lines(s, predict(m, list(x = s)), lty = 1, col = \"blue\")\n",
" text(0, 0.5, paste(\"y =x^ (\", power, \" +/- \", power.se, \")\", sep = \"\"), pos = 4)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example: ecoli lab experiment\n",
"\n",
"\n",
"**Typical pattern:**\n",
"\n",
"The population grows faster and faster. [Why? Is there an underlying (general) mechanism](http://www.zo.utexas.edu/courses/Thoc/PopGrowth.html)?\n",
"\n",
"\n",
"1. Cells divide after $T$ seconds on average (one generation)\n",
"\n",
"2. $2N$ celles divide into twice as many new cells $\\Delta N$ in a time\n",
" interval $\\Delta t$ as $N$ cells would: $\\Delta N \\propto N$\n",
"\n",
"3. $N$ cells result in twice as many new individuals $\\Delta N$ in\n",
" time $2\\Delta t$ as in time $\\Delta t$: $\\Delta N \\propto\\Delta t$\n",
"\n",
"4. Same proportionality wrt death (repeat reasoning)\n",
"\n",
"5. Proposed model: $\\Delta N = b\\Delta t N - d\\Delta tN$ for some unknown\n",
" constants $b$ (births) and $d$ (deaths)\n",
"\n",
"6. Describe evolution in discrete time: $t_n=n\\Delta t$\n",
"\n",
"7. Program-friendly notation: $N$ at $t_n$ is $N^n$\n",
"\n",
"8. Math model: $N^{n+1} = N^n + r\\Delta t\\, N$ (with $\\ r=b-d$)\n",
"\n",
"9. Program model: `N[n+1] = N[n] + r*dt*N[n]`\n",
"\n",
"\n",
"\n",
"## The program\n",
"\n",
"Let us solve the difference equation in as simple way as possible,\n",
"just to train some programming: $r=1.5$, $N^0=1$, $\\Delta t=0.5$"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"t = np.linspace(0, 10, 21) # 20 intervals in [0, 10]\n",
"dt = t[1] - t[0]\n",
"N = np.zeros(t.size)\n",
"\n",
"N[0] = 1\n",
"r = 0.5\n",
"\n",
"for n in range(0, N.size-1, 1):\n",
" N[n+1] = N[n] + r*dt*N[n]\n",
" print 'N[%d]=%.1f' % (n+1, N[n+1])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"% if FORMAT != 'ipynb':\n",
"## The output"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" N[1]=1.2\n",
" N[2]=1.6\n",
" N[3]=2.0\n",
" N[4]=2.4\n",
" N[5]=3.1\n",
" N[6]=3.8\n",
" N[7]=4.8\n",
" N[8]=6.0\n",
" N[9]=7.5\n",
" N[10]=9.3\n",
" N[11]=11.6\n",
" N[12]=14.6\n",
" N[13]=18.2\n",
" N[14]=22.7\n",
" N[15]=28.4\n",
" N[16]=35.5\n",
" N[17]=44.4\n",
" N[18]=55.5\n",
" N[19]=69.4\n",
" N[20]=86.7\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"% endif\n",
"\n",
"## Parameter estimation\n",
"\n",
" * We do not know $r$\n",
"\n",
" * How can we estimate $r$ from data?\n",
"\n",
"We can use the difference equation with the experimental data"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"N^{n+1} = N^n + r\\Delta t N^n\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Say $N^{n+1}$ and $N^n$ are known from data, solve wrt $r$:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"r = \\frac{N^{n+1}-N^n}{N^n\\Delta t}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Use experimental data in the fraction, say $t_1=600$, $t_2=1200$,\n",
"$N^1=140$, $N^2=250$: $r=0.0013$.\n",
"\n",
"\n",
"\n",
"\n",
"## A program relevant for the biological problem\n",
"\n",
"<!-- exact r = 0.000694 -->"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"# Estimate r\n",
"data = np.loadtxt('ecoli.csv', delimiter=',')\n",
"t_e = data[:,0]\n",
"N_e = data[:,1]\n",
"i = 2 # Data point (i,i+1) used to estimate r\n",
"r = (N_e[i+1] - N_e[i])/(N_e[i]*(t_e[i+1] - t_e[i]))\n",
"print 'Estimated r=%.5f' % r\n",
"# Can experiment with r values and see if the model can\n",
"# match the data better\n",
"\n",
"T = 1200 # cell can divide after T sec\n",
"t_max = 5*T # 5 generations in experiment\n",
"t = np.linspace(0, t_max, 1000)\n",
"dt = t[1] - t[0]\n",
"N = np.zeros(t.size)\n",
"\n",
"N[0] = 100\n",
"for n in range(0, len(t)-1, 1):\n",
" N[n+1] = N[n] + r*dt*N[n]\n",
"\n",
"import matplotlib.pyplot as plt\n",
"plt.plot(t, N, 'r-', t_e, N_e, 'bo')\n",
"plt.xlabel('time [s]'); plt.ylabel('N')\n",
"plt.legend(['model', 'experiment'], loc='upper left')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Change `r` in the program and play around to make a better fit!\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Simulating financial transcations\n",
"\n",
"The aim here is to simulate financial transactions among financial agents\n",
"using Monte Carlo methods. The final goal is to extract a distribution of income as function\n",
"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\n",
"that the higher end of the distribution of money follows a distribution"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"w_m\\propto m^{-1-\\alpha},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"with $\\alpha\\in [1,2]$. We will here follow the analysis made by [Patriarca and collaborators](http://www.sciencedirect.com/science/article/pii/S0378437104004327). \n",
"\n",
"Here we will study numerically the relation between the micro-dynamic relations among financial \n",
"agents and the resulting macroscopic money distribution.\n",
"\n",
"We assume we have $N$ agents that exchange money in pairs $(i,j)$. We assume also that all agents\n",
"start with the same amount of money $m_0 > 0$. At a given 'time step', we choose randomly a pair\n",
"of agents $(i,j)$ and let a transaction take place. This means that agent $i$'s money $m_i$ changes\n",
"to $m_i'$ and similarly we have $m_j\\rightarrow m_j'$. \n",
"Money is conserved during a transaction, meaning that"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- Equation labels as ordinary links -->\n",
"<div id=\"eq:conserve\"></div>\n",
"\n",
"$$\n",
"\\begin{equation}\n",
" m_i+m_j=m_i'+m_j'.\n",
"\\label{eq:conserve} \\tag{1}\n",
"\\end{equation}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The change is done via a random reassignement (a random number) $\\epsilon$, meaning that"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"m_i' = \\epsilon(m_i+m_j),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"leading to"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"m_j'= (1-\\epsilon)(m_i+m_j).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The number $\\epsilon$ is extracted from a uniform distribution.\n",
"In this simple model, no agents are left with a debt, that is $m\\ge 0$.\n",
"Due to the conservation law above, one can show that the system relaxes toward an equilibrium\n",
"state given by a Gibbs distribution"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"w_m=\\beta \\exp{(-\\beta m)},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"with"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\beta = \\frac{1}{\\langle m\\rangle},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and $\\langle m\\rangle=\\sum_i m_i/N=m_0$, the average money.\n",
"It means that after equilibrium has been reached that the majority of agents is left with a small\n",
"number of money, while the number of richest agents, those with $m$ larger than a specific value $m'$,\n",
"exponentially decreases with $m'$.\n",
"\n",
"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\n",
"several runs of the above simulations, at least $10^3-10^4$ runs (experiments).\n",
"\n",
"\n",
"\n",
"\n",
"### Simulation of Transactions\n",
"\n",
"Our task is to first set up an algorithm which simulates the above transactions with an initial\n",
" amount $m_0$.\n",
" The challenge here is to figure out a Monte Carlo simulation based on the\n",
" above equations.\n",
" You will in particular need to make an algorithm which sets up a histogram as function of $m$.\n",
" This histogram contains the number of times a value $m$ is registered and represents\n",
" $w_m\\Delta m$. You will need to set up a value for the interval $\\Delta m$ (typically $0.01-0.05$).\n",
" That means you need to account for the number of times you register an income in the interval\n",
" $m,m+\\Delta m$. The number of times you register this income, represents the value that enters the histogram.\n",
" You will also need to find a criterion for when the equilibrium situation has been reached."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"#!/usr/bin/env python\n",
"import numpy as np\n",
"import matplotlib.mlab as mlab\n",
"import matplotlib.pyplot as plt\n",
"import random\n",
"\n",
"# initialize the rng with a seed\n",
"random.seed()\n",
"# Hard coding of input parameters\n",
"Agents = 500\n",
"MCcounts = 1000\n",
"Transactions = 100000\n",
"startMoney = 1.0\n",
"Lambda = 0.0\n",
"FinancialAgents = startMoney*np.ones(Agents)\n",
"for i in range (1, MCcounts, 1):\n",
" for j in range (1, Transactions, 1):\n",
" agent_i = int(Agents*random.random())\n",
" agent_j = int(Agents*random.random())\n",
" epsilon = random.random()\n",
" if agent_i != agent_j:\n",
" m1 = Lambda*FinancialAgents[agent_i] + (1-Lambda)*epsilon*(FinancialAgents[agent_i] + FinancialAgents[agent_j])\n",
" m2 = Lambda*FinancialAgents[agent_j] + (1-Lambda)*(1-epsilon)*(FinancialAgents[agent_i] + FinancialAgents[agent_j])\n",
" FinancialAgents[agent_i] = m1\n",
" FinancialAgents[agent_j] = m2\n",
"\n",
"# the histogram of the data\n",
"n, bins, patches = plt.hist(FinancialAgents, 50, facecolor='green')\n",
"\n",
"plt.xlabel('$x$')\n",
"plt.ylabel('Distribution of wealth')\n",
"plt.title(r'Money')\n",
"plt.axis([0, 10, 0, 500])\n",
"plt.grid(True)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can then change our model to allow for a saving criterion, meaning that the agents save\n",
" 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.\n",
"\n",
" The conservation law of Eq. ([eq:conserve](#eq:conserve)) holds, but the money to be shared in a transaction between\n",
" agent $i$ and agent $j$ is now $(1-\\lambda)(m_i+m_j)$. This means that we have"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"m_i' = \\lambda m_i+\\epsilon(1-\\lambda)(m_i+m_j),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"m_j' = \\lambda m_j+(1-\\epsilon)(1-\\lambda)(m_i+m_j),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which can be written as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"m_i'=m_i+\\delta m\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"m_j'=m_j-\\delta m,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"with"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\delta m=(1-\\lambda)(\\epsilon m_j-(1-\\epsilon)m_i),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"showing how money is conserved during a transaction.\n",
" Select values of $\\lambda =0.25,0.5$ and $\\lambda=0.9$ and try to extract the corresponding\n",
" equilibrium distributions and compare these with the Gibbs distribution. Comment your results.\n",
"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.\n",
"\n",
"In the studies above the agents were selected randomly, irrespective of whether we allowed for\n",
"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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"p_{ij} \\propto \\vert m_i-m_j\\vert^{-\\alpha},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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). \n",
"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$. \n",
"You should try to reproduce Figure 1 of [Goswami and Sen](http://www.sciencedirect.com/science/article/pii/S0378437114006967). \n",
"Extract the tail of the distribution and see if it follows a Pareto distribution"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"w_m\\propto m^{-1-\\alpha}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What happens if $\\alpha \\gg 1$?\n",
"\n",
"Perform the analysis with and without a saving $\\lambda$ on each transaction and comment your results. \n",
"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. \n",
"We add this feature by modifying the previous likelihood to"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"p_{ij} \\propto \\vert m_i-m_j\\vert^{-\\alpha}\\left(c_{ij}+1\\right)^{\\gamma},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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). \n",
"\n",
"## Particle in one dimension an velocity distribution"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Program to test the Metropolis algorithm with one particle at given temp in one dimension\n",
"import numpy as np\n",
"import matplotlib.mlab as mlab\n",
"import matplotlib.pyplot as plt\n",
"import random\n",
"from math import sqrt, exp, log\n",
"# initialize the rng with a seed\n",
"random.seed()\n",
"# Hard coding of input parameters\n",
"MCcycles = 100000\n",
"Temperature = 2.0\n",
"beta = 1./Temperature\n",
"InitialVelocity = -2.0\n",
"CurrentVelocity = InitialVelocity\n",
"Energy = 0.5*InitialVelocity*InitialVelocity\n",
"VelocityRange = 10*sqrt(Temperature)\n",
"VelocityStep = 2*VelocityRange/10.\n",
"AverageEnergy = Energy\n",
"AverageEnergy2 = Energy*Energy\n",
"VelocityValues = np.zeros(MCcycles)\n",
"# The Monte Carlo sampling with Metropolis starts here\n",
"for i in range (1, MCcycles, 1):\n",
" TrialVelocity = CurrentVelocity + (2.0*random.random() - 1.0)*VelocityStep\n",
" EnergyChange = 0.5*(TrialVelocity*TrialVelocity -CurrentVelocity*CurrentVelocity);\n",
" if random.random() <= exp(-beta*EnergyChange):\n",
" CurrentVelocity = TrialVelocity\n",
" Energy += EnergyChange\n",
" VelocityValues[i] = CurrentVelocity\n",
" AverageEnergy += Energy\n",
" AverageEnergy2 += Energy*Energy\n",
"#Final averages\n",
"AverageEnergy = AverageEnergy/MCcycles\n",
"AverageEnergy2 = AverageEnergy2/MCcycles\n",
"Variance = AverageEnergy2 - AverageEnergy*AverageEnergy\n",
"print(AverageEnergy, Variance)\n",
"n, bins, patches = plt.hist(VelocityValues, 400, facecolor='green')\n",
"\n",
"plt.xlabel('$v$')\n",
"plt.ylabel('Velocity distribution P(v)')\n",
"plt.title(r'Velocity histogram at $k_BT=2$')\n",
"plt.axis([-5, 5, 0, 600])\n",
"plt.grid(True)\n",
"plt.show()"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}