Docsity

Python NumPy and Matplotlib: Array Manipulation and Plotting, Lecture notes of Advanced Computer Programming

Partial preview of the text

Download Python NumPy and Matplotlib: Array Manipulation and Plotting and more Lecture notes Advanced Computer Programming in PDF only on Docsity!

Introduction to Scientific Computing in Python

Robert Johansson

April 16, 2016

Contents

Chapter 1

Introduction to scientific computing

with Python

J.R. Johansson (jrjohansson at gmail.com) The latest version of this IPython notebook lecture is available at http://github.com/jrjohansson/ scientific-python-lectures. The other notebooks in this lecture series are indexed at http://jrjohansson.github.io.

1.1 The role of computing in science

Science has traditionally been divided into experimental and theoretical disciplines, but during the last several decades computing has emerged as a very important part of science. Scientific computing is often closely related to theory, but it also has many characteristics in common with experimental work. It is therefore often viewed as a new third branch of science. In most fields of science, computational work is an important complement to both experiments and theory, and nowadays a vast majority of both experimental and theoretical papers involve some numerical calculations, simulations or computer modeling. In experimental and theoretical sciences there are well established codes of conducts for how results and methods are published and made available to other scientists. For example, in theoretical sciences, derivations, proofs and other results are published in full detail, or made available upon request. Likewise, in experimental sciences, the methods used and the results are published, and all experimental data should be available upon request. It is considered unscientific to withhold crucial details in a theoretical proof or experimental method, that would hinder other scientists from replicating and reproducing the results. In computational sciences there are not yet any well established guidelines for how source code and generated data should be handled. For example, it is relatively rare that source code used in simulations for published papers are provided to readers, in contrast to the open nature of experimental and theoretical work. And it is not uncommon that source code for simulation software is withheld and considered a competitive advantage (or unnecessary to publish). However, this issue has recently started to attract increasing attention, and a number of editorials in high-profile journals have called for increased openness in computational sciences. Some prestigious journals, including Science, have even started to demand of authors to provide the source code for simulation software used in publications to readers upon request. Discussions are also ongoing on how to facilitate distribution of scientific software, for example as sup- plementary materials to scientific papers.

1.1.1 References

  • Reproducible Research in Computational Science, Roger D. Peng, Science 334, 1226 (2011).
  • Shining Light into Black Boxes, A. Morin et al., Science 336, 159-160 (2012).
  • The case for open computer programs, D.C. Ince, Nature 482, 485 (2012).

1.2 Requirements on scientific computing

Replication and reproducibility are two of the cornerstones in the scientific method. With respect to numerical work, complying with these concepts have the following practical implications:

  • Replication: An author of a scientific paper that involves numerical calculations should be able to rerun the simulations and replicate the results upon request. Other scientist should also be able to perform the same calculations and obtain the same results, given the information about the methods used in a publication.
  • Reproducibility: The results obtained from numerical simulations should be reproducible with an independent implementation of the method, or using a different method altogether.

In summary: A sound scientific result should be reproducible, and a sound scientific study should be replicable. To achieve these goals, we need to:

  • Keep and take note of exactly which source code and version that was used to produce data and figures in published papers.
  • Record information of which version of external software that was used. Keep access to the environment that was used.
  • Make sure that old codes and notes are backed up and kept for future reference.
  • Be ready to give additional information about the methods used, and perhaps also the simulation codes, to an interested reader who requests it (even years after the paper was published!).
  • Ideally codes should be published online, to make it easier for other scientists interested in the codes to access it.

1.2.1 Tools for managing source code

Ensuring replicability and reprodicibility of scientific simulations is a complicated problem, but there are good tools to help with this:

  • Revision Control System (RCS) software.
    • Good choices include: ∗ git - http://git-scm.com ∗ mercurial - http://mercurial.selenic.com. Also known as hg. ∗ subversion - http://subversion.apache.org. Also known as svn.
  • Online repositories for source code. Available as both private and public repositories.
    • Some good alternatives are ∗ Github - http://www.github.com ∗ Bitbucket - http://www.bitbucket.com ∗ Privately hosted repositories on the university’s or department’s servers.

Note

Repositories are also excellent for version controlling manuscripts, figures, thesis files, data files, lab logs, etc. Basically for any digital content that must be preserved and is frequently updated. Again, both public and private repositories are readily available. They are also excellent collaboration tools!

1.4.1 The scientific python software stack

1.4.2 Python environments

Python is not only a programming language, but often also refers to the standard implementation of the interpreter (technically referred to as CPython) that actually runs the python code on a computer. There are also many different environments through which the python interpreter can be used. Each environment has different advantages and is suitable for different workflows. One strength of python is that it is versatile and can be used in complementary ways, but it can be confusing for beginners so we will start with a brief survey of python environments that are useful for scientific computing.

1.4.3 Python interpreter

The standard way to use the Python programming language is to use the Python interpreter to run python code. The python interpreter is a program that reads and execute the python code in files passed to it as arguments. At the command prompt, the command python is used to invoke the Python interpreter. For example, to run a file my-program.py that contains python code from the command prompt, use::

$ python my-program.py

We can also start the interpreter by simply typing python at the command line, and interactively type python code into the interpreter. This is often how we want to work when developing scientific applications, or when doing small calcula- tions. But the standard python interpreter is not very convenient for this kind of work, due to a number of limitations.

1.4.4 IPython

IPython is an interactive shell that addresses the limitation of the standard python interpreter, and it is a work-horse for scientific use of python. It provides an interactive prompt to the python interpreter with a greatly improved user-friendliness. Some of the many useful features of IPython includes:

  • Command history, which can be browsed with the up and down arrows on the keyboard.
  • Tab auto-completion.
  • In-line editing of code.
  • Object introspection, and automatic extract of documentation strings from python objects like classes and functions.
  • Good interaction with operating system shell.
  • Support for multiple parallel back-end processes, that can run on computing clusters or cloud services like Amazon EE2.

1.4.5 IPython notebook

IPython notebook is an HTML-based notebook environment for Python, similar to Mathematica or Maple. It is based on the IPython shell, but provides a cell-based environment with great interactivity, where calculations can be organized and documented in a structured way. Although using a web browser as graphical interface, IPython notebooks are usually run locally, from the same computer that run the browser. To start a new IPython notebook session, run the following command:

$ ipython notebook

from a directory where you want the notebooks to be stored. This will open a new browser window (or a new tab in an existing window) with an index page where existing notebooks are shown and from which new notebooks can be created.

1.4.6 Spyder

Spyder is a MATLAB-like IDE for scientific computing with python. It has the many advantages of a traditional IDE environment, for example that everything from code editing, execution and debugging is carried out in a single environment, and work on different calculations can be organized as projects in the IDE environment. Some advantages of Spyder:

  • Powerful code editor, with syntax high-lighting, dynamic code introspection and integration with the python debugger.
  • Variable explorer, IPython command prompt.
  • Integrated documentation and help.

1.5 Versions of Python

There are currently two versions of python: Python 2 and Python 3. Python 3 will eventually supercede Python 2, but it is not backward-compatible with Python 2. A lot of existing python code and packages has been written for Python 2, and it is still the most wide-spread version. For these lectures either version will be fine, but it is probably easier to stick with Python 2 for now, because it is more readily available via prebuilt packages and binary installers. To see which version of Python you have, run

$ python --version Python 2.7. $ python3.2 --version Python 3.2.

Several versions of Python can be installed in parallel, as shown above.

1.6 Installation

1.6.1 Conda

The best way set-up an scientific Python environment is to use the cross-platform package manager conda from Continuum Analytics. First download and install miniconda http://conda.pydata.org/miniconda.html or Anaconda (see below). Next, to install the required libraries for these notebooks, simply run:

$ conda install ipython ipython-notebook spyder numpy scipy sympy matplotlib cython

This should be sufficient to get a working environment on any platform supported by conda.

1.6.2 Linux

In Ubuntu Linux, to installing python and all the requirements run:

$ sudo apt-get install python ipython ipython-notebook

$ sudo apt-get install python-numpy python-scipy python-matplotlib python-sympy $ sudo apt-get install spyder

In [1]: # you only need to do this once !pip install --upgrade version_information

Collecting version-information Installing collected packages: version-information Successfully installed version-information-1.0.

or alternatively run (deprecated method): you only need to do this once Now, to load the extension and produce the version table

In [2]: %load_ext version_information

%version_information numpy, scipy, matplotlib, sympy, version_information

Out[2]:

Chapter 2

Introduction to Python programming

J.R. Johansson (jrjohansson at gmail.com) The latest version of this IPython notebook lecture is available at http://github.com/jrjohansson/ scientific-python-lectures. The other notebooks in this lecture series are indexed at http://jrjohansson.github.io.

2.1 Python program files

  • Python code is usually stored in text files with the file ending “.py”:

myprogram.py

  • Every line in a Python program file is assumed to be a Python statement, or part thereof.
    • The only exception is comment lines, which start with the character # (optionally preceded by an arbitrary number of white-space characters, i.e., tabs or spaces). Comment lines are usually ignored by the Python interpreter.
  • To run our Python program from the command line we use:

$ python myprogram.py

  • On UNIX systems it is common to define the path to the interpreter on the first line of the program (note that this is a comment line as far as the Python interpreter is concerned):

#!/usr/bin/env python

If we do, and if we additionally set the file script to be executable, we can run the program like this:

$ myprogram.py

2.1.1 Example:

In [1]: ls scripts/hello-world*.py

scripts/hello-world-in-swedish.py scripts/hello-world.py

In [2]: cat scripts/hello-world.py

To use a module in a Python program it first has to be imported. A module can be imported using the import statement. For example, to import the module math, which contains many standard mathematical functions, we can do:

In [6]: import math

This includes the whole module and makes it available for use later in the program. For example, we can do:

In [7]: import math

x = math.cos(2 * math.pi)

print(x)

Alternatively, we can chose to import all symbols (functions and variables) in a module to the current namespace (so that we don’t need to use the prefix “math.” every time we use something from the math module:

In [8]: from math import *

x = cos(2 * pi)

print(x)

This pattern can be very convenient, but in large programs that include many modules it is often a good idea to keep the symbols from each module in their own namespaces, by using the import math pattern. This would elminate potentially confusing problems with name space collisions. As a third alternative, we can chose to import only a few selected symbols from a module by explicitly listing which ones we want to import instead of using the wildcard character *:

In [9]: from math import cos, pi

x = cos(2 * pi)

print(x)

2.3.2 Looking at what a module contains, and its documentation

Once a module is imported, we can list the symbols it provides using the dir function:

In [10]: import math

print(dir(math))

[' doc ', ' file ', ' name ', ' package ', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh

And using the function help we can get a description of each function (almost .. not all functions have docstrings, as they are technically called, but the vast majority of functions are documented this way).

In [11]: help(math.log)

Help on built-in function log in module math:

log(...) log(x[, base])

Return the logarithm of x to the given base. If the base not specified, returns the natural logarithm (base e) of x.

In [12]: log(10)

Out[12]: 2.

In [13]: log(10, 2)

Out[13]: 3.

We can also use the help function directly on modules: Try

help(math)

Some very useful modules form the Python standard library are os, sys, math, shutil, re, subprocess, multiprocessing, threading. A complete lists of standard modules for Python 2 and Python 3 are available at http://docs.python.org/2/library/ and http://docs.python.org/3/library/, respectively.

2.4 Variables and types

2.4.1 Symbol names

Variable names in Python can contain alphanumerical characters a-z, A-Z, 0-9 and some special characters such as. Normal variable names must start with a letter. By convention, variable names start with a lower-case letter, and Class names start with a capital letter. In addition, there are a number of Python keywords that cannot be used as variable names. These keywords are:

and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, yield

Note: Be aware of the keyword lambda, which could easily be a natural variable name in a scientific program. But being a keyword, it cannot be used as a variable name.

2.4.2 Assignment

The assignment operator in Python is =. Python is a dynamically typed language, so we do not need to specify the type of a variable when we create one. Assigning a value to a new variable creates the variable:

In [14]: # variable assignments x = 1. my_variable = 12.

In [23]: print(x)

(1-1j)

In [24]: print(x.real, x.imag)

(1.0, -1.0)

2.4.4 Type utility functions

The module types contains a number of type name definitions that can be used to test if variables are of certain types:

In [25]: import types

print all types defined in the types module

print(dir(types))

['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'Comp

In [26]: x = 1.

check if the variable x is a float

type(x) is float

Out[26]: True

In [27]: # check if the variable x is an int type(x) is int

Out[27]: False

We can also use the isinstance method for testing types of variables:

In [28]: isinstance(x, float)

Out[28]: True

2.4.5 Type casting

In [29]: x = 1.

print(x, type(x))

(1.5, )

In [30]: x = int(x)

print(x, type(x))

(1, )

In [31]: z = complex(x)

print(z, type(z))

((1+0j), )

In [32]: x = float(z)

TypeError Traceback (most recent call last)

in () ----> 1 x = float(z)

TypeError: can't convert complex to float

Complex variables cannot be cast to floats or integers. We need to use z.real or z.imag to extract the part of the complex number we want:

In [33]: y = bool(z.real)

print(z.real, " -> ", y, type(y))

y = bool(z.imag)

print(z.imag, " -> ", y, type(y))

(1.0, ' -> ', True, ) (0.0, ' -> ', False, )

2.5 Operators and comparisons

Most operators and comparisons in Python work as one would expect:

  • Arithmetic operators +, - , , /, // (integer division), ’*’ power

In [34]: 1 + 2, 1 - 2, 1 * 2, 1 / 2

Out[34]: (3, -1, 2, 0)

In [35]: 1.0 + 2.0, 1.0 - 2.0, 1.0 * 2.0, 1.0 / 2.

Out[35]: (3.0, -1.0, 2.0, 0.5)

In [36]: # Integer division of float numbers 3.0 // 2.

Out[36]: 1.

In [37]: # Note! The power operators in python isn't ^, but ** 2 ** 2