




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































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.
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.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:
In summary: A sound scientific result should be reproducible, and a sound scientific study should be replicable. To achieve these goals, we need to:
Ensuring replicability and reprodicibility of scientific simulations is a complicated problem, but there are good tools to help with this:
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!
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.
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.
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:
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.
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:
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
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.
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]:
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.
myprogram.py
$ python myprogram.py
#!/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
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)
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
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.
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)
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(dir(types))
['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'Comp
In [26]: x = 1.
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
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:
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