diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs000.html b/doc/pub/How2ReadData/html/._How2ReadData-bs000.html index 2e49e32ac..1e3353733 100644 --- a/doc/pub/How2ReadData/html/._How2ReadData-bs000.html +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs000.html @@ -46,45 +46,39 @@ Automatically generated HTML file from DocOnce source ('Software and needed installations', 2, None, '___sec3'), ('Python installers', 2, None, '___sec4'), ('Installing R, C++, cython or Julia', 2, None, '___sec5'), + ('Installing R, C++, cython or Julia', 2, None, '___sec6'), ('Introduction to Jupyter notebook and available tools', 2, None, - '___sec6'), - ('Doing it in R', 2, None, '___sec7'), - ('Representing data, overarching aims', 2, None, '___sec8'), - ('Representing data, more examples', 2, None, '___sec9'), - ('Binning of data', 2, None, '___sec10'), - ('Adding model complexity: Predator-Prey model from ecology', - 2, - None, - '___sec11'), - ('Case study from Hudson bay', 2, None, '___sec12'), - ('Hudson bay data', 2, None, '___sec13'), - ('Plotting the data', 2, None, '___sec14'), + '___sec7'), + ('Representing data, more examples', 2, None, '___sec8'), + ('Predator-Prey model from ecology', 2, None, '___sec9'), + ('Case study from Hudson bay', 2, None, '___sec10'), + ('Hudson bay data', 2, None, '___sec11'), + ('Plotting the data', 2, None, '___sec12'), ('Hares and lynx in Hudson bay from 1900 to 1920', 2, None, - '___sec15'), + '___sec13'), ('Why now create a computer model for the hare and lynx ' 'populations?', 2, None, - '___sec16'), - ('The traditional (top-down) approach', 2, None, '___sec17'), - ("The ``new'' discrete bottom-up approach", 2, None, '___sec18'), - ('Basic (computer-friendly) mathematics notation', - 2, - None, - '___sec19'), + '___sec14'), + ('The traditional (top-down) approach', 2, None, '___sec15'), + ('Basic mathematics notation', 2, None, '___sec16'), ('Basic dynamics of the population of hares', 2, None, - '___sec20'), - ('Basic dynamics of the population of lynx', 2, None, '___sec21'), - ('Evolution equations', 2, None, '___sec22'), - ('Adapt the model to the Hudson Bay case', 2, None, '___sec23'), - ('The program', 2, None, '___sec24'), - ('The plot', 2, None, '___sec25')]} + '___sec17'), + ('Basic dynamics of the population of lynx', 2, None, '___sec18'), + ('Evolution equations', 2, None, '___sec19'), + ('Adapt the model to the Hudson Bay case', 2, None, '___sec20'), + ('The program', 2, None, '___sec21'), + ('The plot', 2, None, '___sec22'), + ('Linear regression in Python', 2, None, '___sec23'), + ('Linear Least squares in R', 2, None, '___sec24'), + ('Non-Linear Least squares in R', 2, None, '___sec25')]} end of tocinfo --> @@ -128,26 +122,26 @@ MathJax.Hub.Config({
  • Software and needed installations
  • Python installers
  • Installing R, C++, cython or Julia
  • -
  • Introduction to Jupyter notebook and available tools
  • -
  • Doing it in R
  • -
  • Representing data, overarching aims
  • -
  • Representing data, more examples
  • -
  • Binning of data
  • -
  • Adding model complexity: Predator-Prey model from ecology
  • -
  • Case study from Hudson bay
  • -
  • Hudson bay data
  • -
  • Plotting the data
  • -
  • Hares and lynx in Hudson bay from 1900 to 1920
  • -
  • Why now create a computer model for the hare and lynx populations?
  • -
  • The traditional (top-down) approach
  • -
  • The ``new'' discrete bottom-up approach
  • -
  • Basic (computer-friendly) mathematics notation
  • -
  • Basic dynamics of the population of hares
  • -
  • Basic dynamics of the population of lynx
  • -
  • Evolution equations
  • -
  • Adapt the model to the Hudson Bay case
  • -
  • The program
  • -
  • The plot
  • +
  • Installing R, C++, cython or Julia
  • +
  • Introduction to Jupyter notebook and available tools
  • +
  • Representing data, more examples
  • +
  • Predator-Prey model from ecology
  • +
  • Case study from Hudson bay
  • +
  • Hudson bay data
  • +
  • Plotting the data
  • +
  • Hares and lynx in Hudson bay from 1900 to 1920
  • +
  • Why now create a computer model for the hare and lynx populations?
  • +
  • The traditional (top-down) approach
  • +
  • Basic mathematics notation
  • +
  • Basic dynamics of the population of hares
  • +
  • Basic dynamics of the population of lynx
  • +
  • Evolution equations
  • +
  • Adapt the model to the Hudson Bay case
  • +
  • The program
  • +
  • The plot
  • +
  • Linear regression in Python
  • +
  • Linear Least squares in R
  • +
  • Non-Linear Least squares in R
  • @@ -182,7 +176,7 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    -

    Dec 1, 2017

    +

    Dec 6, 2017


    diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs001.html b/doc/pub/How2ReadData/html/._How2ReadData-bs001.html index 75bb1815b..86012612f 100644 --- a/doc/pub/How2ReadData/html/._How2ReadData-bs001.html +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs001.html @@ -46,45 +46,39 @@ Automatically generated HTML file from DocOnce source ('Software and needed installations', 2, None, '___sec3'), ('Python installers', 2, None, '___sec4'), ('Installing R, C++, cython or Julia', 2, None, '___sec5'), + ('Installing R, C++, cython or Julia', 2, None, '___sec6'), ('Introduction to Jupyter notebook and available tools', 2, None, - '___sec6'), - ('Doing it in R', 2, None, '___sec7'), - ('Representing data, overarching aims', 2, None, '___sec8'), - ('Representing data, more examples', 2, None, '___sec9'), - ('Binning of data', 2, None, '___sec10'), - ('Adding model complexity: Predator-Prey model from ecology', - 2, - None, - '___sec11'), - ('Case study from Hudson bay', 2, None, '___sec12'), - ('Hudson bay data', 2, None, '___sec13'), - ('Plotting the data', 2, None, '___sec14'), + '___sec7'), + ('Representing data, more examples', 2, None, '___sec8'), + ('Predator-Prey model from ecology', 2, None, '___sec9'), + ('Case study from Hudson bay', 2, None, '___sec10'), + ('Hudson bay data', 2, None, '___sec11'), + ('Plotting the data', 2, None, '___sec12'), ('Hares and lynx in Hudson bay from 1900 to 1920', 2, None, - '___sec15'), + '___sec13'), ('Why now create a computer model for the hare and lynx ' 'populations?', 2, None, - '___sec16'), - ('The traditional (top-down) approach', 2, None, '___sec17'), - ("The ``new'' discrete bottom-up approach", 2, None, '___sec18'), - ('Basic (computer-friendly) mathematics notation', - 2, - None, - '___sec19'), + '___sec14'), + ('The traditional (top-down) approach', 2, None, '___sec15'), + ('Basic mathematics notation', 2, None, '___sec16'), ('Basic dynamics of the population of hares', 2, None, - '___sec20'), - ('Basic dynamics of the population of lynx', 2, None, '___sec21'), - ('Evolution equations', 2, None, '___sec22'), - ('Adapt the model to the Hudson Bay case', 2, None, '___sec23'), - ('The program', 2, None, '___sec24'), - ('The plot', 2, None, '___sec25')]} + '___sec17'), + ('Basic dynamics of the population of lynx', 2, None, '___sec18'), + ('Evolution equations', 2, None, '___sec19'), + ('Adapt the model to the Hudson Bay case', 2, None, '___sec20'), + ('The program', 2, None, '___sec21'), + ('The plot', 2, None, '___sec22'), + ('Linear regression in Python', 2, None, '___sec23'), + ('Linear Least squares in R', 2, None, '___sec24'), + ('Non-Linear Least squares in R', 2, None, '___sec25')]} end of tocinfo --> @@ -128,26 +122,26 @@ MathJax.Hub.Config({

  • Software and needed installations
  • Python installers
  • Installing R, C++, cython or Julia
  • -
  • Introduction to Jupyter notebook and available tools
  • -
  • Doing it in R
  • -
  • Representing data, overarching aims
  • -
  • Representing data, more examples
  • -
  • Binning of data
  • -
  • Adding model complexity: Predator-Prey model from ecology
  • -
  • Case study from Hudson bay
  • -
  • Hudson bay data
  • -
  • Plotting the data
  • -
  • Hares and lynx in Hudson bay from 1900 to 1920
  • -
  • Why now create a computer model for the hare and lynx populations?
  • -
  • The traditional (top-down) approach
  • -
  • The ``new'' discrete bottom-up approach
  • -
  • Basic (computer-friendly) mathematics notation
  • -
  • Basic dynamics of the population of hares
  • -
  • Basic dynamics of the population of lynx
  • -
  • Evolution equations
  • -
  • Adapt the model to the Hudson Bay case
  • -
  • The program
  • -
  • The plot
  • +
  • Installing R, C++, cython or Julia
  • +
  • Introduction to Jupyter notebook and available tools
  • +
  • Representing data, more examples
  • +
  • Predator-Prey model from ecology
  • +
  • Case study from Hudson bay
  • +
  • Hudson bay data
  • +
  • Plotting the data
  • +
  • Hares and lynx in Hudson bay from 1900 to 1920
  • +
  • Why now create a computer model for the hare and lynx populations?
  • +
  • The traditional (top-down) approach
  • +
  • Basic mathematics notation
  • +
  • Basic dynamics of the population of hares
  • +
  • Basic dynamics of the population of lynx
  • +
  • Evolution equations
  • +
  • Adapt the model to the Hudson Bay case
  • +
  • The program
  • +
  • The plot
  • +
  • Linear regression in Python
  • +
  • Linear Least squares in R
  • +
  • Non-Linear Least squares in R
  • diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs002.html b/doc/pub/How2ReadData/html/._How2ReadData-bs002.html new file mode 100644 index 000000000..c8b03088c --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs002.html @@ -0,0 +1,223 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    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 behavioural 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: + +

    + +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs003.html b/doc/pub/How2ReadData/html/._How2ReadData-bs003.html new file mode 100644 index 000000000..fae85ad48 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs003.html @@ -0,0 +1,224 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Different algorithms

    +In this course 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 + +
      +
    1. Linear regression and its variants
    2. +
    3. Decision tree algorithms, from simpler to more complex ones
    4. +
    5. Nearest neighbors models
    6. +
    7. Bayesian statistics
    8. +
    9. Support vector machines and finally various variants of
    10. +
    11. Artifical neural networks
    12. +
    + +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. + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs004.html b/doc/pub/How2ReadData/html/._How2ReadData-bs004.html new file mode 100644 index 000000000..d76aa681f --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs004.html @@ -0,0 +1,237 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    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 + +

      +
    1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow
    2. +
    + +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 + +

      +
    1. brew install python3
    2. +
    + +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 + +
      +
    1. sudo apt-get install python3 (or python for pyhton2.7)
    2. +
    + +etc etc. + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs005.html b/doc/pub/How2ReadData/html/._How2ReadData-bs005.html new file mode 100644 index 000000000..65ea7a5e7 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs005.html @@ -0,0 +1,214 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    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 + +
      +
    1. Anaconda 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
    2. +
    3. Enthought canopy is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.
    4. +
    + +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs006.html b/doc/pub/How2ReadData/html/._How2ReadData-bs006.html new file mode 100644 index 000000000..e90d87a95 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs006.html @@ -0,0 +1,217 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    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 + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs007.html b/doc/pub/How2ReadData/html/._How2ReadData-bs007.html new file mode 100644 index 000000000..415fb75d9 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs007.html @@ -0,0 +1,226 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    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. + +

    +This never ends. +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. + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs008.html b/doc/pub/How2ReadData/html/._How2ReadData-bs008.html new file mode 100644 index 000000000..704e5b969 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs008.html @@ -0,0 +1,240 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Introduction to Jupyter notebook and available tools

    + +

    +

    +
    +

    +

    + + +

    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)
    +
    +

    +

    +
    + + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs009.html b/doc/pub/How2ReadData/html/._How2ReadData-bs009.html new file mode 100644 index 000000000..243b46d6c --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs009.html @@ -0,0 +1,239 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Representing data, more examples

    +
    +
    +

    +

    + + +

    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()
    +
    +

    +

    +
    + + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs010.html b/doc/pub/How2ReadData/html/._How2ReadData-bs010.html new file mode 100644 index 000000000..a6bbe4f71 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs010.html @@ -0,0 +1,233 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Predator-Prey model from ecology

    + +

    +

    +
    +

    +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
    • +
    +
    +
    + + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs011.html b/doc/pub/How2ReadData/html/._How2ReadData-bs011.html new file mode 100644 index 000000000..f7d18ef03 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs011.html @@ -0,0 +1,230 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Case study from Hudson bay

    + +

    +

    +
    +

    +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 + +

      +
    1. plotting the data
    2. +
    3. derive a simple model for the population dynamics
    4. +
    5. (fitting parameters in the model to the data)
    6. +
    7. using the model predict the evolution other predator-pray systems
    8. +
    +
    +
    + + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs012.html b/doc/pub/How2ReadData/html/._How2ReadData-bs012.html new file mode 100644 index 000000000..f29a11f81 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs012.html @@ -0,0 +1,263 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Hudson bay data

    + +

    +

    +
    +

    + +

    +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)
    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
    +
    +
    +

    +

    +
    + + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs013.html b/doc/pub/How2ReadData/html/._How2ReadData-bs013.html new file mode 100644 index 000000000..73f1bd282 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs013.html @@ -0,0 +1,245 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Plotting the data

    + +

    +

    +
    +

    +

    + + +

    import numpy as np
    +from  matplotlib import pyplot as plt
    +
    +# Load in data file
    +data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)
    +# Make arrays containing x-axis and hares and lynx populations
    +year = data[:,0]
    +hares = data[:,1]
    +lynx = data[:,2]
    +
    +plt.plot(year, hares ,'b-+', year, lynx, 'r-o')
    +plt.axis([1900,1920,0, 100.0])
    +plt.xlabel(r'Year')
    +plt.ylabel(r'Numbers of hares and lynx ')
    +plt.legend(('Hares','Lynx'), loc='upper right')
    +plt.title(r'Population of hares and lynx from 1900-1920 (x1000)}')
    +plt.savefig('Hudson_Bay_data.pdf')
    +plt.savefig('Hudson_Bay_data.png')
    +plt.show()
    +
    +

    +

    +
    + + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs014.html b/doc/pub/How2ReadData/html/._How2ReadData-bs014.html new file mode 100644 index 000000000..553ceff16 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs014.html @@ -0,0 +1,216 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Hares and lynx in Hudson bay from 1900 to 1920

    + +

    +



    + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs015.html b/doc/pub/How2ReadData/html/._How2ReadData-bs015.html new file mode 100644 index 000000000..93a878189 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs015.html @@ -0,0 +1,242 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Why now create a computer model for the hare and lynx populations?

    +
    +
    +

    +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
    • +
    +
    +
    + + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs016.html b/doc/pub/How2ReadData/html/._How2ReadData-bs016.html new file mode 100644 index 000000000..95f9937fd --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs016.html @@ -0,0 +1,242 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    The traditional (top-down) approach

    + +

    +

    +
    +

    +The classical way (in all books) is to present the Lotka-Volterra equations: + +$$ +\begin{align*} +\frac{dH}{dt} &= H(a - b L)\\ +\frac{dL}{dt} &= - L(d - c H) +\end{align*} +$$ + +

    +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) +
    +
    + + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs017.html b/doc/pub/How2ReadData/html/._How2ReadData-bs017.html new file mode 100644 index 000000000..9640d05bf --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs017.html @@ -0,0 +1,227 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Basic mathematics notation

    +
    +
    +

    + +

      +
    • 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 \)
    • +
    +
    +
    + + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs018.html b/doc/pub/How2ReadData/html/._How2ReadData-bs018.html new file mode 100644 index 000000000..761bcf6c0 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs018.html @@ -0,0 +1,234 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Basic dynamics of the population of hares

    + +

    +

    +
    +

    +The population of hares evolves due to births and deaths exactly as a bacteria population: + +$$ +\Delta H = a \Delta t H^n +$$ + +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: + +$$ \Delta H = a\Delta t H^n - b \Delta t H^nL^n$$ +

    +
    + + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs019.html b/doc/pub/How2ReadData/html/._How2ReadData-bs019.html new file mode 100644 index 000000000..aa792fadd --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs019.html @@ -0,0 +1,235 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Basic dynamics of the population of lynx

    + +

    +

    +
    +

    +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 \). +

    +
    + + +

    +

    +
    +

    +The accounting of lynx then looks like +$$ \Delta L = d\Delta t H^nL^n - c\Delta t L^n$$ +

    +
    + + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs020.html b/doc/pub/How2ReadData/html/._How2ReadData-bs020.html new file mode 100644 index 000000000..0ef4184b1 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs020.html @@ -0,0 +1,233 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Evolution equations

    + +

    +

    +
    +

    +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 + +$$ H^{n+1} = H^n + a\Delta t H^n - b\Delta t H^n L^n $$ + + +$$ L^{n+1} = L^n + d\Delta t H^nL^n - c\Delta t L^n $$ + +

    +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 \)
    • +
    +
    +
    + + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs021.html b/doc/pub/How2ReadData/html/._How2ReadData-bs021.html new file mode 100644 index 000000000..d710d8224 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs021.html @@ -0,0 +1,226 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Adapt the model to the Hudson Bay case

    + +

    +

    +
    +

    + +

      +
    • 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 \)
    • +
    +
    +
    + + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs022.html b/doc/pub/How2ReadData/html/._How2ReadData-bs022.html new file mode 100644 index 000000000..3af1c1481 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs022.html @@ -0,0 +1,262 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    The program

    + +

    +

    +
    +

    +

    + + +

    import numpy as np
    +import matplotlib.pyplot as plt
    +
    +def solver(m, H0, L0, dt, a, b, c, d, t0):
    +    """Solve the difference equations for H and L over m years
    +    with time step dt (measured in years."""
    +
    +    num_intervals = int(m/float(dt))
    +    t = np.linspace(t0, t0 + m, num_intervals+1)
    +    H = np.zeros(t.size)
    +    L = np.zeros(t.size)
    +
    +    print('Init:', H0, L0, dt)
    +    H[0] = H0
    +    L[0] = L0
    +
    +    for n in range(0, len(t)-1):
    +        H[n+1] = H[n] + a*dt*H[n] - b*dt*H[n]*L[n]
    +        L[n+1] = L[n] + d*dt*H[n]*L[n] - c*dt*L[n]
    +    return H, L, t
    +
    +# Load in data file
    +data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)
    +# Make arrays containing x-axis and hares and lynx populations
    +t_e = data[:,0]
    +H_e = data[:,1]
    +L_e = data[:,2]
    +
    +# Simulate using the model
    +H, L, t = solver(m=20, H0=34.91, L0=3.857, dt=0.1,
    +                 a=0.4807, b=0.02482, c=0.9272, d=0.02756,
    +                 t0=1900)
    +
    +# Visualize simulations and data
    +plt.plot(t_e, H_e, 'b-+', t_e, L_e, 'r-o', t, H, 'm--', t, L, 'k--')
    +plt.xlabel('Year')
    +plt.ylabel('Numbers of hares and lynx')
    +plt.axis([1900, 1920, 0, 140])
    +plt.title(r'Population of hares and lynx 1900-1920 (x1000)')
    +plt.legend(('H_e', 'L_e', 'H', 'L'), loc='upper left')
    +plt.savefig('Hudson_Bay_sim.pdf')
    +plt.savefig('Hudson_Bay_sim.png')
    +plt.show()
    +
    +

    +

    +
    + + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs023.html b/doc/pub/How2ReadData/html/._How2ReadData-bs023.html new file mode 100644 index 000000000..3d973a91d --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs023.html @@ -0,0 +1,211 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    The plot

    + +

    +



    + +

    +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. + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs024.html b/doc/pub/How2ReadData/html/._How2ReadData-bs024.html new file mode 100644 index 000000000..60b16cc52 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs024.html @@ -0,0 +1,233 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Linear regression in Python

    +
    +
    +

    +

    + + +

    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()
    +
    +

    +

    +
    + + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs025.html b/doc/pub/How2ReadData/html/._How2ReadData-bs025.html new file mode 100644 index 000000000..d6b8cf5bb --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs025.html @@ -0,0 +1,233 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Linear Least squares in 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")
    +
    +

    +

    +
    + + +

    +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs026.html b/doc/pub/How2ReadData/html/._How2ReadData-bs026.html new file mode 100644 index 000000000..5b0df88f8 --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs026.html @@ -0,0 +1,232 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Non-Linear Least squares in 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)
    +
    +

    +

    +
    + + +

    + +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/._How2ReadData-bs027.html b/doc/pub/How2ReadData/html/._How2ReadData-bs027.html new file mode 100644 index 000000000..27432af8a --- /dev/null +++ b/doc/pub/How2ReadData/html/._How2ReadData-bs027.html @@ -0,0 +1,237 @@ + + + + + + + +Data Analysis and Machine Learning: Introduction and Representing data + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

     

     

     

    + + + + +

    Non-Linear Least squares in 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)
    +
    +

    +

    +
    + + +

    + +

    + +

    + + +
    + + + + + + + +
    + +
    + + + + + + diff --git a/doc/pub/How2ReadData/html/How2ReadData-bs.html b/doc/pub/How2ReadData/html/How2ReadData-bs.html index 2e49e32ac..1e3353733 100644 --- a/doc/pub/How2ReadData/html/How2ReadData-bs.html +++ b/doc/pub/How2ReadData/html/How2ReadData-bs.html @@ -46,45 +46,39 @@ Automatically generated HTML file from DocOnce source ('Software and needed installations', 2, None, '___sec3'), ('Python installers', 2, None, '___sec4'), ('Installing R, C++, cython or Julia', 2, None, '___sec5'), + ('Installing R, C++, cython or Julia', 2, None, '___sec6'), ('Introduction to Jupyter notebook and available tools', 2, None, - '___sec6'), - ('Doing it in R', 2, None, '___sec7'), - ('Representing data, overarching aims', 2, None, '___sec8'), - ('Representing data, more examples', 2, None, '___sec9'), - ('Binning of data', 2, None, '___sec10'), - ('Adding model complexity: Predator-Prey model from ecology', - 2, - None, - '___sec11'), - ('Case study from Hudson bay', 2, None, '___sec12'), - ('Hudson bay data', 2, None, '___sec13'), - ('Plotting the data', 2, None, '___sec14'), + '___sec7'), + ('Representing data, more examples', 2, None, '___sec8'), + ('Predator-Prey model from ecology', 2, None, '___sec9'), + ('Case study from Hudson bay', 2, None, '___sec10'), + ('Hudson bay data', 2, None, '___sec11'), + ('Plotting the data', 2, None, '___sec12'), ('Hares and lynx in Hudson bay from 1900 to 1920', 2, None, - '___sec15'), + '___sec13'), ('Why now create a computer model for the hare and lynx ' 'populations?', 2, None, - '___sec16'), - ('The traditional (top-down) approach', 2, None, '___sec17'), - ("The ``new'' discrete bottom-up approach", 2, None, '___sec18'), - ('Basic (computer-friendly) mathematics notation', - 2, - None, - '___sec19'), + '___sec14'), + ('The traditional (top-down) approach', 2, None, '___sec15'), + ('Basic mathematics notation', 2, None, '___sec16'), ('Basic dynamics of the population of hares', 2, None, - '___sec20'), - ('Basic dynamics of the population of lynx', 2, None, '___sec21'), - ('Evolution equations', 2, None, '___sec22'), - ('Adapt the model to the Hudson Bay case', 2, None, '___sec23'), - ('The program', 2, None, '___sec24'), - ('The plot', 2, None, '___sec25')]} + '___sec17'), + ('Basic dynamics of the population of lynx', 2, None, '___sec18'), + ('Evolution equations', 2, None, '___sec19'), + ('Adapt the model to the Hudson Bay case', 2, None, '___sec20'), + ('The program', 2, None, '___sec21'), + ('The plot', 2, None, '___sec22'), + ('Linear regression in Python', 2, None, '___sec23'), + ('Linear Least squares in R', 2, None, '___sec24'), + ('Non-Linear Least squares in R', 2, None, '___sec25')]} end of tocinfo --> @@ -128,26 +122,26 @@ MathJax.Hub.Config({
  • Software and needed installations
  • Python installers
  • Installing R, C++, cython or Julia
  • -
  • Introduction to Jupyter notebook and available tools
  • -
  • Doing it in R
  • -
  • Representing data, overarching aims
  • -
  • Representing data, more examples
  • -
  • Binning of data
  • -
  • Adding model complexity: Predator-Prey model from ecology
  • -
  • Case study from Hudson bay
  • -
  • Hudson bay data
  • -
  • Plotting the data
  • -
  • Hares and lynx in Hudson bay from 1900 to 1920
  • -
  • Why now create a computer model for the hare and lynx populations?
  • -
  • The traditional (top-down) approach
  • -
  • The ``new'' discrete bottom-up approach
  • -
  • Basic (computer-friendly) mathematics notation
  • -
  • Basic dynamics of the population of hares
  • -
  • Basic dynamics of the population of lynx
  • -
  • Evolution equations
  • -
  • Adapt the model to the Hudson Bay case
  • -
  • The program
  • -
  • The plot
  • +
  • Installing R, C++, cython or Julia
  • +
  • Introduction to Jupyter notebook and available tools
  • +
  • Representing data, more examples
  • +
  • Predator-Prey model from ecology
  • +
  • Case study from Hudson bay
  • +
  • Hudson bay data
  • +
  • Plotting the data
  • +
  • Hares and lynx in Hudson bay from 1900 to 1920
  • +
  • Why now create a computer model for the hare and lynx populations?
  • +
  • The traditional (top-down) approach
  • +
  • Basic mathematics notation
  • +
  • Basic dynamics of the population of hares
  • +
  • Basic dynamics of the population of lynx
  • +
  • Evolution equations
  • +
  • Adapt the model to the Hudson Bay case
  • +
  • The program
  • +
  • The plot
  • +
  • Linear regression in Python
  • +
  • Linear Least squares in R
  • +
  • Non-Linear Least squares in R
  • @@ -182,7 +176,7 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    -

    Dec 1, 2017

    +

    Dec 6, 2017


    diff --git a/doc/pub/How2ReadData/html/How2ReadData-reveal.html b/doc/pub/How2ReadData/html/How2ReadData-reveal.html index 9dbe670f1..1b24cedfa 100644 --- a/doc/pub/How2ReadData/html/How2ReadData-reveal.html +++ b/doc/pub/How2ReadData/html/How2ReadData-reveal.html @@ -148,7 +148,7 @@ MathJax.Hub.Config({

    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

     
    -

    Dec 1, 2017

    +

    Dec 6, 2017


    @@ -274,8 +274,8 @@ If you don't want to perform these operations separately, we recommend two widel all relevant dependencies for Python, namely

      -

    1. anaconda
    2. -

    3. Enthought canopy
    4. +

    5. Anaconda 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
    6. +

    7. Enthought canopy is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.
    @@ -284,10 +284,18 @@ all relevant dependencies for Python, namely

    Installing R, C++, cython or Julia

    -You will also find it convenient to utilize R. Say more about R. +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 + + + +

    +

    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 @@ -300,27 +308,16 @@ including symbolic operations, Python offers a unique computational environment. can easily be converted into a nicely rendered PDF file or a Latex file for further processing.

    -This never ends, - -

    -If you se the light mark-up language doconce you can convert a standard ascii text file into various HTML +This never ends. +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.

    -

    Introduction to Jupyter notebook and available tools

    -
    +

    Introduction to Jupyter notebook and available tools

    - -
    -

    Doing it in R

    -Use the Hudson bay model to load data and make plot in R and with python -
    - - -
    -

    Representing data, overarching aims

    +

    @@ -339,7 +336,7 @@ x = np.linspace(-10,'x') plt.show() -data = {'Name': ["John", "Anna", "Peter", "Linda"], 'Location': ["Roma", "Napoli", "Torino", "Milano"], 'Age':[51, 21, 34, 45]} +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)

    @@ -349,7 +346,7 @@ display(data_pandas)
    -

    Representing data, more examples

    +

    Representing data, more examples

    @@ -378,13 +375,7 @@ plt.show()

    -

    Binning of data

    -Use the Hudson bay model to load data and make plot in R and with python -
    - - -
    -

    Adding model complexity: Predator-Prey model from ecology

    +

    Predator-Prey model from ecology

    @@ -407,14 +398,14 @@ scientific method:
    -

    Case study from Hudson bay

    +

    Case study from Hudson bay

    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? -We shall demonstrate the scientific method by +Here we start by

    1. plotting the data
    2. @@ -427,18 +418,16 @@ We shall demonstrate the scientific method by
      -

      Hudson bay data

      +

      Hudson bay data

      -% if FORMAT == 'ipynb': 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. -% endif

      @@ -475,7 +464,7 @@ One reason that this particular system has been so extensively studied is that t
      -

      Plotting the data

      +

      Plotting the data

      @@ -487,7 +476,7 @@ One reason that this particular system has been so extensively studied is that t from matplotlib import pyplot as plt # Load in data file -data = np.loadtxt('Hudson_Bay.dat', delimiter=',', skiprows=1) +data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1) # Make arrays containing x-axis and hares and lynx populations year = data[:,0] hares = data[:,1] @@ -505,27 +494,22 @@ plt.show()
      - -

      -% if FORMAT != 'ipynb':

      -

      Hares and lynx in Hudson bay from 1900 to 1920

      +

      Hares and lynx in Hudson bay from 1900 to 1920





      -% endif
      -

      Why now create a computer model for the hare and lynx populations?

      +

      Why now create a computer model for the hare and lynx populations?

      -% if FORMAT == 'ipynb': 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 @@ -540,7 +524,6 @@ 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? -% else:

      • We see oscillations in the data
      • @@ -550,15 +533,12 @@ climate and other complicating factors. How significant are these?

      • More important: we can understand the ecology dynamics of predator-pray populations
      -

      - -% endif

      -

      The traditional (top-down) approach

      +

      The traditional (top-down) approach

      @@ -593,28 +573,7 @@ ODEs (which cannot be solved)
      -

      The "new" discrete bottom-up approach

      - -

      -

      -The bottom-up approach. -
        -

      • Start with experimental data and discuss the methods which have been used to collect the data, the assumptions, the electronic devices, the aims etc. That is, expose the students to the theory and assumptions behind the data that have been collected and motivate for the scientific method.
      • -

      • Where appropriate the students should do the experiment(s) needed to collect the data.
      • -

      • The first programming tasks are to read and visualize the data to see if there are patterns or regularities. This strengthens a research-driven intuition.
      • -

      • Now we want to increase the understanding through modeling.
      • -

      • Most of the biology lies in the derivation of the model. We shall - focus on an intuitive discrete approach that leads to difference - equations that can be programmed and solved directly.
      • -
      - - -
      -
      - - -
      -

      Basic (computer-friendly) mathematics notation

      +

      Basic mathematics notation

        @@ -631,7 +590,7 @@ ODEs (which cannot be solved)
        -

        Basic dynamics of the population of hares

        +

        Basic dynamics of the population of hares

        @@ -652,8 +611,7 @@ All the hares and lynx can form 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 and must be accounted for: -subtracted in the equation for hares: +loss of hares must be accounted for. Subtracted in the equation for hares:

         
        $$ \Delta H = a\Delta t H^n - b \Delta t H^nL^n$$ @@ -663,7 +621,7 @@ $$ \Delta H = a\Delta t H^n - b \Delta t H^nL^n$$

        -

        Basic dynamics of the population of lynx

        +

        Basic dynamics of the population of lynx

        @@ -692,7 +650,7 @@ $$ \Delta L = d\Delta t H^nL^n - c\Delta t L^n$$
        -

        Evolution equations

        +

        Evolution equations

        @@ -723,7 +681,7 @@ Note:
        -

        Adapt the model to the Hudson Bay case

        +

        Adapt the model to the Hudson Bay case

        @@ -743,7 +701,7 @@ Note:
        -

        The program

        +

        The program

        @@ -763,7 +721,7 @@ Note: H = np.zeros(t.size) L = np.zeros(t.size) - print 'Init:', H0, L0, dt + print('Init:', H0, L0, dt) H[0] = H0 L[0] = L0 @@ -773,7 +731,7 @@ Note: return H, L, t # Load in data file -data = np.loadtxt('Hudson_Bay.csv', delimiter=',', skiprows=1) +data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1) # Make arrays containing x-axis and hares and lynx populations t_e = data[:,0] H_e = data[:,1] @@ -797,22 +755,112 @@ plt.show()
        - -

        -% if FORMAT != 'ipynb':

        -

        The plot

        +

        The plot





        -% else: 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. -% endif +

        + + +
        +

        Linear regression in Python

        +
        + +

        + + +

        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()
        +
        + +
        +
        + + +
        +

        Linear Least squares in 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")
        +
        + +
        +
        + + +
        +

        Non-Linear Least squares in 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)
        +
        + +
        diff --git a/doc/pub/How2ReadData/html/How2ReadData-solarized.html b/doc/pub/How2ReadData/html/How2ReadData-solarized.html index 9ed14446b..1abe49b41 100644 --- a/doc/pub/How2ReadData/html/How2ReadData-solarized.html +++ b/doc/pub/How2ReadData/html/How2ReadData-solarized.html @@ -66,45 +66,39 @@ div { text-align: justify; text-justify: inter-word; } ('Software and needed installations', 2, None, '___sec3'), ('Python installers', 2, None, '___sec4'), ('Installing R, C++, cython or Julia', 2, None, '___sec5'), + ('Installing R, C++, cython or Julia', 2, None, '___sec6'), ('Introduction to Jupyter notebook and available tools', 2, None, - '___sec6'), - ('Doing it in R', 2, None, '___sec7'), - ('Representing data, overarching aims', 2, None, '___sec8'), - ('Representing data, more examples', 2, None, '___sec9'), - ('Binning of data', 2, None, '___sec10'), - ('Adding model complexity: Predator-Prey model from ecology', - 2, - None, - '___sec11'), - ('Case study from Hudson bay', 2, None, '___sec12'), - ('Hudson bay data', 2, None, '___sec13'), - ('Plotting the data', 2, None, '___sec14'), + '___sec7'), + ('Representing data, more examples', 2, None, '___sec8'), + ('Predator-Prey model from ecology', 2, None, '___sec9'), + ('Case study from Hudson bay', 2, None, '___sec10'), + ('Hudson bay data', 2, None, '___sec11'), + ('Plotting the data', 2, None, '___sec12'), ('Hares and lynx in Hudson bay from 1900 to 1920', 2, None, - '___sec15'), + '___sec13'), ('Why now create a computer model for the hare and lynx ' 'populations?', 2, None, - '___sec16'), - ('The traditional (top-down) approach', 2, None, '___sec17'), - ("The ``new'' discrete bottom-up approach", 2, None, '___sec18'), - ('Basic (computer-friendly) mathematics notation', - 2, - None, - '___sec19'), + '___sec14'), + ('The traditional (top-down) approach', 2, None, '___sec15'), + ('Basic mathematics notation', 2, None, '___sec16'), ('Basic dynamics of the population of hares', 2, None, - '___sec20'), - ('Basic dynamics of the population of lynx', 2, None, '___sec21'), - ('Evolution equations', 2, None, '___sec22'), - ('Adapt the model to the Hudson Bay case', 2, None, '___sec23'), - ('The program', 2, None, '___sec24'), - ('The plot', 2, None, '___sec25')]} + '___sec17'), + ('Basic dynamics of the population of lynx', 2, None, '___sec18'), + ('Evolution equations', 2, None, '___sec19'), + ('Adapt the model to the Hudson Bay case', 2, None, '___sec20'), + ('The program', 2, None, '___sec21'), + ('The plot', 2, None, '___sec22'), + ('Linear regression in Python', 2, None, '___sec23'), + ('Linear Least squares in R', 2, None, '___sec24'), + ('Non-Linear Least squares in R', 2, None, '___sec25')]} end of tocinfo --> @@ -146,7 +140,7 @@ MathJax.Hub.Config({
        [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

        -

        Dec 1, 2017

        +

        Dec 6, 2017












        @@ -258,8 +252,8 @@ If you don't want to perform these operations separately, we recommend two widel all relevant dependencies for Python, namely

          -
        1. anaconda
        2. -
        3. Enthought canopy
        4. +
        5. Anaconda 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
        6. +
        7. Enthought canopy is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.










        @@ -267,10 +261,18 @@ all relevant dependencies for Python, namely

        Installing R, C++, cython or Julia

        -You will also find it convenient to utilize R. Say more about R. +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 + +

        +









        + +

        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 @@ -283,27 +285,16 @@ including symbolic operations, Python offers a unique computational environment. can easily be converted into a nicely rendered PDF file or a Latex file for further processing.

        -This never ends, - -

        -If you se the light mark-up language doconce you can convert a standard ascii text file into various HTML +This never ends. +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.











        -

        Introduction to Jupyter notebook and available tools

        +

        Introduction to Jupyter notebook and available tools

        -









        - -

        Doing it in R

        -Use the Hudson bay model to load data and make plot in R and with python - -

        -









        - -

        Representing data, overarching aims

        @@ -323,7 +314,7 @@ x = np.linspace(-10,'x') plt.show() -data = {'Name': ["John", "Anna", "Peter", "Linda"], 'Location': ["Roma", "Napoli", "Torino", "Milano"], 'Age':[51, 21, 34, 45]} +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)

        @@ -334,7 +325,7 @@ display(data_pandas)











        -

        Representing data, more examples

        +

        Representing data, more examples

        @@ -365,13 +356,7 @@ plt.show()











        -

        Binning of data

        -Use the Hudson bay model to load data and make plot in R and with python - -

        -









        - -

        Adding model complexity: Predator-Prey model from ecology

        +

        Predator-Prey model from ecology

        @@ -395,14 +380,14 @@ scientific method:











        -

        Case study from Hudson bay

        +

        Case study from Hudson bay

        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? -We shall demonstrate the scientific method by +Here we start by

        1. plotting the data
        2. @@ -416,18 +401,18 @@ We shall demonstrate the scientific method by











          -

          Hudson bay data

          +

          Hudson bay data

          -% if FORMAT == 'ipynb': + +

          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. -% endif

      @@ -465,7 +450,7 @@ One reason that this particular system has been so extensively studied is that t











      -

      Plotting the data

      +

      Plotting the data

      @@ -478,7 +463,7 @@ One reason that this particular system has been so extensively studied is that t from matplotlib import pyplot as plt # Load in data file -data = np.loadtxt('Hudson_Bay.dat', delimiter=',', skiprows=1) +data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1) # Make arrays containing x-axis and hares and lynx populations year = data[:,0] hares = data[:,1] @@ -499,23 +484,20 @@ plt.show()

      -% if FORMAT != 'ipynb':









      -

      Hares and lynx in Hudson bay from 1900 to 1920

      +

      Hares and lynx in Hudson bay from 1900 to 1920





      -% endif











      -

      Why now create a computer model for the hare and lynx populations?

      +

      Why now create a computer model for the hare and lynx populations?

      -% if FORMAT == 'ipynb': 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 @@ -530,7 +512,6 @@ 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? -% else:

      • We see oscillations in the data
      • @@ -540,15 +521,13 @@ climate and other complicating factors. How significant are these?
      • More important: we can understand the ecology dynamics of predator-pray populations
      - -% endif











      -

      The traditional (top-down) approach

      +

      The traditional (top-down) approach

      @@ -581,32 +560,7 @@ ODEs (which cannot be solved)











      -

      The "new" discrete bottom-up approach

      - -

      -

      -The bottom-up approach. -

      - - -

        -
      • Start with experimental data and discuss the methods which have been used to collect the data, the assumptions, the electronic devices, the aims etc. That is, expose the students to the theory and assumptions behind the data that have been collected and motivate for the scientific method.
      • -
      • Where appropriate the students should do the experiment(s) needed to collect the data.
      • -
      • The first programming tasks are to read and visualize the data to see if there are patterns or regularities. This strengthens a research-driven intuition.
      • -
      • Now we want to increase the understanding through modeling.
      • -
      • Most of the biology lies in the derivation of the model. We shall - focus on an intuitive discrete approach that leads to difference - equations that can be programmed and solved directly.
      • -
      - - -
      - - -

      -









      - -

      Basic (computer-friendly) mathematics notation

      +

      Basic mathematics notation

      @@ -626,7 +580,7 @@ ODEs (which cannot be solved)











      -

      Basic dynamics of the population of hares

      +

      Basic dynamics of the population of hares

      @@ -645,8 +599,7 @@ All the hares and lynx can form 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 and must be accounted for: -subtracted in the equation for hares: +loss of hares must be accounted for. Subtracted in the equation for hares: $$ \Delta H = a\Delta t H^n - b \Delta t H^nL^n$$
      @@ -655,7 +608,7 @@ $$ \Delta H = a\Delta t H^n - b \Delta t H^nL^n$$











      -

      Basic dynamics of the population of lynx

      +

      Basic dynamics of the population of lynx

      @@ -684,7 +637,7 @@ $$ \Delta L = d\Delta t H^nL^n - c\Delta t L^n$$











      -

      Evolution equations

      +

      Evolution equations

      @@ -713,7 +666,7 @@ Note:











      -

      Adapt the model to the Hudson Bay case

      +

      Adapt the model to the Hudson Bay case

      @@ -736,7 +689,7 @@ Note:











      -

      The program

      +

      The program

      @@ -757,7 +710,7 @@ Note: H = np.zeros(t.size) L = np.zeros(t.size) - print 'Init:', H0, L0, dt + print('Init:', H0, L0, dt) H[0] = H0 L[0] = L0 @@ -767,7 +720,7 @@ Note: return H, L, t # Load in data file -data = np.loadtxt('Hudson_Bay.csv', delimiter=',', skiprows=1) +data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1) # Make arrays containing x-axis and hares and lynx populations t_e = data[:,0] H_e = data[:,1] @@ -794,18 +747,116 @@ plt.show()

      -% if FORMAT != 'ipynb':









      -

      The plot

      +

      The plot





      -% else: 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. -% endif + +

      +









      + +

      Linear regression in Python

      +
      + +

      +

      + + +

      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()
      +
      + +
      + + +

      +









      + +

      Linear Least squares in 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")
      +
      + +
      + + +

      +









      + +

      Non-Linear Least squares in 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)
      +
      + +
      +

      diff --git a/doc/pub/How2ReadData/html/How2ReadData.html b/doc/pub/How2ReadData/html/How2ReadData.html index 6a1b851c5..4586bf651 100644 --- a/doc/pub/How2ReadData/html/How2ReadData.html +++ b/doc/pub/How2ReadData/html/How2ReadData.html @@ -71,45 +71,39 @@ div { text-align: justify; text-justify: inter-word; } ('Software and needed installations', 2, None, '___sec3'), ('Python installers', 2, None, '___sec4'), ('Installing R, C++, cython or Julia', 2, None, '___sec5'), + ('Installing R, C++, cython or Julia', 2, None, '___sec6'), ('Introduction to Jupyter notebook and available tools', 2, None, - '___sec6'), - ('Doing it in R', 2, None, '___sec7'), - ('Representing data, overarching aims', 2, None, '___sec8'), - ('Representing data, more examples', 2, None, '___sec9'), - ('Binning of data', 2, None, '___sec10'), - ('Adding model complexity: Predator-Prey model from ecology', - 2, - None, - '___sec11'), - ('Case study from Hudson bay', 2, None, '___sec12'), - ('Hudson bay data', 2, None, '___sec13'), - ('Plotting the data', 2, None, '___sec14'), + '___sec7'), + ('Representing data, more examples', 2, None, '___sec8'), + ('Predator-Prey model from ecology', 2, None, '___sec9'), + ('Case study from Hudson bay', 2, None, '___sec10'), + ('Hudson bay data', 2, None, '___sec11'), + ('Plotting the data', 2, None, '___sec12'), ('Hares and lynx in Hudson bay from 1900 to 1920', 2, None, - '___sec15'), + '___sec13'), ('Why now create a computer model for the hare and lynx ' 'populations?', 2, None, - '___sec16'), - ('The traditional (top-down) approach', 2, None, '___sec17'), - ("The ``new'' discrete bottom-up approach", 2, None, '___sec18'), - ('Basic (computer-friendly) mathematics notation', - 2, - None, - '___sec19'), + '___sec14'), + ('The traditional (top-down) approach', 2, None, '___sec15'), + ('Basic mathematics notation', 2, None, '___sec16'), ('Basic dynamics of the population of hares', 2, None, - '___sec20'), - ('Basic dynamics of the population of lynx', 2, None, '___sec21'), - ('Evolution equations', 2, None, '___sec22'), - ('Adapt the model to the Hudson Bay case', 2, None, '___sec23'), - ('The program', 2, None, '___sec24'), - ('The plot', 2, None, '___sec25')]} + '___sec17'), + ('Basic dynamics of the population of lynx', 2, None, '___sec18'), + ('Evolution equations', 2, None, '___sec19'), + ('Adapt the model to the Hudson Bay case', 2, None, '___sec20'), + ('The program', 2, None, '___sec21'), + ('The plot', 2, None, '___sec22'), + ('Linear regression in Python', 2, None, '___sec23'), + ('Linear Least squares in R', 2, None, '___sec24'), + ('Non-Linear Least squares in R', 2, None, '___sec25')]} end of tocinfo --> @@ -151,7 +145,7 @@ MathJax.Hub.Config({

      [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

      -

      Dec 1, 2017

      +

      Dec 6, 2017












      @@ -263,8 +257,8 @@ If you don't want to perform these operations separately, we recommend two widel all relevant dependencies for Python, namely

        -
      1. anaconda
      2. -
      3. Enthought canopy
      4. +
      5. Anaconda 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
      6. +
      7. Enthought canopy is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.










      @@ -272,10 +266,18 @@ all relevant dependencies for Python, namely

      Installing R, C++, cython or Julia

      -You will also find it convenient to utilize R. Say more about R. +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 + +

      +









      + +

      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 @@ -288,27 +290,16 @@ including symbolic operations, Python offers a unique computational environment. can easily be converted into a nicely rendered PDF file or a Latex file for further processing.

      -This never ends, - -

      -If you se the light mark-up language doconce you can convert a standard ascii text file into various HTML +This never ends. +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.











      -

      Introduction to Jupyter notebook and available tools

      +

      Introduction to Jupyter notebook and available tools

      -









      - -

      Doing it in R

      -Use the Hudson bay model to load data and make plot in R and with python - -

      -









      - -

      Representing data, overarching aims

      @@ -328,7 +319,7 @@ x = np.l y = np.sin(x) plt.plot(x,y,marker='x') plt.show() -data = {'Name': ["John", "Anna", "Peter", "Linda"], 'Location': ["Roma", "Napoli", "Torino", "Milano"], 'Age':[51, 21, 34, 45]} +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)

      @@ -339,7 +330,7 @@ display(data_pandas)











      -

      Representing data, more examples

      +

      Representing data, more examples

      @@ -370,13 +361,7 @@ plt.show()











      -

      Binning of data

      -Use the Hudson bay model to load data and make plot in R and with python - -

      -









      - -

      Adding model complexity: Predator-Prey model from ecology

      +

      Predator-Prey model from ecology

      @@ -400,14 +385,14 @@ scientific method:











      -

      Case study from Hudson bay

      +

      Case study from Hudson bay

      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? -We shall demonstrate the scientific method by +Here we start by

      1. plotting the data
      2. @@ -421,18 +406,18 @@ We shall demonstrate the scientific method by











        -

        Hudson bay data

        +

        Hudson bay data

        -% if FORMAT == 'ipynb': + +

        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. -% endif

      @@ -470,7 +455,7 @@ One reason that this particular system has been so extensively studied is that t











      -

      Plotting the data

      +

      Plotting the data

      @@ -483,7 +468,7 @@ One reason that this particular system has been so extensively studied is that t from matplotlib import pyplot as plt # Load in data file -data = np.loadtxt('Hudson_Bay.dat', delimiter=',', skiprows=1) +data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1) # Make arrays containing x-axis and hares and lynx populations year = data[:,0] hares = data[:,1] @@ -504,23 +489,20 @@ plt.show()

      -% if FORMAT != 'ipynb':









      -

      Hares and lynx in Hudson bay from 1900 to 1920

      +

      Hares and lynx in Hudson bay from 1900 to 1920





      -% endif











      -

      Why now create a computer model for the hare and lynx populations?

      +

      Why now create a computer model for the hare and lynx populations?

      -% if FORMAT == 'ipynb': 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 @@ -535,7 +517,6 @@ 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? -% else:

      • We see oscillations in the data
      • @@ -545,15 +526,13 @@ climate and other complicating factors. How significant are these?
      • More important: we can understand the ecology dynamics of predator-pray populations
      - -% endif











      -

      The traditional (top-down) approach

      +

      The traditional (top-down) approach

      @@ -586,32 +565,7 @@ ODEs (which cannot be solved)











      -

      The "new" discrete bottom-up approach

      - -

      -

      -The bottom-up approach. -

      - - -

        -
      • Start with experimental data and discuss the methods which have been used to collect the data, the assumptions, the electronic devices, the aims etc. That is, expose the students to the theory and assumptions behind the data that have been collected and motivate for the scientific method.
      • -
      • Where appropriate the students should do the experiment(s) needed to collect the data.
      • -
      • The first programming tasks are to read and visualize the data to see if there are patterns or regularities. This strengthens a research-driven intuition.
      • -
      • Now we want to increase the understanding through modeling.
      • -
      • Most of the biology lies in the derivation of the model. We shall - focus on an intuitive discrete approach that leads to difference - equations that can be programmed and solved directly.
      • -
      - - -
      - - -

      -









      - -

      Basic (computer-friendly) mathematics notation

      +

      Basic mathematics notation

      @@ -631,7 +585,7 @@ ODEs (which cannot be solved)











      -

      Basic dynamics of the population of hares

      +

      Basic dynamics of the population of hares

      @@ -650,8 +604,7 @@ All the hares and lynx can form 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 and must be accounted for: -subtracted in the equation for hares: +loss of hares must be accounted for. Subtracted in the equation for hares: $$ \Delta H = a\Delta t H^n - b \Delta t H^nL^n$$
      @@ -660,7 +613,7 @@ $$ \Delta H = a\Delta t H^n - b \Delta t H^nL^n$$











      -

      Basic dynamics of the population of lynx

      +

      Basic dynamics of the population of lynx

      @@ -689,7 +642,7 @@ $$ \Delta L = d\Delta t H^nL^n - c\Delta t L^n$$











      -

      Evolution equations

      +

      Evolution equations

      @@ -718,7 +671,7 @@ Note:











      -

      Adapt the model to the Hudson Bay case

      +

      Adapt the model to the Hudson Bay case

      @@ -741,7 +694,7 @@ Note:











      -

      The program

      +

      The program

      @@ -762,7 +715,7 @@ Note: H = np.zeros(t.size) L = np.zeros(t.size) - print 'Init:', H0, L0, dt + print('Init:', H0, L0, dt) H[0] = H0 L[0] = L0 @@ -772,7 +725,7 @@ Note: return H, L, t # Load in data file -data = np.loadtxt('Hudson_Bay.csv', delimiter=',', skiprows=1) +data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1) # Make arrays containing x-axis and hares and lynx populations t_e = data[:,0] H_e = data[:,1] @@ -799,18 +752,116 @@ plt.show()

      -% if FORMAT != 'ipynb':









      -

      The plot

      +

      The plot





      -% else: 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. -% endif + +

      +









      + +

      Linear regression in Python

      +
      + +

      +

      + + +

      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()
      +
      + +
      + + +

      +









      + +

      Linear Least squares in 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")
      +
      + +
      + + +

      +









      + +

      Non-Linear Least squares in 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)
      +
      + +
      +

      diff --git a/doc/pub/How2ReadData/html/fig/Hudson_Bay_data.pdf b/doc/pub/How2ReadData/html/fig/Hudson_Bay_data.pdf new file mode 100644 index 000000000..6a81e9928 Binary files /dev/null and b/doc/pub/How2ReadData/html/fig/Hudson_Bay_data.pdf differ diff --git a/doc/pub/How2ReadData/html/fig/Hudson_Bay_data.png b/doc/pub/How2ReadData/html/fig/Hudson_Bay_data.png new file mode 100644 index 000000000..7c6a56222 Binary files /dev/null and b/doc/pub/How2ReadData/html/fig/Hudson_Bay_data.png differ diff --git a/doc/pub/How2ReadData/html/fig/Hudson_Bay_sim.pdf b/doc/pub/How2ReadData/html/fig/Hudson_Bay_sim.pdf new file mode 100644 index 000000000..b0e391469 Binary files /dev/null and b/doc/pub/How2ReadData/html/fig/Hudson_Bay_sim.pdf differ diff --git a/doc/pub/How2ReadData/html/fig/Hudson_Bay_sim.png b/doc/pub/How2ReadData/html/fig/Hudson_Bay_sim.png new file mode 100644 index 000000000..d377d071b Binary files /dev/null and b/doc/pub/How2ReadData/html/fig/Hudson_Bay_sim.png differ diff --git a/doc/pub/How2ReadData/html/src/Hudson_Bay.csv b/doc/pub/How2ReadData/html/src/Hudson_Bay.csv new file mode 100644 index 000000000..fd9d4767f --- /dev/null +++ b/doc/pub/How2ReadData/html/src/Hudson_Bay.csv @@ -0,0 +1,22 @@ +Year,Hares (x1000),Lynx (x1000) +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 diff --git a/doc/pub/How2ReadData/html/src/Hudson_Bay.py b/doc/pub/How2ReadData/html/src/Hudson_Bay.py new file mode 100644 index 000000000..bff849971 --- /dev/null +++ b/doc/pub/How2ReadData/html/src/Hudson_Bay.py @@ -0,0 +1,43 @@ +import numpy as np +import matplotlib.pyplot as plt + +def solver(m, H0, L0, dt, a, b, c, d, t0): + """Solve the difference equations for H and L over m years + with time step dt (measured in years.""" + + num_intervals = int(m/float(dt)) + t = np.linspace(t0, t0 + m, num_intervals+1) + H = np.zeros(t.size) + L = np.zeros(t.size) + + print('Init:', H0, L0, dt) + H[0] = H0 + L[0] = L0 + + for n in range(0, len(t)-1): + H[n+1] = H[n] + a*dt*H[n] - b*dt*H[n]*L[n] + L[n+1] = L[n] + d*dt*H[n]*L[n] - c*dt*L[n] + return H, L, t + +# Load in data file +data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1) +# Make arrays containing x-axis and hares and lynx populations +t_e = data[:,0] +H_e = data[:,1] +L_e = data[:,2] + +# Simulate using the model +H, L, t = solver(m=20, H0=34.91, L0=3.857, dt=0.1, + a=0.4807, b=0.02482, c=0.9272, d=0.02756, + t0=1900) + +# Visualize simulations and data +plt.plot(t_e, H_e, 'b-+', t_e, L_e, 'r-o', t, H, 'm--', t, L, 'k--') +plt.xlabel('Year') +plt.ylabel('Numbers of hares and lynx') +plt.axis([1900, 1920, 0, 140]) +plt.title(r'Population of hares and lynx 1900-1920 (x1000)') +plt.legend(('H_e', 'L_e', 'H', 'L'), loc='upper left') +plt.savefig('Hudson_Bay_sim.pdf') +plt.savefig('Hudson_Bay_sim.png') +plt.show() diff --git a/doc/pub/How2ReadData/html/src/Hudson_Bay_sim.pdf b/doc/pub/How2ReadData/html/src/Hudson_Bay_sim.pdf new file mode 100644 index 000000000..59eabb871 Binary files /dev/null and b/doc/pub/How2ReadData/html/src/Hudson_Bay_sim.pdf differ diff --git a/doc/pub/How2ReadData/html/src/Hudson_Bay_sim.png b/doc/pub/How2ReadData/html/src/Hudson_Bay_sim.png new file mode 100644 index 000000000..41af1e52e Binary files /dev/null and b/doc/pub/How2ReadData/html/src/Hudson_Bay_sim.png differ diff --git a/doc/pub/How2ReadData/html/src/diffeq.py b/doc/pub/How2ReadData/html/src/diffeq.py new file mode 100644 index 000000000..fcfa16090 --- /dev/null +++ b/doc/pub/How2ReadData/html/src/diffeq.py @@ -0,0 +1,12 @@ +import numpy as np + +t = np.linspace(0, 10, 21) # 20 intervals in [0, 10] +dt = t[1] - t[0] +N = np.zeros(t.size) + +N[0] = 1 +r = 0.5 + +for n in range(0, N.size-1, 1): + N[n+1] = N[n] + r*dt*N[n] + print 'N[%d]=%.1f' % (n+1, N[n+1]) diff --git a/doc/pub/How2ReadData/html/src/ecoli.csv b/doc/pub/How2ReadData/html/src/ecoli.csv new file mode 100644 index 000000000..187c34b87 --- /dev/null +++ b/doc/pub/How2ReadData/html/src/ecoli.csv @@ -0,0 +1,11 @@ +0,100 +600,140 +1200,250 +1800,360 +2400,480 +3000,820 +3600,1300 +4200,1700 +4800,2900 +5400,3900 +6000,7000 diff --git a/doc/pub/How2ReadData/html/src/ecoli.py b/doc/pub/How2ReadData/html/src/ecoli.py new file mode 100644 index 000000000..ad411a3cf --- /dev/null +++ b/doc/pub/How2ReadData/html/src/ecoli.py @@ -0,0 +1,27 @@ +import numpy as np + +# Estimate r +data = np.loadtxt('ecoli.csv', delimiter=',') +t_e = data[:,0] +N_e = data[:,1] +i = 2 # Data point (i,i+1) used to estimate r +r = (N_e[i+1] - N_e[i])/(N_e[i]*(t_e[i+1] - t_e[i])) +print 'Estimated r=%.5f' % r +# Can experiment with r values and see if the model can +# match the data better + +T = 1200 # cell can divide after T sec +t_max = 5*T # 5 generations in experiment +t = np.linspace(0, t_max, 1000) +dt = t[1] - t[0] +N = np.zeros(t.size) + +N[0] = 100 +for n in range(0, len(t)-1, 1): + N[n+1] = N[n] + r*dt*N[n] + +import matplotlib.pyplot as plt +plt.plot(t, N, 'r-', t_e, N_e, 'bo') +plt.xlabel('time [s]'); plt.ylabel('N') +plt.legend(['model', 'experiment'], loc='upper left') +plt.show() diff --git a/doc/pub/How2ReadData/html/src/ecoli_inverse.py b/doc/pub/How2ReadData/html/src/ecoli_inverse.py new file mode 100644 index 000000000..43a406fc5 --- /dev/null +++ b/doc/pub/How2ReadData/html/src/ecoli_inverse.py @@ -0,0 +1,27 @@ +import numpy as np + +data = np.loadtxt('ecoli.csv', delimiter=',') +t_experiment = data[:,0] +N_experiment = data[:,1] + +def error(p): + r = p[0] + T = 1200 # cell can divide after T sec + t_max = 5*T # 5 generations in experiment + t = np.linspace(0, t_max, len(t_experiment)) + dt = (t[1] - t[0]) + N = np.zeros(t.size) + + N[0] = 100 + for n in range(0, len(t)-1, 1): + N[n+1] = N[n] + r*dt*N[n] + + e = np.sqrt(np.sum((N - N_experiment)**2))/N[0] # error measure + e = abs(N[-1] - N_experiment[-1])/N[0] + print 'r=', r, 'e=',e + return e + +from scipy.optimize import minimize + +p = minimize(error, [0.0006], tol=1E-5) +print p diff --git a/doc/pub/How2ReadData/html/src/plot_Hudson.py b/doc/pub/How2ReadData/html/src/plot_Hudson.py new file mode 100644 index 000000000..9eee0da83 --- /dev/null +++ b/doc/pub/How2ReadData/html/src/plot_Hudson.py @@ -0,0 +1,19 @@ +import numpy as np +from matplotlib import pyplot as plt + +# Load in data file +data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1) +# Make arrays containing x-axis and hares and lynx populations +year = data[:,0] +hares = data[:,1] +lynx = data[:,2] + +plt.plot(year, hares ,'b-+', year, lynx, 'r-o') +plt.axis([1900,1920,0, 100.0]) +plt.xlabel(r'Year') +plt.ylabel(r'Numbers of hares and lynx ') +plt.legend(('Hares','Lynx'), loc='upper right') +plt.title(r'Population of hares and lynx from 1900-1920 (x1000)}') +plt.savefig('Hudson_Bay_data.pdf') +plt.savefig('Hudson_Bay_data.png') +plt.show() diff --git a/doc/pub/How2ReadData/ipynb/How2ReadData.ipynb b/doc/pub/How2ReadData/ipynb/How2ReadData.ipynb index 7e6ae0e87..42ff97acd 100644 --- a/doc/pub/How2ReadData/ipynb/How2ReadData.ipynb +++ b/doc/pub/How2ReadData/ipynb/How2ReadData.ipynb @@ -10,7 +10,7 @@ " \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: **Dec 1, 2017**\n", + "Date: **Dec 6, 2017**\n", "\n", "Copyright 1999-2017, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", "\n", @@ -101,16 +101,23 @@ "## 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\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\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. Say more about R. \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++ affecianodas, 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", @@ -120,18 +127,13 @@ "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.\n", "\n", - "This never ends, \n", - "\n", - "If you se the light mark-up language **doconce** you can convert a standard ascii text file into various HTML \n", + "This never ends.\n", + "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", - "## Introduction to Jupyter notebook and available tools\n", - "\n", - "## Doing it in R\n", - "Use the Hudson bay model to load data and make plot in R and with python\n", "\n", "\n", - "## Representing data, overarching aims" + "## Introduction to Jupyter notebook and available tools" ] }, { @@ -157,7 +159,7 @@ "y = np.sin(x)\n", "plt.plot(x,y,marker='x')\n", "plt.show()\n", - "data = {'Name': [\"John\", \"Anna\", \"Peter\", \"Linda\"], 'Location': [\"Roma\", \"Napoli\", \"Torino\", \"Milano\"], 'Age':[51, 21, 34, 45]}\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)" ] @@ -199,13 +201,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Binning of data\n", - "Use the Hudson bay model to load data and make plot in R and with python\n", - "\n", - "\n", - "\n", - "\n", - "## Adding model complexity: Predator-Prey model from ecology\n", + "## 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", @@ -228,7 +224,7 @@ "## 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", - "We shall demonstrate the scientific method by\n", + "Here we start by\n", "\n", "1. plotting the data\n", "\n", @@ -243,11 +239,11 @@ "## Hudson bay data\n", "\n", "\n", - "% if FORMAT == 'ipynb':\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", - "% endif\n", + "\n", "\n", "

      \n", "\n", @@ -297,7 +293,7 @@ "from matplotlib import pyplot as plt\n", "\n", "# Load in data file\n", - "data = np.loadtxt('Hudson_Bay.dat', delimiter=',', skiprows=1)\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", @@ -318,7 +314,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "% if FORMAT != 'ipynb':\n", "## Hares and lynx in Hudson bay from 1900 to 1920\n", "\n", "\n", @@ -329,11 +324,10 @@ "\n", "\n", "\n", - "% endif\n", + "\n", "\n", "\n", "## Why now create a computer model for the hare and lynx populations?\n", - "% if FORMAT == 'ipynb':\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", @@ -348,7 +342,7 @@ "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", - "% else:\n", + "\n", " * We see oscillations in the data\n", "\n", " * What causes cycles to slow or speed up?\n", @@ -360,8 +354,6 @@ " * More important: we can understand the ecology dynamics of\n", " predator-pray populations\n", "\n", - "% endif\n", - "\n", "\n", "\n", "\n", @@ -401,25 +393,8 @@ "\n", "\n", "\n", - "## The \"new\" discrete bottom-up approach\n", "\n", - "**The bottom-up approach.**\n", - "\n", - " * Start with experimental data and discuss the methods which have been used to collect the data, the assumptions, the electronic devices, the aims etc. That is, expose the students to the theory and assumptions behind the data that have been collected and motivate for the scientific method.\n", - "\n", - " * Where appropriate the students should do the experiment(s) needed to collect the data.\n", - "\n", - " * The first programming tasks are to read and visualize the data to see if there are patterns or regularities. This strengthens a research-driven intuition.\n", - "\n", - " * Now we want to increase the understanding through modeling.\n", - "\n", - " * Most of the biology lies in the *derivation* of the model. We shall\n", - " focus on an intuitive discrete approach that leads to difference\n", - " equations that can be programmed *and solved* directly.\n", - "\n", - "\n", - "\n", - "## Basic (computer-friendly) mathematics notation\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", @@ -459,8 +434,7 @@ "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 and must be accounted for:\n", - "subtracted in the equation for hares:" + "loss of hares must be accounted for. Subtracted in the equation for hares:" ] }, { @@ -584,7 +558,7 @@ " H = np.zeros(t.size)\n", " L = np.zeros(t.size)\n", "\n", - " print 'Init:', H0, L0, dt\n", + " print('Init:', H0, L0, dt)\n", " H[0] = H0\n", " L[0] = L0\n", "\n", @@ -594,7 +568,7 @@ " return H, L, t\n", "\n", "# Load in data file\n", - "data = np.loadtxt('Hudson_Bay.csv', delimiter=',', skiprows=1)\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", @@ -621,7 +595,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "% if FORMAT != 'ipynb':\n", "## The plot\n", "\n", "\n", @@ -633,9 +606,110 @@ "\n", "\n", "\n", - "% else:\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", - "% endif" + "\n", + "\n", + "## Linear regression in Python" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "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": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [], + "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\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Non-Linear Least squares in R" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [], + "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)" ] } ], diff --git a/doc/pub/How2ReadData/ipynb/fig/Hudson_Bay_data.pdf b/doc/pub/How2ReadData/ipynb/fig/Hudson_Bay_data.pdf new file mode 100644 index 000000000..6a81e9928 Binary files /dev/null and b/doc/pub/How2ReadData/ipynb/fig/Hudson_Bay_data.pdf differ diff --git a/doc/pub/How2ReadData/ipynb/fig/Hudson_Bay_data.png b/doc/pub/How2ReadData/ipynb/fig/Hudson_Bay_data.png new file mode 100644 index 000000000..7c6a56222 Binary files /dev/null and b/doc/pub/How2ReadData/ipynb/fig/Hudson_Bay_data.png differ diff --git a/doc/pub/How2ReadData/ipynb/fig/Hudson_Bay_sim.pdf b/doc/pub/How2ReadData/ipynb/fig/Hudson_Bay_sim.pdf new file mode 100644 index 000000000..b0e391469 Binary files /dev/null and b/doc/pub/How2ReadData/ipynb/fig/Hudson_Bay_sim.pdf differ diff --git a/doc/pub/How2ReadData/ipynb/fig/Hudson_Bay_sim.png b/doc/pub/How2ReadData/ipynb/fig/Hudson_Bay_sim.png new file mode 100644 index 000000000..d377d071b Binary files /dev/null and b/doc/pub/How2ReadData/ipynb/fig/Hudson_Bay_sim.png differ diff --git a/doc/pub/How2ReadData/ipynb/ipynb-How2ReadData-src.tar.gz b/doc/pub/How2ReadData/ipynb/ipynb-How2ReadData-src.tar.gz index 0fa3383aa..e4b77e928 100644 Binary files a/doc/pub/How2ReadData/ipynb/ipynb-How2ReadData-src.tar.gz and b/doc/pub/How2ReadData/ipynb/ipynb-How2ReadData-src.tar.gz differ diff --git a/doc/pub/How2ReadData/ipynb/src/Hudson_Bay.csv b/doc/pub/How2ReadData/ipynb/src/Hudson_Bay.csv new file mode 100644 index 000000000..fd9d4767f --- /dev/null +++ b/doc/pub/How2ReadData/ipynb/src/Hudson_Bay.csv @@ -0,0 +1,22 @@ +Year,Hares (x1000),Lynx (x1000) +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 diff --git a/doc/pub/How2ReadData/ipynb/src/Hudson_Bay.py b/doc/pub/How2ReadData/ipynb/src/Hudson_Bay.py new file mode 100644 index 000000000..bff849971 --- /dev/null +++ b/doc/pub/How2ReadData/ipynb/src/Hudson_Bay.py @@ -0,0 +1,43 @@ +import numpy as np +import matplotlib.pyplot as plt + +def solver(m, H0, L0, dt, a, b, c, d, t0): + """Solve the difference equations for H and L over m years + with time step dt (measured in years.""" + + num_intervals = int(m/float(dt)) + t = np.linspace(t0, t0 + m, num_intervals+1) + H = np.zeros(t.size) + L = np.zeros(t.size) + + print('Init:', H0, L0, dt) + H[0] = H0 + L[0] = L0 + + for n in range(0, len(t)-1): + H[n+1] = H[n] + a*dt*H[n] - b*dt*H[n]*L[n] + L[n+1] = L[n] + d*dt*H[n]*L[n] - c*dt*L[n] + return H, L, t + +# Load in data file +data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1) +# Make arrays containing x-axis and hares and lynx populations +t_e = data[:,0] +H_e = data[:,1] +L_e = data[:,2] + +# Simulate using the model +H, L, t = solver(m=20, H0=34.91, L0=3.857, dt=0.1, + a=0.4807, b=0.02482, c=0.9272, d=0.02756, + t0=1900) + +# Visualize simulations and data +plt.plot(t_e, H_e, 'b-+', t_e, L_e, 'r-o', t, H, 'm--', t, L, 'k--') +plt.xlabel('Year') +plt.ylabel('Numbers of hares and lynx') +plt.axis([1900, 1920, 0, 140]) +plt.title(r'Population of hares and lynx 1900-1920 (x1000)') +plt.legend(('H_e', 'L_e', 'H', 'L'), loc='upper left') +plt.savefig('Hudson_Bay_sim.pdf') +plt.savefig('Hudson_Bay_sim.png') +plt.show() diff --git a/doc/pub/How2ReadData/ipynb/src/Hudson_Bay_sim.pdf b/doc/pub/How2ReadData/ipynb/src/Hudson_Bay_sim.pdf new file mode 100644 index 000000000..59eabb871 Binary files /dev/null and b/doc/pub/How2ReadData/ipynb/src/Hudson_Bay_sim.pdf differ diff --git a/doc/pub/How2ReadData/ipynb/src/Hudson_Bay_sim.png b/doc/pub/How2ReadData/ipynb/src/Hudson_Bay_sim.png new file mode 100644 index 000000000..41af1e52e Binary files /dev/null and b/doc/pub/How2ReadData/ipynb/src/Hudson_Bay_sim.png differ diff --git a/doc/pub/How2ReadData/ipynb/src/diffeq.py b/doc/pub/How2ReadData/ipynb/src/diffeq.py new file mode 100644 index 000000000..fcfa16090 --- /dev/null +++ b/doc/pub/How2ReadData/ipynb/src/diffeq.py @@ -0,0 +1,12 @@ +import numpy as np + +t = np.linspace(0, 10, 21) # 20 intervals in [0, 10] +dt = t[1] - t[0] +N = np.zeros(t.size) + +N[0] = 1 +r = 0.5 + +for n in range(0, N.size-1, 1): + N[n+1] = N[n] + r*dt*N[n] + print 'N[%d]=%.1f' % (n+1, N[n+1]) diff --git a/doc/pub/How2ReadData/ipynb/src/ecoli.csv b/doc/pub/How2ReadData/ipynb/src/ecoli.csv new file mode 100644 index 000000000..187c34b87 --- /dev/null +++ b/doc/pub/How2ReadData/ipynb/src/ecoli.csv @@ -0,0 +1,11 @@ +0,100 +600,140 +1200,250 +1800,360 +2400,480 +3000,820 +3600,1300 +4200,1700 +4800,2900 +5400,3900 +6000,7000 diff --git a/doc/pub/How2ReadData/ipynb/src/ecoli.py b/doc/pub/How2ReadData/ipynb/src/ecoli.py new file mode 100644 index 000000000..ad411a3cf --- /dev/null +++ b/doc/pub/How2ReadData/ipynb/src/ecoli.py @@ -0,0 +1,27 @@ +import numpy as np + +# Estimate r +data = np.loadtxt('ecoli.csv', delimiter=',') +t_e = data[:,0] +N_e = data[:,1] +i = 2 # Data point (i,i+1) used to estimate r +r = (N_e[i+1] - N_e[i])/(N_e[i]*(t_e[i+1] - t_e[i])) +print 'Estimated r=%.5f' % r +# Can experiment with r values and see if the model can +# match the data better + +T = 1200 # cell can divide after T sec +t_max = 5*T # 5 generations in experiment +t = np.linspace(0, t_max, 1000) +dt = t[1] - t[0] +N = np.zeros(t.size) + +N[0] = 100 +for n in range(0, len(t)-1, 1): + N[n+1] = N[n] + r*dt*N[n] + +import matplotlib.pyplot as plt +plt.plot(t, N, 'r-', t_e, N_e, 'bo') +plt.xlabel('time [s]'); plt.ylabel('N') +plt.legend(['model', 'experiment'], loc='upper left') +plt.show() diff --git a/doc/pub/How2ReadData/ipynb/src/ecoli_inverse.py b/doc/pub/How2ReadData/ipynb/src/ecoli_inverse.py new file mode 100644 index 000000000..43a406fc5 --- /dev/null +++ b/doc/pub/How2ReadData/ipynb/src/ecoli_inverse.py @@ -0,0 +1,27 @@ +import numpy as np + +data = np.loadtxt('ecoli.csv', delimiter=',') +t_experiment = data[:,0] +N_experiment = data[:,1] + +def error(p): + r = p[0] + T = 1200 # cell can divide after T sec + t_max = 5*T # 5 generations in experiment + t = np.linspace(0, t_max, len(t_experiment)) + dt = (t[1] - t[0]) + N = np.zeros(t.size) + + N[0] = 100 + for n in range(0, len(t)-1, 1): + N[n+1] = N[n] + r*dt*N[n] + + e = np.sqrt(np.sum((N - N_experiment)**2))/N[0] # error measure + e = abs(N[-1] - N_experiment[-1])/N[0] + print 'r=', r, 'e=',e + return e + +from scipy.optimize import minimize + +p = minimize(error, [0.0006], tol=1E-5) +print p diff --git a/doc/pub/How2ReadData/ipynb/src/plot_Hudson.py b/doc/pub/How2ReadData/ipynb/src/plot_Hudson.py new file mode 100644 index 000000000..9eee0da83 --- /dev/null +++ b/doc/pub/How2ReadData/ipynb/src/plot_Hudson.py @@ -0,0 +1,19 @@ +import numpy as np +from matplotlib import pyplot as plt + +# Load in data file +data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1) +# Make arrays containing x-axis and hares and lynx populations +year = data[:,0] +hares = data[:,1] +lynx = data[:,2] + +plt.plot(year, hares ,'b-+', year, lynx, 'r-o') +plt.axis([1900,1920,0, 100.0]) +plt.xlabel(r'Year') +plt.ylabel(r'Numbers of hares and lynx ') +plt.legend(('Hares','Lynx'), loc='upper right') +plt.title(r'Population of hares and lynx from 1900-1920 (x1000)}') +plt.savefig('Hudson_Bay_data.pdf') +plt.savefig('Hudson_Bay_data.png') +plt.show() diff --git a/doc/pub/How2ReadData/pdf/How2ReadData-beamer-handouts2x3.pdf b/doc/pub/How2ReadData/pdf/How2ReadData-beamer-handouts2x3.pdf index 87483f064..083f7c59c 100644 Binary files a/doc/pub/How2ReadData/pdf/How2ReadData-beamer-handouts2x3.pdf and b/doc/pub/How2ReadData/pdf/How2ReadData-beamer-handouts2x3.pdf differ diff --git a/doc/pub/How2ReadData/pdf/How2ReadData-beamer.pdf b/doc/pub/How2ReadData/pdf/How2ReadData-beamer.pdf index e09e901d6..2f0b619bd 100644 Binary files a/doc/pub/How2ReadData/pdf/How2ReadData-beamer.pdf and b/doc/pub/How2ReadData/pdf/How2ReadData-beamer.pdf differ diff --git a/doc/pub/How2ReadData/pdf/How2ReadData-minted.pdf b/doc/pub/How2ReadData/pdf/How2ReadData-minted.pdf index 9648da49b..f3b68e5f6 100644 Binary files a/doc/pub/How2ReadData/pdf/How2ReadData-minted.pdf and b/doc/pub/How2ReadData/pdf/How2ReadData-minted.pdf differ diff --git a/doc/src/How2ReadData/.ipynb_checkpoints/How2ReadData-checkpoint.ipynb b/doc/src/How2ReadData/.ipynb_checkpoints/How2ReadData-checkpoint.ipynb new file mode 100644 index 000000000..1c8b1116b --- /dev/null +++ b/doc/src/How2ReadData/.ipynb_checkpoints/How2ReadData-checkpoint.ipynb @@ -0,0 +1,728 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "# Data Analysis and Machine Learning: Introduction and Representing data\n", + "\n", + " \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: **Dec 6, 2017**\n", + "\n", + "Copyright 1999-2017, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", + "\n", + "\n", + "\n", + "\n", + "## What is Machine Learning?\n", + "\n", + "Machine learning is the science of giving computers the ability to\n", + "learn without being explicitly programmed. The idea is that there\n", + "exist generic algorithms which can be used to find patterns in a broad\n", + "class of data sets without having to write code specifically for each\n", + "problem. The algorithm will build its own logic based on the data.\n", + "\n", + "Machine learning is a subfield of computer science, and is closely\n", + "related to computational statistics. It evolved from the study of\n", + "pattern recognition in artificial intelligence (AI) research, and has\n", + "made contributions to AI tasks like computer vision, natural language\n", + "processing and speech recognition. It has also, especially in later\n", + "years, found applications in a wide variety of other areas, including\n", + "bioinformatics, economy, physics, finance and marketing.\n", + "\n", + "## Types of Machine Learning\n", + "\n", + "\n", + "The approaches to machine learning are many, but are often split into two main categories. \n", + "In *supervised learning* we know the answer to a problem,\n", + "and let the computer deduce the logic behind it. On the other hand, *unsupervised learning*\n", + "is a method for finding patterns and relationship in data sets without any prior knowledge of the system.\n", + "Some authours also operate with a third category, namely *reinforcement learning*. This is a paradigm \n", + "of learning inspired by behavioural psychology, where learning is achieved by trial-and-error, \n", + "solely from rewards and punishment.\n", + "\n", + "Another way to categorize machine learning tasks is to consider the desired output of a system.\n", + "Some of the most common tasks are:\n", + "\n", + " * 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.\n", + "\n", + " * 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.\n", + "\n", + " * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.\n", + "\n", + "## Different algorithms\n", + "In this course we will build our machine learning approach on a statistical foundation, with elements \n", + "from data analysis, stochastic processes etc before we proceed with the following machine learning algorithms\n", + "\n", + "1. Linear regression and its variants\n", + "\n", + "2. Decision tree algorithms, from simpler to more complex ones\n", + "\n", + "3. Nearest neighbors models\n", + "\n", + "4. Bayesian statistics \n", + "\n", + "5. Support vector machines and finally various variants of\n", + "\n", + "6. Artifical neural networks\n", + "\n", + "Before we proceed however, there are several practicalities with data analysis and software tools we would \n", + "like to present. These tools will help us in our understanding of various machine learning algorithms. \n", + "\n", + "Our emphasis here is on understanding the mathematical aspects of different algorithms, however, where possible \n", + "we will emphasize the importance of using available software. \n", + "\n", + "\n", + "## Software and needed installations\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++ affecianodas, 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.\n", + "\n", + "This never ends.\n", + "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", + "## Useful packages\n", + "\n", + "If you already have a Python installation set up, you can use **pip** or **pip3** to install \n", + "1. pip3 install numpy scipy ipython \n", + "\n", + "2. pip3 install pandas matplotlib scikit-learn pillow \n", + "\n", + "Another useful package is **mglearn**. \n", + "\n", + "## Introduction to Jupyter notebook and available tools" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "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": 2, + "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 Rgression\")\n", + "plt.show()" + ] + }, + { + "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", + "% if FORMAT == 'ipynb':\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", + "% endif\n", + "\n", + "
      \n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "
      Year Hares (x1000) Lynx (x1000)
      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
      \n", + "\n", + "\n", + "\n", + "\n", + "\n", + "## Plotting the data" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "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('Hudson_Bay.dat', 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": [ + "% if FORMAT != 'ipynb':\n", + "## Hares and lynx in Hudson bay from 1900 to 1920\n", + "\n", + "\n", + "\n", + "\n", + "

      \n", + "\n", + "\n", + "\n", + "\n", + "% endif\n", + "\n", + "\n", + "## Why now create a computer model for the hare and lynx populations?\n", + "% if FORMAT == 'ipynb':\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", + "% else:\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", + "% endif\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", + "## The \"new\" discrete bottom-up approach\n", + "\n", + "**The bottom-up approach.**\n", + "\n", + " * Start with experimental data and discuss the methods which have been used to collect the data, the assumptions, the electronic devices, the aims etc. That is, expose the students to the theory and assumptions behind the data that have been collected and motivate for the scientific method.\n", + "\n", + " * Where appropriate the students should do the experiment(s) needed to collect the data.\n", + "\n", + " * The first programming tasks are to read and visualize the data to see if there are patterns or regularities. This strengthens a research-driven intuition.\n", + "\n", + " * Now we want to increase the understanding through modeling.\n", + "\n", + " * Most of the biology lies in the *derivation* of the model. We shall\n", + " focus on an intuitive discrete approach that leads to difference\n", + " equations that can be programmed *and solved* directly.\n", + "\n", + "\n", + "\n", + "## Basic (computer-friendly) 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 and must be accounted for:\n", + "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": 4, + "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('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": [ + "% if FORMAT != 'ipynb':\n", + "## The plot\n", + "\n", + "\n", + "\n", + "\n", + "

      \n", + "\n", + "\n", + "\n", + "\n", + "\n", + "% else:\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", + "% endif\n", + "\n", + "\n", + "\n", + "## 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": [ + "## 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" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/doc/src/How2ReadData/.ipynb_checkpoints/Untitled-checkpoint.ipynb b/doc/src/How2ReadData/.ipynb_checkpoints/Untitled-checkpoint.ipynb new file mode 100644 index 000000000..2fd64429b --- /dev/null +++ b/doc/src/How2ReadData/.ipynb_checkpoints/Untitled-checkpoint.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/doc/src/How2ReadData/.ipynb_checkpoints/Untitled1-checkpoint.ipynb b/doc/src/How2ReadData/.ipynb_checkpoints/Untitled1-checkpoint.ipynb new file mode 100644 index 000000000..2fd64429b --- /dev/null +++ b/doc/src/How2ReadData/.ipynb_checkpoints/Untitled1-checkpoint.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/doc/src/How2ReadData/How2ReadData.do.txt b/doc/src/How2ReadData/How2ReadData.do.txt index e78fd19e6..cfcb08ad9 100644 --- a/doc/src/How2ReadData/How2ReadData.do.txt +++ b/doc/src/How2ReadData/How2ReadData.do.txt @@ -86,17 +86,25 @@ etc etc. ===== 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 -o Enthought canopy +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. Say more about R. +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. @@ -106,21 +114,15 @@ setup allows you to integrate widely popular softwares and tools for scientific 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. -This never ends, - -If you se the light mark-up language _doconce_ you can convert a standard ascii text file into various HTML +This never ends. +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 ===== -!split -===== Doing it in R ===== -Use the Hudson bay model to load data and make plot in R and with python - - -!split -===== Representing data, overarching aims ===== !bblock !bc pycod import numpy as np @@ -136,14 +138,12 @@ 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': ["Roma", "Napoli", "Torino", "Milano"], 'Age':[51, 21, 34, 45]} +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 @@ -167,16 +167,8 @@ plt.show() !ec !eblock - !split -===== Binning of data ===== -Use the Hudson bay model to load data and make plot in R and with python -Use LSQ first, then neural networks with R and scikt-learn - - - -!split -===== Adding model complexity: Predator-Prey model from ecology ===== +===== Predator-Prey model from ecology ===== !bblock The population dynamics of a simple predator-prey system is a @@ -197,7 +189,7 @@ scientific method: !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? -We shall demonstrate the scientific method by +Here we start by o plotting the data o derive a simple model for the population dynamics @@ -210,11 +202,11 @@ We shall demonstrate the scientific method by !bblock -% if FORMAT == 'ipynb': + 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. -% endif + |------------------------------------------------------| | Year | Hares (x1000) | Lynx (x1000)| @@ -253,18 +245,16 @@ One reason that this particular system has been so extensively studied is that t @@@CODE src/plot_Hudson.py !eblock -% if FORMAT != 'ipynb': !split ===== Hares and lynx in Hudson bay from 1900 to 1920 ===== FIGURE: [fig/Hudson_Bay_data, width=700 frac=0.9] -% endif + !split ===== Why now create a computer model for the hare and lynx populations? ===== !bblock -% if FORMAT == 'ipynb': 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 @@ -279,14 +269,13 @@ 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? -% else: + * 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 -% endif !eblock @@ -315,23 +304,9 @@ ODEs* (which cannot be solved) !eblock -!split -===== The ``new'' discrete bottom-up approach ===== - -!bblock The bottom-up approach -!bpop - * Start with experimental data and discuss the methods which have been used to collect the data, the assumptions, the electronic devices, the aims etc. That is, expose the students to the theory and assumptions behind the data that have been collected and motivate for the scientific method. - * Where appropriate the students should do the experiment(s) needed to collect the data. - * The first programming tasks are to read and visualize the data to see if there are patterns or regularities. This strengthens a research-driven intuition. - * Now we want to increase the understanding through modeling. - * Most of the biology lies in the *derivation* of the model. We shall - focus on an intuitive discrete approach that leads to difference - equations that can be programmed *and solved* directly. -!epop -!eblock !split -===== Basic (computer-friendly) mathematics notation ===== +===== Basic mathematics notation ===== !bblock * Time points: $t_0,t_1,\ldots,t_m$ * Uniform distribution of time points: $t_n=n\Delta t$ @@ -360,8 +335,7 @@ $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 and must be accounted for: -subtracted in the equation for hares: +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\] @@ -433,15 +407,97 @@ Note: @@@CODE src/Hudson_Bay.py !eblock -% if FORMAT != 'ipynb': !split ===== The plot ===== FIGURE: [fig/Hudson_Bay_sim, width=700 frac=0.9] -% else: 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. -% endif + + +!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 pycod +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 pycod +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 + + + + + diff --git a/doc/src/How2ReadData/src/Hudson_Bay.py b/doc/src/How2ReadData/src/Hudson_Bay.py index acd44518e..bff849971 100644 --- a/doc/src/How2ReadData/src/Hudson_Bay.py +++ b/doc/src/How2ReadData/src/Hudson_Bay.py @@ -10,7 +10,7 @@ def solver(m, H0, L0, dt, a, b, c, d, t0): H = np.zeros(t.size) L = np.zeros(t.size) - print 'Init:', H0, L0, dt + print('Init:', H0, L0, dt) H[0] = H0 L[0] = L0 @@ -20,7 +20,7 @@ def solver(m, H0, L0, dt, a, b, c, d, t0): return H, L, t # Load in data file -data = np.loadtxt('Hudson_Bay.csv', delimiter=',', skiprows=1) +data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1) # Make arrays containing x-axis and hares and lynx populations t_e = data[:,0] H_e = data[:,1] diff --git a/doc/src/How2ReadData/src/plot_Hudson.py b/doc/src/How2ReadData/src/plot_Hudson.py index 2d05fd162..9eee0da83 100644 --- a/doc/src/How2ReadData/src/plot_Hudson.py +++ b/doc/src/How2ReadData/src/plot_Hudson.py @@ -2,7 +2,7 @@ import numpy as np from matplotlib import pyplot as plt # Load in data file -data = np.loadtxt('Hudson_Bay.dat', delimiter=',', skiprows=1) +data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1) # Make arrays containing x-axis and hares and lynx populations year = data[:,0] hares = data[:,1] diff --git a/doc/src/How2ReadData/test.py b/doc/src/How2ReadData/test.py new file mode 100644 index 000000000..be8ccd053 --- /dev/null +++ b/doc/src/How2ReadData/test.py @@ -0,0 +1,21 @@ +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 +from sklearn.model_selection import train_test_split +X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0) + +data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1) +x = data[:,0] +y = data[:,1] +x_train, y_train = train_test_split(x, y, random_state=0) +line = np.linspace(1900,1930,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() +