Escolar Documentos
Profissional Documentos
Cultura Documentos
SciKits
Numpy
SciPy
Matplotlib
2015
Python
EDITION
IP[y]:
Cython
IPython
Scipy
Lecture Notes
www.scipy-lectures.org
Edited by
Gal Varoquaux
Emmanuelle Gouillart
Olaf Vahtras
4
4
5
6
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
10
10
11
18
22
27
34
35
39
42
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
43
43
55
68
72
77
4 Matplotlib: plotting
4.1 Introduction . . . . . . . . . . . . . . . . . . .
4.2 Simple plot . . . . . . . . . . . . . . . . . . . .
4.3 Figures, Subplots, Axes and Ticks . . . . . . .
4.4 Other Types of Plots: examples and exercises
4.5 Beyond this tutorial . . . . . . . . . . . . . . .
4.6 Quick references . . . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
82
82
83
89
90
96
98
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
101
102
103
103
104
109
113
115
116
118
120
137
II Advanced topics
140
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
159
160
173
182
185
188
188
9 Debugging code
9.1 Avoiding bugs . . . . . . . . . . . . . . . . .
9.2 Debugging workflow . . . . . . . . . . . . .
9.3 Using the Python debugger . . . . . . . . .
9.4 Debugging segmentation faults using gdb
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
192
192
195
195
200
10 Optimizing code
10.1 Optimization workflow . . . .
10.2 Profiling Python code . . . . .
10.3 Making code go faster . . . . .
10.4 Writing faster numerical code
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
203
203
203
206
207
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
210
210
212
224
229
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
230
231
232
233
235
240
243
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
248
249
251
258
260
261
14 Interfacing with C
14.1 Introduction . . . . . . . . . . .
14.2 Python-C-Api . . . . . . . . . . .
14.3 Ctypes . . . . . . . . . . . . . . .
14.4 SWIG . . . . . . . . . . . . . . . .
14.5 Cython . . . . . . . . . . . . . . .
14.6 Summary . . . . . . . . . . . . .
14.7 Further Reading and References
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
263
263
264
268
272
276
279
280
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
ii
282
15 Statistics in Python
15.1 Data representation and interaction . . . . . . . . . . . .
15.2 Hypothesis testing: comparing two groups . . . . . . . .
15.3 Linear models, multiple factors, and analysis of variance
15.4 More visualization: seaborn for statistical exploration . .
15.5 Testing for interactions . . . . . . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
284
285
289
292
297
299
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
301
302
303
304
305
306
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
308
308
310
312
315
318
318
320
.
.
.
.
.
.
.
.
.
.
322
. 323
. 323
. 324
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
340
340
346
347
349
350
351
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
353
354
355
357
359
360
361
362
Index
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
363
iii
Part I
Contents
This part of the Scipy lecture notes is a self-contained introduction to everything that is needed to use Python
for science, from the language itself, to numerical computing or plotting.
1.1.2 Specifications
Rich collection of already existing bricks corresponding to classical numerical methods or basic actions:
we dont want to re-program the plotting of a curve, a Fourier transform or a fitting algorithm. Dont
reinvent the wheel!
Easy to learn: computer science is neither our job nor our education. We want to be able to draw a curve,
smooth a signal, do a Fourier transform in a few minutes.
Easy communication with collaborators, students, customers, to make the code live within a lab or a
company: the code should be as readable as a book. Thus, the language should contain as few syntax symbols or unneeded routines as possible that would divert the reader from the mathematical or
scientific understanding of the code.
Efficient code that executes quickly... but needless to say that a very fast code becomes useless if we
spend too much time writing it. So, we need both a quick development time and a quick execution time.
A single environment/language for everything, if possible, to avoid learning a new software for each new
problem.
Some very optimized scientific libraries have been written for these languages. Example: BLAS
(vector/matrix operations)
Python language: data types (string, int), flow control, data collections (lists, dictionaries), patterns, etc.
Modules of the standard library.
Drawbacks:
Painful usage: no interactivity during development, mandatory compilation steps, verbose syntax
(&, ::, }}, ; etc.), manual memory management (tricky in C). These are difficult languages for non
computer scientists.
A large number of specialized modules or applications written in Python: web protocols, web
framework, etc. ... and scientific computing.
Development tools (automatic testing, documentation generation)
Drawbacks:
Numpy : provides powerful numerical arrays objects, and routines to manipulate them.
http://www.numpy.org/
Base language is quite poor and can become restrictive for advanced users.
Not free.
Other scripting languages: Scilab, Octave, Igor, R, IDL, etc.
Advantages:
Open-source, free, or at least cheaper than Matlab.
Some features can be very advanced (statistics in R, figures in Igor, etc.)
Drawbacks:
Fewer available algorithms than in Matlab, and the language is not more advanced.
Some software are dedicated to one domain. Ex: Gnuplot or xmgrace to draw curves. These programs are very powerful, but they are restricted to a single type of usage, such as plotting.
Unlike Matlab, Scilab or R, Python does not come with a pre-bundled set of modules for scientific computing.
Below are the basic building blocks that can be combined to obtain a scientific computing environment:
Python, a generic and modern computing language
Python is a general-purpose language. As such, there is not one blessed environment to work in, and not only
one way of using it. Although this makes it harder for beginners to find their way, it makes it possible for Python
to be used to write programs, in web servers, or embedded devices.
Reference document for this section:
IPython user manual: http://ipython.org/ipython-doc/dev/index.html
The IPython user manual contains a wealth of information about using IPython, but to get you started we want
to give you a quick introduction to four useful features: history, magic functions, aliases and tab completion.
Start ipython:
In [1]: print('Hello world')
Hello world
Like a UNIX shell, IPython supports command history. Type up and down to navigate previously typed commands:
In [1]: x = 10
In [2]: print?
Type:
builtin_function_or_method
Base Class:
<type 'builtin_function_or_method'>
String Form:
<built-in function print>
Namespace:
Python builtin
Docstring:
print(value, ..., sep=' ', end='\n', file=sys.stdout)
In [2]: <UP>
In [2]: x = 10
IPython supports so called magic functions by prefixing a command with the % character. For example, the run
and whos functions from the previous section are magic functions. Note that, the setting automagic, which is
enabled by default, allows you to omit the preceding % sign. Thus, you can just type the magic function and it
will work.
%timeit allows you to time the execution of short snippets using the timeit module from the standard
library:
In [3]: timeit x = 10
10000000 loops, best of 3: 39 ns per loop
%cpaste allows you to paste code, especially code from websites which has been prefixed with the standard Python prompt (e.g. >>>) or with an ipython prompt, (e.g. in [3]):
In [5]: cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:In [3]: timeit x = 10
:-10000000 loops, best of 3: 85.9 ns per loop
In [6]: cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:>>> timeit x = 10
:-10000000 loops, best of 3: 86 ns per loop
Now, you can run it in IPython and explore the resulting variables:
In [1]: %run my_file.py
Hello world
In [2]: s
Out[2]: 'Hello world'
In [3]: %whos
Variable
Type
Data/Info
---------------------------s
str
Hello world
%debug allows you to enter post-mortem debugging. That is to say, if the code you try to execute, raises
an exception, using %debug will enter the debugger at the point where the exception was thrown.
In [7]: x === 10
File "<ipython-input-6-12fd421b5f28>", line 1
x === 10
^
SyntaxError: invalid syntax
In [8]: debug
> /.../IPython/core/compilerop.py (87)ast_parse()
86
and are passed to the built-in compile function."""
---> 87
return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)
88
ipdb>locals()
{'source': u'x === 10\n', 'symbol': 'exec', 'self':
<IPython.core.compilerop.CachingCompiler instance at 0x2ad8ef0>,
'filename': '<ipython-input-6-12fd421b5f28>'}
IPython help
The built-in IPython cheat-sheet is accessible via the %quickref magic function.
A list of all available magic functions is shown when typing %magic.
Furthermore IPython ships with various aliases which emulate common UNIX command line tools such as ls
to list files, cp to copy files and rm to remove files. A list of aliases is shown when typing alias:
In [1]: alias
Total number of aliases: 16
Out[1]:
[('cat', 'cat'),
('clear', 'clear'),
('cp', 'cp -i'),
('ldir', 'ls -F -o --color %l
('less', 'less'),
('lf', 'ls -F -o --color %l |
('lk', 'ls -F -o --color %l |
('ll', 'ls -F -o --color'),
('ls', 'ls -F --color'),
('lx', 'ls -F -o --color %l |
('man', 'man'),
('mkdir', 'mkdir'),
('more', 'more'),
('mv', 'mv -i'),
('rm', 'rm -i'),
('rmdir', 'rmdir')]
grep ^-'),
grep ^l'),
grep ^-..x'),
Tab completion, especially for attributes, is a convenient way to explore the structure of any object youre dealing
with. Simply type object_name.<TAB> to view the objects attributes. Besides Python objects and keywords, tab
completion also works on file and directory names.
In [1]: x = 10
In [3]: x.real.
x.real.bit_length
x.real.conjugate
We introduce here the Python language. Only the bare minimum necessary for getting started with
Numpy and Scipy is addressed here. To learn more about the language, consider going through
the excellent tutorial https://docs.python.org/tutorial. Dedicated books are also available, such as
http://www.diveintopython.net/.
| grep /$'),
Lastly, we would like to mention the tab completion feature, whose description we cite directly from the
IPython manual:
In [2]: x.<TAB>
x.bit_length
x.conjugate
x.real
x.denominator
x.real.denominator
x.real.imag
x.imag
Python is a programming language, as are C, Fortran, BASIC, PHP, etc. Some specific features of Python are as
follows:
an interpreted (as opposed to compiled) language. Contrary to e.g. C or Fortran, one does not compile
Python code before executing it. In addition, Python can be used interactively: many Python interpreters are available, from which commands and scripts can be executed.
a free software released under an open-source license: Python can be used and distributed free of
charge, even for building commercial software.
multi-platform: Python is available for all major operating systems, Windows, Linux/Unix, MacOS X,
most likely your mobile phone OS, etc.
a very readable language with clear non-verbose syntax
a language for which a large variety of high-quality packages are available for various applications, from
web frameworks to scientific computing.
a language very easy to interface with other languages, in particular C and C++.
Some other features of the language are illustrated just below. For example, Python is an object-oriented
language, with dynamic typing (the same variable can contain objects of different types during the
course of a program).
See https://www.python.org/about/ for more information about distinguishing features of Python.
x.numerator
x.real.numerator
x.real.real
In [4]: x.real.
10
or by starting the program from a menu, e.g. in the Python(x,y) or EPD menu if you have installed one
of these scientific-Python suites.
If you dont have Ipython installed on your computer, other Python shells are available, such as the plain
Python shell started by typing python in a terminal, or the Idle interpreter. However, we advise to use the
Ipython shell because of its enhanced features, especially for interactive scientific computing.
Once you have started the interpreter, type
>>> print("Hello, world!")
Hello, world!
Complex
>>> a = 1.5 + 0.5j
>>> a.real
1.5
>>> a.imag
0.5
>>> type(1. + 0j)
<type 'complex'>
Booleans
The message Hello, world! is then displayed. You just executed your first Python instruction, congratulations!
To get yourself started, type the following stack of instructions
>>> a = 3
>>> b = 2*a
>>> type(b)
<type 'int'>
>>> print(b)
6
>>> a*b
18
>>> b = 'hello'
>>> type(b)
<type 'str'>
>>> b + b
'hellohello'
>>> 2*b
'hellohello'
>>> 3 > 4
False
>>> test = (3 > 4)
>>> test
False
>>> type(test)
<type 'bool'>
A Python shell can therefore replace your pocket calculator, with the basic arithmetic operations +, -, *, /, %
(modulo) natively implemented
>>> 7 * 3.
21.0
>>> 2**10
1024
>>> 8 % 3
2
Two variables a and b have been defined above. Note that one does not declare the type of an variable before
assigning its value. In C, conversely, one should write:
>>> float(1)
1.0
int a = 3;
In addition, the type of a variable may change, in the sense that at one point in time it can be equal to a
value of a certain type, and a second point in time, it can be equal to a value of a different type. b was first
equal to an integer, but it became equal to a string when it was assigned the value hello. Operations on
integers (b=2*a) are coded natively in Python, and so are some operations on strings such as additions and
multiplications, which amount respectively to concatenation and repetition.
Floats
>>> c = 2.1
>>> type(c)
<type 'float'>
11
12
>>> l
['red', 'blue', 'green', 'black', 'white']
>>> l[2:4]
['green', 'black']
B Integer division
In Python 2:
>>> 3 / 2
1
B Note that l[start:stop] contains the elements with indices i such as start<=
In Python 3:
>>> 3 / 2
1.5
>>> 3 / 2.
1.5
>>> l
['red', 'blue', 'green', 'black', 'white']
>>> l[3:]
['black', 'white']
>>> l[:3]
['red', 'blue', 'green']
>>> l[::2]
['red', 'green', 'white']
a = 3
b = 2
a / b # In Python 2
a / float(b)
>>> l[0] =
>>> l
['yellow',
>>> l[2:4]
>>> l
['yellow',
'yellow'
'blue', 'green', 'black', 'white']
= ['gray', 'purple']
'blue', 'gray', 'purple', 'white']
2.2.2 Containers
Python provides many efficient types of containers, in which collections of objects can be stored.
For collections of numerical data that all have the same type, it is often more efficient to use the array type
provided by the numpy module. A NumPy array is a chunk of memory containing fixed-sized items. With
NumPy arrays, operations on elements can be faster because elements are regularly spaced in memory and
more operations are performed through specialized C functions instead of Python loops.
Lists
A list is an ordered collection of objects, that may have different types. For example:
Python offers a large panel of functions to modify lists, or query them. Here are a few examples; for more
details, see https://docs.python.org/tutorial/datastructures.html#more-on-lists
>>>
>>>
>>>
1
>>>
1.5
Reverse:
13
14
>>> r = L[::-1]
>>> r
['white', 'black', 'green', 'blue', 'red']
>>> r2 = list(L)
>>> r2
['red', 'blue', 'green', 'black', 'white']
>>> r2.reverse() # in-place
>>> r2
['white', 'black', 'green', 'blue', 'red']
>>> r + L
['white', 'black', 'green', 'blue', 'red', 'red', 'blue', 'green', 'black', 'white']
>>> r * 2
['white', 'black', 'green', 'blue', 'red', 'white', 'black', 'green', 'blue', 'red']
Sort:
Indexing:
>>>
>>>
'h'
>>>
'e'
>>>
'o'
The notation r.method() (e.g. r.append(3) and L.pop()) is our first example of object-oriented programming (OOP). Being a list, the object r owns the method function that is called using the notation
.. No further knowledge of OOP than understanding the notation . is necessary for going through this
tutorial.
a[1]
a[-1]
Slicing:
>>> a = "hello, world!"
>>> a[3:6] # 3rd to 6th (excluded) elements: elements 3, 4, 5
'lo,'
>>> a[2:10:2] # Syntax: a[start:stop:step]
'lo o'
>>> a[::3] # every three characters, from beginning to end
'hl r!'
Discovering methods:
Reminder: in Ipython: tab-completion (press tab)
r.__iadd__
r.__imul__
r.__init__
r.__iter__
r.__le__
r.__len__
r.__lt__
r.__mul__
r.__ne__
r.__new__
r.__reduce__
r.__reduce_ex__
r.__repr__
r.__reversed__
r.__rmul__
a = "hello"
a[0]
(Remember that negative indices correspond to counting from the right end.)
Accents
and
special
characters
can
also
be
handled
https://docs.python.org/tutorial/introduction.html#unicode-strings).
r.__setattr__
r.__setitem__
r.__setslice__
r.__sizeof__
r.__str__
r.__subclasshook__
r.append
r.count
r.extend
r.index
r.insert
r.pop
r.remove
r.reverse
r.sort
in
Unicode
strings
(see
A string is an immutable object and it is not possible to modify its contents. One may however create new
strings from the original one.
In [53]: a = "hello, world!"
In [54]: a[2] = 'z'
--------------------------------------------------------------------------Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
In [55]:
Out[55]:
In [56]:
Out[56]:
a.replace('l', 'z', 1)
'hezlo, world!'
a.replace('l', 'z')
'hezzo, worzd!'
Strings have many useful methods, such as a.replace as seen above. Remember the a. object-oriented
notation and use tab completion or help(str) to search for new methods.
Strings
See also:
Python offers advanced possibilities for manipulating strings, looking for patterns or formatting.
The interested reader is referred to https://docs.python.org/library/stdtypes.html#string-methods and
https://docs.python.org/library/string.html#new-string-formatting
In [28]: r.<TAB>
r.__add__
r.__class__
r.__contains__
r.__delattr__
r.__delitem__
r.__delslice__
r.__doc__
r.__eq__
r.__format__
r.__ge__
r.__getattribute__
r.__getitem__
r.__getslice__
r.__gt__
r.__hash__
15
16
String formatting:
>>> 'An integer: %i ; a float: %f ; another string: %s ' % (1, 0.1, 'string')
'An integer: 1; a float: 0.100000; another string: string'
>>> i = 102
>>> filename = 'processing_of_dataset_%d .txt' % i
>>> filename
'processing_of_dataset_102.txt'
Things to note:
Dictionaries
A dictionary is basically an efficient table that maps keys to values. It is an unordered container
>>> tel = {'emmanuelle': 5752, 'sebastian': 5578}
>>> tel['francis'] = 5915
>>> tel
{'sebastian': 5578, 'francis': 5915, 'emmanuelle': 5752}
>>> tel['sebastian']
5578
>>> tel.keys()
['sebastian', 'francis', 'emmanuelle']
>>> tel.values()
[5578, 5915, 5752]
>>> 'francis' in tel
True
a = [1, 2, 3]
b = a
a
[1, 2, 3]
b
[1, 2, 3]
a is b
True
b[1] = 'hi!'
a
[1, 'hi!', 3]
It can be used to conveniently store and retrieve values associated with a name (a string for a date, a name,
etc.). See https://docs.python.org/tutorial/datastructures.html#dictionaries for more information.
A dictionary can have keys (resp. values) with different types:
>>> d = {'a':1, 'b':2, 3:'hello'}
>>> d
{'a': 1, 3: 'hello', 'b': 2}
a = [1, 2, 3]
a
[1, 2, 3]
a = ['a', 'b', 'c'] # Creates another object.
a
['a', 'b', 'c']
id(a)
138641676
a[:] = [1, 2, 3] # Modifies object in place.
a
[1, 2, 3]
id(a)
138641676 # Same as in Out[6], yours will differ...
2.3.1 if/elif/else
>>> if 2**2 == 4:
...
print('Obvious!')
17
18
>>> a =
>>> for
...
...
...
1.0
0.5
0.25
[1, 0, 2, 4]
element in a:
if element == 0:
continue
print(1. / element)
Indentation is compulsory in scripts as well. As an exercise, re-type the previous lines with the same indentation in a script condition.py, and execute the script with run condition.py in Ipython.
2.3.2 for/range
Evaluates to True:
everything else
>>> 1 == 1.
True
>>> a = 1
>>> b = 1
>>> a is b
True
2.3.3 while/break/continue
Typical C-style while loop (Mandelbrot problem):
>>> z = 1 + 1j
>>> while abs(z) < 100:
...
z = z**2 + 1
>>> z
(-134+352j)
You can iterate over any sequence (string, list, keys in a dictionary, lines in a file, ...):
>>> z = 1 + 1j
19
20
e
u
Exercise
Few languages (in particular, languages for scientific computing) allow to loop over anything but integers/indices. With Python it is possible to loop exactly over the objects of interest without bothering with
indices you often dont care about. This feature can often be used to make code more readable.
In [57]: test()
in test function
Common task is to iterate over a sequence while keeping track of the item number.
Could use while loop with a counter as above. Or a for loop:
>>>
>>>
...
(0,
(1,
(2,
4i 2
2 1
4i
i =1
In [8]: disk_area(1.5)
Out[8]: 7.0649999999999995
2.4.3 Parameters
Mandatory parameters (positional arguments)
In [81]: def double_it(x):
....:
return x * 2
....:
The ordering of a dictionary in random, thus we use sorted() which will sort on the keys.
In [82]: double_it(3)
Out[82]: 6
In [83]: double_it()
---------------------------------------------------------------------------
21
22
In [101]: rhyme = 'one fish, two fish, red fish, blue fish'.split()
In [102]: rhyme
Out[102]: ['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish']
In [85]: double_it()
Out[85]: 4
In [103]: slicer(rhyme)
Out[103]: ['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish']
In [86]: double_it(3)
Out[86]: 6
using mutable types (e.g. dictionary or list) and modifying them in the function body, since the modifications
will be persistent across invocations of the function.
Using an immutable type in a keyword argument:
In [124]: bigx = 10
but it is good practice to use the same ordering as the functions definition.
Keyword arguments are a very convenient feature for defining functions with a variable number of arguments,
especially when default values are to be used in most calls to the function.
In [128]: double_it()
Out[128]: 20
Using an mutable type in a keyword argument (and modifying it inside the function body):
In [2]: def add_to_dict(args={'a': 1, 'b': 2}):
...:
for i in args.keys():
...:
args[i] += 1
...:
print args
...:
Can you modify the value of a variable inside a function? Most languages (C, Java, ...) distinguish passing by
value and passing by reference. In Python, such a distinction is somewhat artificial, and it is a bit subtle
whether your variables are going to be modified or not. Fortunately, there exist clear rules.
Parameters to functions are references to objects, which are passed by value. When you pass a variable to a
function, python passes the reference to the object to which the variable refers (the value). Not the variable
itself.
In [3]: add_to_dict
Out[3]: <function __main__.add_to_dict>
If the value passed in a function is immutable, the function does not modify the callers variable. If the value
is mutable, the function may modify the callers variable in-place:
In [4]: add_to_dict()
{'a': 2, 'b': 3}
In [5]: add_to_dict()
{'a': 3, 'b': 4}
In [6]: add_to_dict()
{'a': 4, 'b': 5}
23
24
>>> print(b)
[99, 42]
>>> print(c)
[28]
2.4.7 Docstrings
Variables declared outside the function can be referenced within the function:
Documentation about what the function does and its parameters. General convention:
In [114]: x = 5
But these global variables cannot be modified within the function, unless declared global in the function.
This doesnt work:
In [117]: def setx(y):
.....:
x = y
.....:
print('x is %d ' % x)
.....:
.....:
In [118]: setx(10)
x is 10
In [68]: funcname?
Type:
function
Base Class:
type 'function'>
String Form:
<function funcname at 0xeaa0f0>
Namespace:
Interactive
File:
<ipython console>
Definition:
funcname(params)
Docstring:
Concise one-line sentence describing the function.
Extended summary which can contain multiple paragraphs.
In [120]: x
Out[120]: 5
Docstring guidelines
For the sake of standardization, the Docstring Conventions webpage documents the semantics and conventions associated with Python docstrings.
Also, the Numpy and Scipy modules have defined a precise standard for documenting scientific functions, that you may want to follow for your own functions, with a Parameters section, an Examples
section, etc.
See http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines#docstring-standard and
http://projects.scipy.org/numpy/browser/trunk/doc/example.py#L37
This works:
In [121]: def setx(y):
.....:
global x
.....:
x = y
.....:
print('x is %d ' % x)
.....:
.....:
In [122]: setx(10)
x is 10
In [123]: x
Out[123]: 10
In [38]: va = variable_args
25
26
2.4.9 Methods
you?
Methods are functions attached to objects. Youve seen these in our examples on lists, dictionaries, strings,
etc...
In [2]: message
Out[2]: 'Hello how are you?'
2.4.10 Exercises
The script has been executed. Moreover the variables defined in the script (such as message) are now available
inside the interpreters namespace.
Other interpreters also offer the possibility to execute scripts (e.g., execfile in the plain Python interpreter,
etc.).
It is also possible In order to execute this script as a standalone program, by executing the script inside a shell
terminal (Linux/Mac console or cmd Windows console). For example, if we are in the same directory as the
test.py file, we can execute this in a console:
Write a function that displays the n first terms of the Fibonacci sequence, defined by:
u_0 = 1; u_1 = 1
u_(n+2) = u_(n+1) + u_n
$ python test.py
Hello
how
are
you?
Exercise: Quicksort
Implement the quicksort algorithm, as defined by wikipedia
function quicksort(array)
var list less, greater
if length(array) < 2
return array
select and remove a pivot value pivot from array
for each x in array
if x < pivot + 1 then append x to less
else append x to greater
return concatenate(quicksort(less), pivot, quicksort(greater))
import sys
print sys.argv
$ python file.py test arguments
['file.py', 'test', 'arguments']
B Dont implement option parsing yourself. Use modules such as optparse, argparse or docopt.
2.5.1 Scripts
Let us first write a script, that is a file with a sequence of instructions that are executed each time the script is
called. Instructions may be e.g. copied-and-pasted from the interpreter (but take care to respect indentation
rules!).
The extension for Python files is .py. Write or copy-and-paste the following lines in a file called test.py
message = "Hello how are you?"
for word in message.split():
print word
In [1]: import os
In [2]: os
Out[2]: <module 'os' from '/usr/lib/python2.6/os.pyc'>
In [3]: os.listdir('.')
Out[3]:
['conf.py',
'basic_types.rst',
'control_flow.rst',
'functions.rst',
'python_language.rst',
'reusing.rst',
'file_io.rst',
'exceptions.rst',
'workflow.rst',
'index.rst']
And also:
Let us now execute the script interactively, that is inside the Ipython interpreter. This is maybe the most common use of scripts in scientific computing.
Importing shorthands:
In [5]: import numpy as np
27
28
Importing the module gives access to its objects, using the module.object syntax. Dont forget to put the
modules name before the objects name, otherwise Python wont recognize the instruction.
from os import *
This is called the star import and please, Use it with caution
Makes the code harder to read and understand: where do symbols come from?
Makes it impossible to guess the functionality by the context and the name (hint: os.name is the name
of the OS), and to profit usefully from tab completion.
Restricts the variable names you can use: os.name might override name, or vise-versa.
Creates possible name clashes between modules.
Makes the code impossible to statically check for undefined symbols.
Modules are thus a good way to organize code in a hierarchical way. Actually, all the scientific computing tools
we are going to use are modules:
>>> import numpy as np # data arrays
>>> np.linspace(0, 10, 6)
array([ 0.,
2.,
4.,
6.,
8., 10.])
>>> import scipy # scientific computing
Introspection
In [4]: demo?
Type:
module
Base Class: <type 'module'>
String Form:
<module 'demo' from 'demo.py'>
Namespace: Interactive
File:
/home/varoquau/Projects/Python_talks/scipy_2009_tutorial/source/demo.py
Docstring:
A demo module.
In [5]: who
demo
In [6]: whos
Variable
Type
Data/Info
-----------------------------demo
module
<module 'demo' from 'demo.py'>
import numpy
import numpy as np
from pylab import *
import scipy
In [7]: dir(demo)
Out[7]:
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'c',
'd',
'print_a',
'print_b']
In [8]: demo.
demo.__builtins__
demo.__class__
demo.__delattr__
demo.__dict__
demo.__doc__
demo.__file__
demo.__format__
demo.__getattribute__
demo.__hash__
demo.__init__
demo.__name__
demo.__new__
demo.__package__
demo.__reduce__
demo.__reduce_ex__
demo.__repr__
demo.__setattr__
demo.__sizeof__
demo.__str__
demo.__subclasshook__
demo.c
demo.d
demo.print_a
demo.print_b
demo.py
demo.pyc
c = 2
d = 2
In this file, we defined two functions print_a and print_b. Suppose we want to call the print_a function
from the interpreter. We could execute the file as a script, but since we just want to have access to the function
print_a, we are rather going to import it as a module. The syntax is as follows.
In [1]: import demo
In [2]: demo.print_a()
a
In [10]: whos
Variable
Type
Data/Info
-------------------------------demo
module
<module 'demo' from 'demo.py'>
print_a
function
<function print_a at 0xb7421534>
print_b
function
<function print_b at 0xb74214c4>
In [11]: print_a()
a
In [3]: demo.print_b()
b
29
30
B Module caching
Modules are cached: if you modify demo.py and re-import it in the old session, you will get the old
one.
Solution:
In [10]: reload(demo)
In Python3 instead reload is not builtin, so you have to import the importlib module first and then do:
In [10]: importlib.reload(demo)
File demo2.py:
your
own
modules
within
directories
$HOME/.local/lib/python2.7/dist-packages).
def print_b():
"Prints b."
print 'b'
def print_a():
"Prints a."
print 'a'
On Linux/Unix, add the following line to a file read by the shell at startup (e.g. /etc/profile, .profile)
export PYTHONPATH=$PYTHONPATH:/home/emma/user_defined_modules
if __name__ == '__main__':
# print_a() is only executed when the module is run directly.
print_a()
import sys
new_path = '/home/emma/user_defined_modules'
if new_path not in sys.path:
sys.path.append(new_path)
Importing it:
This method is not very robust, however, because it makes the code less portable (user-dependent path) and
because you have to add the directory to your sys.path each time you want to import from a module in this
directory.
See also:
Running it:
2.5.6 Packages
A directory that contains many modules is called a package. A package is a module with submodules (which
can have submodules themselves, etc.). A special file called __init__.py (which may be empty) tells Python
that the directory is a Python package, from which modules can be imported.
31
$ ls
cluster/
__config__.py@
__config__.pyc
constants/
fftpack/
__init__.py@
__init__.pyc
INSTALL.txt@
integrate/
interpolate/
$ cd ndimage
$ ls
io/
LATEST.txt@
lib/
linalg/
linsolve/
maxentropy/
misc/
ndimage/
odr/
optimize/
README.txt@
setup.py@
setup.pyc
setupscons.py@
setupscons.pyc
signal/
sparse/
spatial/
special/
stats/
stsci/
__svn_version__.py@
__svn_version__.pyc
THANKS.txt@
TOCHANGE.txt@
version.py@
version.pyc
weave/
32
doccer.py@
fourier.pyc
doccer.pyc
info.py@
setupscons.py@
filters.py@ info.pyc
setupscons.pyc
filters.pyc __init__.py@
fourier.py@ __init__.pyc
interpolation.py@
interpolation.pyc
morphology.pyc
_nd_image.so
measurements.py@
_ni_support.py@
measurements.pyc
morphology.py@
_ni_support.pyc
setup.py@
setup.pyc
Indentation depth: Inside your text editor, you may choose to indent with any positive number of spaces
(1, 2, 3, 4, ...). However, it is considered good practice to indent with 4 spaces. You may configure your
editor to map the Tab key to a 4-space indentation. In Python(x,y), the editor is already configured this
way.
tests/
Style guidelines
Long lines: you should not write very long lines that span over more than (e.g.) 80 characters. Long lines
can be broken with the \ character
From Ipython:
In [1]: import scipy
In [2]: scipy.__file__
Out[2]: '/usr/lib/python2.6/dist-packages/scipy/__init__.pyc'
Spaces
Write well-spaced code: put whitespaces after commas, around arithmetic operators, etc.:
>>> a = 1 # yes
>>> a=1 # too cramped
In [4]: scipy.version.version
Out[4]: '0.7.0'
A certain number of rules for writing beautiful code (and more importantly using the same conventions as anybody else!) are given in the Style Guide for Python Code.
Quick read
If you want to do a first quick pass through the Scipy lectures to learn the ecosystem, you can directly
skip to the next chapter: NumPy: creating and manipulating numerical data.
The remainder of this chapter is not necessary to follow the rest of the intro part. But be sure to come
back and finish this chapter later.
To be exhaustive, here are some information about input and output in Python. Since we will use the Numpy
methods to read and write files, you may skip this chapter at first reading.
We write or read strings to/from files (other types must be converted to strings). To write in a file:
>>> f = open('workfile', 'w') # opens the workfile file
>>> type(f)
<type 'file'>
>>> f.write('This is a test \nand another test')
>>> f.close()
Indentation: no choice!
In [2]: s = f.read()
Indenting is compulsory in Python! Every command block following a colon bears an additional indentation
level with respect to the previous line with a colon. One must therefore indent after def f(): or while:.
At the end of such logical blocks, one decreases the indentation depth (and re-increases it if a new block is
entered, etc.)
Strict respect of indentation is the price to pay for getting rid of { or ; characters that delineate logical blocks
in other languages. Improper indentation leads to errors such as
In [3]: print(s)
This is a test
and another test
In [4]: f.close()
See also:
All this indentation business can be a bit confusing in the beginning. However, with the clear indentation, and
in the absence of extra characters, the resulting code is very nice to read compared to other languages.
33
34
'debugging.rst',
...
Make a directory:
In [32]: os.mkdir('junkdir')
In [33]: 'junkdir' in os.listdir(os.curdir)
Out[33]: True
In [8]: f.close()
File modes
Read-only: r
Write-only: w
In [41]: os.rmdir('foodir')
Append a file: a
Read and Write: r+
Delete a file:
Binary mode: b
In [45]: fp.close()
In [71]: fp.close()
Current directory:
In [72]: a = os.path.abspath('junk.txt')
In [17]: os.getcwd()
Out[17]: '/Users/cburns/src/scipy2009/scipy_2009_tutorial/source'
In [73]: a
Out[73]: '/Users/cburns/src/scipy2009/scipy_2009_tutorial/source/junk.txt'
List a directory:
In [74]: os.path.split(a)
Out[74]: ('/Users/cburns/src/scipy2009/scipy_2009_tutorial/source',
'junk.txt')
In [31]: os.listdir(os.curdir)
Out[31]:
['.index.rst.swo',
'.python_language.rst.swp',
'.view_array.py.swp',
'_static',
'_templates',
'basic_types.rst',
'conf.py',
'control_flow.rst',
In [78]: os.path.dirname(a)
Out[78]: '/Users/cburns/src/scipy2009/scipy_2009_tutorial/source'
In [79]: os.path.basename(a)
Out[79]: 'junk.txt'
In [80]: os.path.splitext(os.path.basename(a))
35
36
In [9]: import os
In [84]: os.path.exists('junk.txt')
Out[84]: True
In [11]: os.environ.keys()
Out[11]:
['_',
'FSLDIR',
'TERM_PROGRAM_VERSION',
'FSLREMOTECALL',
'USER',
'HOME',
'PATH',
'PS1',
'SHELL',
'EDITOR',
'WORKON_HOME',
'PYTHONPATH',
...
In [86]: os.path.isfile('junk.txt')
Out[86]: True
In [87]: os.path.isdir('junk.txt')
Out[87]: False
In [88]: os.path.expanduser('~/local')
Out[88]: '/Users/cburns/local'
In [92]: os.path.join(os.path.expanduser('~'), 'local', 'bin')
Out[92]: '/Users/cburns/local/bin'
functions.rst
io.rst
oop.rst
python_language.rst
python-logo.png
reusing_code.rst
In [12]: os.environ['PYTHONPATH']
Out[12]: '.:/Users/cburns/src/utils:/Users/cburns/src/nitools:
/Users/cburns/local/lib/python2.5/site-packages/:
/usr/local/lib/python2.5/site-packages/:
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5'
standard_library.rst
Alternative to os.system
A noteworthy alternative to os.system is the sh module. Which provides much more convenient ways to
obtain the output, error stream and exit code of the external command.
In [20]: import sh
In [20]: com = sh.ls()
In [21]: print com
basic_types.rst
exceptions.rst
control_flow.rst first_steps.rst
demo2.py
functions.rst
demo.py
io.rst
oop.rst
python_language.rst
python-logo.png
reusing_code.rst
In [16]: os.getenv('PYTHONPATH')
Out[16]: '.:/Users/cburns/src/utils:/Users/cburns/src/nitools:
/Users/cburns/local/lib/python2.5/site-packages/:
/usr/local/lib/python2.5/site-packages/:
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5'
standard_library.rst
Walking a directory
37
38
2.8.1 Exceptions
In [117]: sys.platform
Out[117]: 'darwin'
In [118]: sys.version
Out[118]: '2.5.2 (r252:60911, Feb 22 2008, 07:57:53) \n
[GCC 4.0.1 (Apple Computer, Inc. build 5363)]'
In [1]: 1/0
--------------------------------------------------------------------------ZeroDivisionError: integer division or modulo by zero
In [119]: sys.prefix
Out[119]: '/Library/Frameworks/Python.framework/Versions/2.5'
In [2]: 1 + 'e'
--------------------------------------------------------------------------TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [100]: sys.argv
Out[100]: ['/Users/cburns/local/bin/ipython']
In [4]: d[3]
--------------------------------------------------------------------------KeyError: 3
sys.path is a list of strings that specifies the search path for modules. Initialized from PYTHONPATH:
In [121]: sys.path
Out[121]:
['',
'/Users/cburns/local/bin',
'/Users/cburns/local/lib/python2.5/site-packages/grin-1.1-py2.5.egg',
'/Users/cburns/local/lib/python2.5/site-packages/argparse-0.8.0-py2.5.egg',
'/Users/cburns/local/lib/python2.5/site-packages/urwid-0.9.7.1-py2.5.egg',
'/Users/cburns/local/lib/python2.5/site-packages/yolk-0.4.1-py2.5.egg',
'/Users/cburns/local/lib/python2.5/site-packages/virtualenv-1.2-py2.5.egg',
...
In [5]: l = [1, 2, 3]
In [6]: l[4]
--------------------------------------------------------------------------IndexError: list index out of range
In [7]: l.foobar
--------------------------------------------------------------------------AttributeError: 'list' object has no attribute 'foobar'
As you can see, there are different types of exceptions for different errors.
try/except
Exercise
Write a program to search your PYTHONPATH for the module site.py.
path_site
In [9]: x
Out[9]: 1
try/finally
Exceptions are raised by different kinds of errors arising when executing Python code. In your own code, you
may also catch errors, or define custom error types. You may want to look at the descriptions of the the built-in
Exceptions when looking for the right exception type.
In [10]: try:
....:
x = int(raw_input('Please enter a number: '))
....: finally:
....:
print('Thank you for your input')
....:
....:
Please enter a number: a
Thank you for your input
--------------------------------------------------------------------------ValueError: invalid literal for int() with base 10: 'a'
It is likely that you have raised Exceptions if you have typed all the previous commands of the tutorial. For
example, you may have raised an exception if you entered a command with a typo.
39
40
....:
....:
In [20]: x
Out[20]: 0.9990234375
Use exceptions to notify certain conditions are met (e.g. StopIteration) or not (e.g. custom error raising)
Here is a small example: we create a Student class, which is an object gathering several custom functions
(methods) and variables (attributes), we will be able to use:
In [14]: print_sorted('132')
132
>>>
...
...
...
...
...
...
...
>>>
>>>
>>>
class Student(object):
def __init__(self, name):
self.name = name
def set_age(self, age):
self.age = age
def set_major(self, major):
self.major = major
anna = Student('anna')
anna.set_age(21)
anna.set_major('physics')
In the previous example, the Student class has __init__, set_age and set_major methods. Its attributes are name, age and major. We can call these methods and attributes with the following notation:
classinstance.method or classinstance.attribute. The __init__ constructor is a special method we
call with: MyClass(init parameters if any).
Now, suppose we want to create a new class MasterStudent with the same methods and attributes as the previous one, but with an additional internship attribute. We wont copy the previous class, but inherit from
it:
In [16]: filter_name('Gal')
OK, Gal
Out[16]: 'Ga\xc3\xabl'
In [17]: filter_name('Stfan')
--------------------------------------------------------------------------UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in range(128)
The MasterStudent class inherited from the Student attributes and methods.
Thanks to classes and object-oriented programming, we can organize code with different classes corresponding to different objects we encounter (an Experiment class, an Image class, a Flow class, etc.), with their own
methods and attributes. Then we can use inheritance to consider variations around a base class and re-use
code. Ex : from a Flow base class, we can create derived StokesFlow, TurbulentFlow, PotentialFlow, etc.
In [18]: x = 0
In [19]: while True:
....:
try:
....:
x = achilles_arrow(x)
....:
except StopIteration:
....:
break
41
42
Authors: Emmanuelle Gouillart, Didrik Pinte, Gal Varoquaux, and Pauli Virtanen
This chapter gives an overview of Numpy, the core tool for performant numerical computing with Python.
In [3]: a = np.arange(1000)
In [4]: %timeit a**2
100000 loops, best of 3: 12.7 us per loop
Interactive help:
In [5]: np.array?
String Form:<built-in function array>
Docstring:
array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0, ...
In [6]: np.con*?
np.concatenate
np.conj
np.conjugate
np.convolve
Import conventions
43
44
or by number of points:
>>> c =
>>> c
array([
>>> d =
>>> d
array([
np.linspace(0, 1, 6)
0.2,
0.4,
0.6,
0.8])
Common arrays:
>>> a = np.ones((3, 3)) # reminder: (3, 3) is a tuple
>>> a
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
>>> b = np.zeros((2, 2))
>>> b
array([[ 0., 0.],
[ 0., 0.]])
>>> c = np.eye(3)
>>> c
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> d = np.diag(np.array([1, 2, 3, 4]))
>>> d
array([[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]])
[[3],
[4]]])
>>> c.shape
(2, 2, 1)
>>> b = np.random.randn(4)
# Gaussian
>>> b
array([ 0.37544699, -0.11425369, -0.47616538,
>>> np.random.seed(1234)
Create a simple two dimensional array. First, redo the examples from above. And then create your
own: how about odd numbers counting backwards on the first row, and even numbers on the
second?
Use the functions len(), numpy.shape() on these arrays. How do they relate to each other? And
to the ndim attribute of the arrays?
1.79664113])
Evenly spaced:
You may have noticed that, in some instances, array elements are displayed with a trailing dot (e.g. 2. vs 2).
This is due to a difference in the data-type used:
45
46
>>> b.dtype
dtype('float64')
>>> %matplotlib
Different data-types allow us to store data more compactly in memory, but most of the time we simply work
with floating point numbers. Note that, in the example above, NumPy auto-detects the data-type from the
input.
The inline is important for the notebook, so that plots are displayed in the notebook and not in a new window.
Matplotlib is a 2D plotting package. We can import its functions as below:
And then use (note that you have to use show explicitly if you have not enabled interactive plots with
%matplotlib):
>>> plt.plot(x, y)
>>> plt.show()
# line plot
# <-- shows the plot (not needed with interactive plots)
# line plot
1D plotting:
Complex
Bool
>>> e = np.array([True, False, False, True])
>>> e.dtype
dtype('bool')
9
8
7
6
5
4
3
2
1
0
0.0
Strings
>>> f = np.array(['Bonjour', 'Hello', 'Hallo',])
>>> f.dtype
# <--- strings containing max. 7 letters
dtype('S7')
Much more
int32
int64
uint32
uint64
Or the notebook:
0.5
1.0
1.5
2.0
2.5
3.0
$ ipython notebook
47
48
>>> a[::-1]
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
0
5
10
15
20
25
0
10
15
20
25
>>> a = np.diag(np.arange(3))
>>> a
array([[0, 0, 0],
[0, 1, 0],
[0, 0, 2]])
>>> a[1, 1]
1
>>> a[2, 1] = 10 # third line, second column
>>> a
array([[ 0, 0, 0],
[ 0, 1, 0],
[ 0, 10, 2]])
>>> a[1]
array([0, 1, 0])
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0.0
See also:
All three slice components are not required: by default, start is 0, end is the last and step is 1:
>>> a[1:3]
array([1, 2])
>>> a[::2]
array([0, 2, 4, 6, 8])
>>> a[3:]
array([3, 4, 5, 6, 7, 8, 9])
at 1.
The usual python idiom for reversing a sequence is supported:
49
50
1,
1,
1,
6,
[[0.,
[2.,
[0.,
[0.,
[0.,
[0.,
1,
1,
1,
1,
0.,
0.,
3.,
0.,
0.,
0.,
1],
1],
2],
1]]
0.,
0.,
0.,
4.,
0.,
0.,
0.,
0.,
0.,
0.,
5.,
0.,
0.],
0.],
0.],
0.],
0.],
6.]]
[[4,
[2,
[4,
[2,
>>> a = np.arange(10)
>>> a[5:] = 10
>>> a
array([ 0, 1, 2, 3, 4, 10, 10, 10, 10, 10])
>>> b = np.arange(5)
>>> a[5:] = b[::-1]
>>> a
array([0, 1, 2, 3, 4, 4, 3, 2, 1, 0])
3,
1,
3,
1,
4,
2,
4,
2,
3,
1,
3,
1,
4,
2,
4,
2,
3],
1],
3],
1]]
8,
9])
>>> a = np.arange(10)
>>> c = a[::2].copy() # force a copy
>>> c[0] = 12
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.may_share_memory(a, c)
False
51
52
This behavior can be surprising at first sight... but it allows to save both memory and time.
>>> mask = (a % 3 == 0)
>>> extract_from_a = a[mask] # or, a[a%3==0]
>>> extract_from_a
# extract a sub-array with the mask
array([ 3, 0, 9, 6, 0, 12])
Indexing with a mask can be very useful to assign a new value to a sub-array:
>>> a[a % 3 == 0] = -1
>>> a
array([10, -1, 8, -1, 19, 10, 11, -1, 10, -1, -1, 20, -1,
7, 14])
Indexing can be done with an array of integers, where the same index is repeated several time:
>>> a[[2, 3, 2, 4, 2]] # note: [2, 3, 2, 4, 2] is a Python list
array([20, 30, 20, 40, 20])
30,
40,
50,
60, -100,
80, -100])
When a new array is created by indexing with an array of integers, the new array has the same shape than the
array of integers:
For each integer j starting from 2, cross out its higher multiples:
>>> a = np.arange(10)
>>> idx = np.array([[3, 4], [9, 7]])
>>> idx.shape
(2, 2)
>>> a[idx]
array([[3, 4],
[9, 7]])
53
54
>>> c.dot(c)
array([[ 3.,
[ 3.,
[ 3.,
Section contents
Elementwise operations
Basic reductions
Broadcasting
Array shape manipulation
Sorting data
Summary
3.,
3.,
3.,
3.],
3.],
3.]])
Other operations
Basic operations
Comparisons:
With scalars:
Array-wise comparisons:
>>> b = np.ones(4) + 1
>>> a - b
array([-1., 0., 1., 2.])
>>> a * b
array([ 2., 4., 6., 8.])
>>> j = np.arange(5)
>>> 2**(j + 1) - j
array([ 2, 3, 6, 13, 28])
Logical operations:
>>> a = np.array([1, 1, 0, 0], dtype=bool)
>>> b = np.array([1, 0, 1, 0], dtype=bool)
>>> np.logical_or(a, b)
array([ True, True, True, False], dtype=bool)
>>> np.logical_and(a, b)
array([ True, False, False, False], dtype=bool)
These operations are of course much faster than if you did them in pure python:
>>> a = np.arange(10000)
>>> %timeit a + 1
10000 loops, best of 3: 24.3 us per loop
>>> l = range(10000)
>>> %timeit [i+1 for i in l]
1000 loops, best of 3: 861 us per loop
Matrix multiplication:
Transcendental functions:
>>> a = np.arange(5)
>>> np.sin(a)
array([ 0.
, 0.84147098, 0.90929743, 0.14112001, -0.7568025 ])
>>> np.log(a)
array([
-inf, 0.
, 0.69314718, 1.09861229, 1.38629436])
>>> np.exp(a)
array([ 1.
,
2.71828183,
7.3890561 , 20.08553692, 54.59815003])
55
56
Shape mismatches
>>> a = np.arange(4)
>>> a + np.array([1, 2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4) (2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4) (2)
# see help(np.triu)
As a results, the following code is wrong and will not make a matrix symmetric:
>>> a += a.T
It will work for small arrays (because of buffering) but fail for large one, in unpredictable ways.
Linear algebra
The sub-module numpy.linalg implements basic linear algebra, such as solving linear systems, singular
value decomposition, etc. However, it is not guaranteed to be compiled using efficient routines, and thus
we recommend the use of scipy.linalg, as detailed in section Linear algebra operations: scipy.linalg
Exercise other operations
Look at the help for np.allclose. When might this be useful?
Look at the help for np.triu and np.tril.
Other reductions
works the same way (and take axis=)
Extrema:
>>> x = np.array([1, 3, 2])
>>> x.min()
1
>>> x.max()
3
Computing sums
>>> x = np.array([1, 2, 3, 4])
>>> np.sum(x)
10
>>> x.sum()
10
>>> x.argmin()
0
>>> x.argmax()
1
# index of minimum
# index of maximum
Logical operations:
>>> np.all([True, True, False])
False
>>> np.any([True, True, False])
True
57
58
Data in populations.txt describes the populations of hares and lynxes (and carrots) in northern
Canada during 20 years.
You can view the data in an editor, or alternatively in IPython (both shell and notebook):
In [1]: !cat data/populations.txt
np.array([1, 2, 3, 2])
np.array([2, 2, 3, 2])
np.array([6, 4, 4, 5])
<= b) & (b <= c)).all()
Statistics:
>>>
>>>
>>>
>>>
80000
70000
60000
Hare
Lynx
Carrot
50000
Exercise: Reductions
Given there is a sum, what other function might you expect to see?
What is the difference between sum and cumsum?
40000
30000
20000
10000
0
1900 1905 1910 1915 1920
The mean populations over time:
>>> populations = data[:, 1:]
>>> populations.mean(axis=0)
array([ 34080.95238095, 20166.66666667,
42400.
])
3322.50622558])
59
60
3.2.3 Broadcasting
Worked Example: diffusion using a random walk algorithm
Let us consider a simple 1D random walk process: at each time step a walker jumps right or left with
equal probability.
We are interested in finding the typical distance from the origin of a random walker after t left or right
jumps? We are going to simulate many walkers to find this law, and we are going to do so using array
computing tricks: we are going to create a 2D array with the stories (each walker has a story) in one
direction, and the time in the other:
Lets verify:
(x)2
16
14
12
10
8
6
Numerical operations on arrays
4
2
3.2.
61
62
[ 1.,
[ 1.,
1.,
1.,
1.,
1.,
1.,
1.,
1.],
1.]])
An useful trick:
>>> a = np.arange(0, 40, 10)
>>> a.shape
(4,)
>>> a = a[:, np.newaxis] # adds a new axis -> 2D array
>>> a.shape
(4, 1)
>>> a
array([[ 0],
[10],
[20],
[30]])
>>> a + b
array([[ 0, 1, 2],
[10, 11, 12],
[20, 21, 22],
[30, 31, 32]])
4.
],
4.12310563],
4.47213595],
5.
],
5.65685425]])
Or in color:
>>> plt.pcolor(distance)
>>> plt.colorbar()
Broadcasting seems a bit magical, but it is actually quite natural to use it when we want to solve a problem
whose output data is an array with more dimensions than input data.
4
3
>>> mileposts = np.array([0, 198, 303, 736, 871, 1175, 1475, 1544,
...
1913, 2448])
>>> distance_array = np.abs(mileposts - mileposts[:, np.newaxis])
>>> distance_array
array([[
0, 198, 303, 736, 871, 1175, 1475, 1544, 1913, 2448],
[ 198,
0, 105, 538, 673, 977, 1277, 1346, 1715, 2250],
[ 303, 105,
0, 433, 568, 872, 1172, 1241, 1610, 2145],
[ 736, 538, 433,
0, 135, 439, 739, 808, 1177, 1712],
[ 871, 673, 568, 135,
0, 304, 604, 673, 1042, 1577],
[1175, 977, 872, 439, 304,
0, 300, 369, 738, 1273],
[1475, 1277, 1172, 739, 604, 300,
0,
69, 438, 973],
[1544, 1346, 1241, 808, 673, 369,
69,
0, 369, 904],
[1913, 1715, 1610, 1177, 1042, 738, 438, 369,
0, 535],
[2448, 2250, 2145, 1712, 1577, 1273, 973, 904, 535,
0]])
1
0
0
5.4
4.8
4.2
3.6
3.0
2.4
1.8
1.2
0.6
0.0
Remark : the numpy.ogrid function allows to directly create vectors x and y of the previous example, with two
significant dimensions:
>>> x, y = np.ogrid[0:5, 0:5]
>>> x, y
(array([[0],
[1],
[2],
[3],
[4]]), array([[0, 1, 2, 3, 4]]))
>>> x.shape, y.shape
((5, 1), (1, 5))
>>> distance = np.sqrt(x ** 2 + y ** 2)
A lot of grid-based or network-based problems can also use broadcasting. For instance, if we want to compute
the distance from the origin of points on a 10x10 grid, we can do
63
64
So, np.ogrid is very useful as soon as we have to handle computations on a grid. On the other hand, np.mgrid
directly provides matrices full of indices for cases where we cant (or dont want to) benefit from broadcasting:
>>> x, y =
>>> x
array([[0,
[1,
[2,
[3,
>>> y
array([[0,
[0,
[0,
[0,
np.mgrid[0:4, 0:4]
0,
1,
2,
3,
0,
1,
2,
3,
0],
1],
2],
3]])
1,
1,
1,
1,
2,
2,
2,
2,
3],
3],
3],
3]])
>>> b[0, 0] = 99
>>> a
array([[99, 2, 3],
[ 4, 5, 6]])
To understand this you need to learn more about the memory layout of a numpy array.
Adding a dimension
Flattening
Indexing with the np.newaxis object allows us to add an axis to an array (you have seen this already above in
the broadcasting section):
>>> z[np.newaxis, :]
array([[1, 2, 3]])
Reshaping
Dimension shuffling
>>>
>>>
(4,
>>>
5
>>>
>>>
(3,
>>>
5
Or,
>>> a.reshape((2, -1))
array([[1, 2, 3],
[4, 5, 6]])
B
a = np.arange(4*3*2).reshape(4, 3, 2)
a.shape
3, 2)
a[0, 2, 1]
b = a.transpose(1, 2, 0)
b.shape
2, 4)
b[2, 1, 0]
Resizing
Size of an array can be changed with ndarray.resize:
>>> a = np.arange(4)
>>> a.resize((8,))
>>> a
array([0, 1, 2, 3, 0, 0, 0, 0])
65
66
Exercise: Sorting
>>> b = a
>>> a.resize((4,))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot resize an array that has been referenced or is
referencing another array in this way. Use the resize function
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot resize an array that has been referenced or is
3.2.6 Summary
What do you need to know to get started?
Look at the docstring for reshape, especially the notes section which has some more information
about copies and views.
Use flatten as an alternative to ravel. What is the difference? (Hint: check which one returns a
view and which a copy)
Experiment with transpose for dimension shuffling.
Know the shape of the array with array.shape, then use slicing to obtain different views of the array:
array[::2], etc. Adjust the shape of the array using reshape or flatten it with ravel.
Obtain a subset of the elements of an array and/or modify their values with masks
>>> a[a < 0] = 0
Know miscellaneous operations on arrays, such as finding the mean or max (array.max(),
array.mean()). No need to retain everything, but have the reflex to search in the documentation (online docs, help(), lookfor())!!
For advanced use: master the indexing with arrays of integers, as well as broadcasting. Know more
Numpy functions to handle various array operations.
Quick read
If you want to do a first quick pass through the Scipy lectures to learn the ecosystem, you can directly
skip to the next chapter: Matplotlib: plotting.
The remainder of this chapter is not necessary to follow the rest of the intro part. But be sure to come
back and finish this chapter, as well as to do some more exercices.
Section contents
More data types
Structured data types
maskedarray: dealing with (propagation of) missing data
a = np.array([4, 3, 1, 2])
j_max = np.argmax(a)
j_min = np.argmin(a)
j_max, j_min
2)
Casting
Bigger type wins in mixed-type operations:
>>> np.array([1, 2, 3]) + 1.5
array([ 2.5, 3.5, 4.5])
67
68
16 bits
32 bits
64 bits (same as float)
96 bits, platform-dependent (same as np.longdouble)
128 bits, platform-dependent (same as np.longdouble)
>>> np.finfo(np.float32).eps
1.1920929e-07
>>> np.finfo(np.float64).eps
2.2204460492503131e-16
Forced casts:
>>> a = np.array([1.7, 1.2, 1.6])
>>> b = a.astype(int) # <-- truncates to integer
>>> b
array([1, 1, 1])
Rounding:
>>> a = np.array([1.2, 1.5, 1.6, 2.5, 3.5, 4.5])
>>> b = np.around(a)
>>> b
# still floating-point
array([ 1., 2., 2., 2., 4., 4.])
>>> c = np.around(a).astype(int)
>>> c
array([1, 2, 2, 2, 4, 4])
complex64
complex128
complex192
complex256
int8
int16
int32
int64
8 bits
16 bits
32 bits (same as int on 32-bit platform)
64 bits (same as int on 64-bit platform)
Unsigned integers:
uint8
uint16
uint32
uint64
But: bigger rounding errors sometimes in surprising places (i.e., dont use them unless you really
need them)
8 bits
16 bits
32 bits
64 bits
sensor_code
position
value
Long integers
(4-character string)
(float)
(float)
Python 2 has a specific type for long integers, that cannot overflow, represented with an L at the end.
In Python 3, all integers are long, and thus cannot overflow.
>>> np.iinfo(np.int64).max, 2**63 - 1
(9223372036854775807, 9223372036854775807L)
Floating-point numbers:
69
70
Good practices
Explicit variable names (no need of a comment to explain what is in the variable)
Style: spaces after commas, around =, etc.
A certain number of rules for writing beautiful code (and, more importantly, using the same conventions as everybody else!) are given in the Style Guide for Python Code and the Docstring Conventions page (to manage help strings).
Except some rare cases, variable names and comments in English.
Section contents
Polynomials
Loading data files
3.4.1 Polynomials
For example, 3x 2 + 2x 1:
>>> p = np.poly1d([3, 2, -1])
>>> p(0)
-1
>>> p.roots
array([-1.
, 0.33333333])
>>> p.order
2
There are a bunch of other syntaxes for constructing structured arrays, see here and here.
While it is off topic in a chapter on numpy, lets take a moment to recall good coding practice, which really do
pay off in the long run:
71
72
1.3
1.3
1.2
1.2
1.1
1.1
1.0
1.0
0.9
0.9
0.8
0.8
0.7
0.7
0.6
0.6
0.0
0.2
0.4
0.6
0.8
0.5
1.0
1.0
0.5
0.0
0.5
Numpy also has a more sophisticated polynomial interface, which supports e.g. the Chebyshev basis.
Text files
3x 2 + 2x 1:
Example: populations.txt:
# year
1900
1901
1902
1903
Example using polynomials in Chebyshev basis, for polynomials in range [-1, 1]:
lynx
4e3
6.1e3
9.8e3
35.2e3
carrot
48300
48200
41500
38200
hare
30e3
47.2e3
70.2e3
77.4e3
1.0
If you have a complicated text file, what you can try are:
np.genfromtxt
Using Pythons I/O functions and e.g. regexps for parsing (Python is quite well suited for this)
73
74
0
5
10
Images
15
Using Matplotlib:
20
25
30
10
20
30
40
>>> plt.imshow(plt.imread('red_elephant.png'))
<matplotlib.image.AxesImage object at ...>
Other libraries:
Numpy has its own binary format, not portable but with efficient I/O:
>>> data = np.ones((3, 3))
>>> np.save('pop.npy', data)
>>> data3 = np.load('pop.npy')
75
76
The face is displayed in false colors. A colormap must be specified for it to be displayed in grey.
Numpy internals
If you are interested in the Numpy internals, there is a good discussion in Advanced Numpy.
Create an array of the image with a narrower centering [for example,] remove 100 pixels from all the
borders of the image. To check the result, display this new array with imshow.
We will now frame the face with a black locket. For this, we need to create a mask corresponding to
the pixels we want to be black. The center of the face is around (660, 330), so we defined the mask
by this condition (y-300)**2 + (x-660)**2
11],
12],
13],
14],
15]]
and generate a new array containing its 2nd and 4th rows.
then we assign the value 0 to the pixels of the image corresponding to the mask. The syntax is
extremely simple and intuitive:
>>> face[mask] = 0
>>> plt.imshow(face)
<matplotlib.image.AxesImage object at 0x...>
elementwise with the array b = np.array([1., 5, 10, 15, 20]). (Hint: np.newaxis).
3. Harder one: Generate a 10 x 3 array of random numbers (in range [0,1]). For each row, pick the number
closest to 0.5.
Use abs and argsort to find the column j closest for each row.
Use fancy indexing to extract the numbers. (Hint: a[i,j] the array i must contain the row numbers corresponding to stuff in j.)
Follow-up: copy all instructions of this exercise in a script called face_locket.py then execute this
script in IPython with %run face_locket.py.
# 2D grayscale image
Here are a few images we will be able to obtain with our manipulations: use different colormaps, crop the
image, change some parts of the image.
77
78
80000
70000
60000
Hare
Lynx
Carrot
50000
40000
1.5
30000
1.0
20000
0.5
10000
0.0
0
1900 1905 1910 1915 1920
0.5
1.0
1. The mean and std of the populations of each species for the years in the period.
2. Which year each species had the largest population.
3. Which species has the largest population for each year.
np.array([H, L, C]))
4. Which years any of the populations is above 50000. (Hint: comparisons and np.any)
1.5
2.0
1.5
1.0
0.5 0.0
0.5
1.0
5. The top 2 years for each species when they had the lowest populations. (Hint: argsort, fancy indexing)
6. Compare (plot) the change in hare population (see help(np.gradient)) and the number of lynxes.
Check correlation (see help(np.corrcoef)).
... all without for-loops.
N_max = 50
some_threshold = 50
c = x + 1j*y
for j in xrange(N_max):
z = z**2 + c
1
0
2. Do the iteration
(a b c)d a d b d c
3. Form the 2-d boolean mask indicating which points are in the set
4. Save the result to an image with:
1
2
over this volume with the mean. The exact result is: ln 2 0.1931 . . . what is your relative error?
(Hints: use elementwise operations and broadcasting. You can make np.ogrid give a number of points in
given range with np.ogrid[0:1:20j].)
Write a script that computes the Mandelbrot fractal. The Mandelbrot iteration:
79
80
>>> plt.gray()
>>> plt.savefig('mandelbrot.png')
Matplotlib: plotting
Thanks
Many thanks to Bill Wing and Christoph Deil for review and corrections.
Authors: Nicolas Rougier, Mike Mller, Gal Varoquaux
Chapter contents
Introduction
Simple plot
Figures, Subplots, Axes and Ticks
Other Types of Plots: examples and exercises
Beyond this tutorial
Quick references
4.1 Introduction
Constructs a random matrix, and normalizes each row so that it is a transition matrix.
Starts from a random (normalized) probability distribution p and takes 50 steps => p_50
Computes the stationary distribution: the eigenvector of P.T with eigenvalue 1 (numerically: closest to
1) => p_stationary
Matplotlib is probably the single most used Python package for 2D-graphics. It provides both a very quick
way to visualize data from Python and publication-quality figures in many formats. We are going to explore
matplotlib in interactive mode covering most common cases.
IPython is an enhanced interactive Python shell that has lots of interesting features including named inputs
and outputs, access to shell commands, improved debugging and many more. It is central to the scientificcomputing workflow in Python for its use in combination with Matplotlib:
For interactive matplotlib sessions with Matlab/Mathematica-like functionality, we use IPython with its special Matplotlib mode that enables non-blocking plotting.
IPython console When using the IPython console, we start it with the command line argument
--matplotlib (-pylab in very old versions).
IPython notebook In the IPython notebook, we insert, at the beginning of the notebook the following magic:
%matplotlib inline
81
82
4.1.2 pyplot
pyplot provides a procedural interface to the matplotlib object-oriented plotting library. It is modeled closely
after Matlab. Therefore, the majority of plotting commands in pyplot have Matlab analogs with similar
arguments. Important commands are explained with interactive examples.
from matplotlitb import pyplot as plt
Matplotlib comes with a set of default settings that allow customizing all kinds of properties. You can control
the defaults of almost every property in matplotlib: figure size and dpi, line width, color and style, axes, axis
and grid properties, text and font properties and so on.
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)
plt.plot(X, C)
plt.plot(X, S)
In this section, we want to draw the cosine and sine functions on the same plot. Starting from the default
settings, well enrich the figure step by step to make it nicer.
First step is to get the data for the sine and cosine functions:
import numpy as np
plt.show()
X is now a numpy array with 256 values ranging from - to + (included). C is the cosine (256 values) and S is
the sine (256 values).
To run the example, you can type them in an IPython interactive session:
$ ipython --pylab
Documentation
Customizing matplotlib
In the script below, weve instantiated (and commented) all the figure settings that influence the appearance
of the plot.
The settings have been explicitly set to their default values, but now you can interactively play with the values
to explore their affect (see Line properties and Line styles below).
import numpy as np
import matplotlib.pyplot as plt
You can also download each of the examples and run it using regular python, but you will loose interactive
data manipulation:
$ python exercice_1.py
You can get source for each step by clicking on the corresponding figure.
Documentation
plot tutorial
plot() command
# Set y limits
plt.ylim(-1.0, 1.0)
83
84
# Set y ticks
plt.yticks(np.linspace(-1, 1, 5, endpoint=True))
# Save figure using 72 dots per inch
# plt.savefig("exercice_2.png", dpi=72)
# Show result on screen
plt.show()
Documentation
xticks() command
yticks() command
Tick container
Tick locating and formatting
Current ticks are not ideal because they do not show the interesting values (+/-,+/-/2) for sine and cosine.
Well change them such that they show only these values.
...
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
plt.yticks([-1, 0, +1])
...
Documentation
Controlling line properties
Line API
First step, we want to have the cosine in blue and the sine in red and a slighty thicker line for both of them.
Well also slightly alter the figure size to make it more horizontal.
...
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")
...
Documentation
Working with text
xticks() command
yticks() command
set_xticklabels()
set_yticklabels()
Ticks are now properly placed but their label is not very explicit. We could guess that 3.142 is but it would
be better to make it explicit. When we set tick values, we can also provide a corresponding label in the second
argument list. Note that well use latex to allow for nice rendering of the label.
...
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
Documentation
xlim() command
ylim() command
Current limits of the figure are a bit too tight and we want to make some space in order to clearly see all data
points.
...
plt.xlim(X.min() * 1.1, X.max() * 1.1)
plt.ylim(C.min() * 1.1, C.max() * 1.1)
...
85
plt.yticks([-1, 0, +1],
[r'$-1$', r'$0$', r'$+1$'])
...
86
Documentation
Spines
Axis container
Transformations tutorial
Documentation
Annotating axis
annotate() command
Spines are the lines connecting the axis tick marks and noting the boundaries of the data area. They can be
placed at arbitrary positions and until now, they were on the border of the axis. Well change that since we
want to have them in the middle. Since there are four of them (top/bottom/left/right), well discard the top
and right by setting their color to none and well move the bottom and left ones to coordinate 0 in data space
coordinates.
...
ax = plt.gca() # gca stands for 'get current axis'
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
...
Lets annotate some interesting points using the annotate command. We chose the 2/3 value and we want to
annotate both the sine and the cosine. Well first draw a marker on the curve as well as a straight dotted line.
Then, well use the annotate command to display some text with an arrow.
...
t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--")
plt.scatter([t, ], [np.cos(t), ], 50, color='blue')
plt.annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
xy=(t, np.sin(t)), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
plt.plot([t, t],[0, np.sin(t)], color='red', linewidth=2.5, linestyle="--")
plt.scatter([t, ],[np.sin(t), ], 50, color='red')
plt.annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$',
xy=(t, np.cos(t)), xycoords='data',
xytext=(-90, -50), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
...
Documentation
Artists
BBox
The tick labels are now hardly visible because of the blue and red lines. We can make them bigger and we can
also adjust their properties such that theyll be rendered on a semi-transparent white background. This will
allow us to see both the data and the labels.
...
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(16)
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65))
...
87
88
4.3.4 Ticks
4.3.1 Figures
A figure is the windows in the GUI that has Figure # as title. Figures are numbered starting from 1 as opposed
to the normal Python way starting from 0. This is clearly MATLAB-style. There are several parameters that
determine what the figure looks like:
Argument
num
figsize
dpi
facecolor
edgecolor
frameon
Default
1
figure.figsize
figure.dpi
figure.facecolor
figure.edgecolor
True
Well formatted ticks are an important part of publishing-ready figures. Matplotlib provides a totally configurable system for ticks. There are tick locators to specify where ticks should appear and tick formatters to
give ticks the appearance you want. Major and minor ticks can be located and formatted independently from
each other. Per default minor ticks are not shown, i.e. there is only an empty list for them because it is as
NullLocator (see below).
Description
Tick Locators
number of figure
figure size in in inches (width, height)
resolution in dots per inch
color of the drawing background
color of edge around the drawing background
draw figure frame or not
Tick locators control the positions of the ticks. They are set as follows:
ax = plt.gca()
ax.xaxis.set_major_locator(eval(locator))
The defaults can be specified in the resource file and will be used most of the time. Only the number of the
figure is frequently changed.
As with other objects, you can set figure properties also setp or with the set_something methods.
When you work with the GUI you can close a figure by clicking on the x in the upper right corner. But you can
close a figure programmatically by calling close. Depending on the argument it closes (1) the current figure
(no argument), (2) a specific figure (figure number or figure instance as argument), or (3) all figures ("all" as
argument).
plt.close(1)
# Closes figure 1
4.3.2 Subplots
With subplot you can arrange plots in a regular grid. You need to specify the number of rows and columns and
the number of the plot. Note that the gridspec command is a more powerful alternative.
4.3.3 Axes
Axes are very similar to subplots but allow placement of plots at any location in the figure.
So if we want to put a smaller plot inside a bigger one we do so with axes.
89
90
Starting from the code below, try to reproduce the graphic on the right by adding labels for red bars.
n = 256
X = np.linspace(-np.pi, np.pi, n, endpoint=True)
Y = np.sin(2 * X)
n = 12
X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
plt.ylim(-1.25, +1.25)
plt.scatter(X,Y)
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)
plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap='jet')
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
91
92
4.4.5 Imshow
You need to take care of the origin of the image in the imshow command and use a colorbar
Starting from the code below, try to reproduce the graphic on the right taking care of colormap, image interpolation and origin.
def f(x, y):
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
n = 10
x = np.linspace(-3, 3, 4 * n)
y = np.linspace(-3, 3, 3 * n)
X, Y = np.meshgrid(x, y)
plt.imshow(f(X, Y))
4.4.8 Grids
Starting from the code below, try to reproduce the graphic on the right
taking care of line styles.
axes = plt.gca()
axes.set_xlim(0, 4)
axes.set_ylim(0, 3)
axes.set_xticklabels([])
axes.set_yticklabels([])
Z = np.random.uniform(0, 1, 20)
plt.pie(Z)
93
94
plt.subplot(2, 2, 1)
plt.subplot(2, 2, 3)
plt.subplot(2, 2, 4)
See also:
3D plotting with Mayavi
4.4.12 Text
plt.axes([0, 0, 1, 1])
N = 20
theta = np.arange(0., 2 * np.pi, 2 * np.pi / N)
radii = 10 * np.random.rand(N)
width = np.pi / 4 * np.random.rand(N)
bars = plt.bar(theta, radii, width=width, bottom=0.0)
Quick read
If you want to do a first quick pass through the Scipy lectures to learn the ecosystem, you can directly
skip to the next chapter: Scipy : high-level scientific computing.
The remainder of this chapter is not necessary to follow the rest of the intro part. But be sure to come
back and finish this chapter later.
4.4.11 3D Plots
Matplotlib benefits from extensive documentation as well as a large community of users and developers. Here
are some links of interest:
4.5.1 Tutorials
95
Pyplot tutorial
Introduction
Controlling line properties
Working with multiple figures and axes
Working with text
Image tutorial
Startup commands
Importing image data into Numpy arrays
Plotting numpy arrays as images
Text tutorial
Text introduction
Basic text commands
Text properties and layout
Writing mathematical expressions
Text rendering With LaTeX
96
4.5.4 Galleries
Annotating text
Artist tutorial
Introduction
Customizing your objects
Object containers
Figure container
Axes container
Axis containers
Tick containers
Path tutorial
Introduction
Bzier example
Compound paths
Transforms tutorial
Introduction
Data coordinates
Axes coordinates
Blended transformations
Using offset transforms to create a shadow effect
The transformation pipeline
The matplotlib gallery is also incredibly useful when you search how to render a given graphic. Each example
comes with its source.
Description
alpha (or a)
antialiased
Installation
color (or c)
Usage
How-To
solid_capstyle
solid_joinstyle
dash_capstyle
The code is well documented and you can quickly access a specific command from within a python session:
dash_joinstyle
marker
see Markers
markeredgewidth
(mew)
markeredgecolor
(mec)
markerfacecolor
(mfc)
markersize (ms)
Appearance
Troubleshooting
Environment Variables
Screenshots
plot(*args, **kwargs)
Plot lines and/or markers to the
:class:`~matplotlib.axes.Axes`. *args* is a variable length
argument, allowing for multiple *x*, *y* pairs with an
optional format string. For example, each of the following is
legal::
plot(x, y)
plot(x, y, 'bo')
plot(y)
plot(y, 'r+')
#
#
#
#
plot x
plot x
plot y
ditto,
97
98
4.6.3 Markers
4.6.4 Colormaps
All colormaps can be reversed by appending _r. For instance, gray_r is the reverse of gray.
If you want to know more about colormaps, checks Documenting the matplotlib colormaps.
99
100
Authors: Adrien Chauve, Andre Espaze, Emmanuelle Gouillart, Gal Varoquaux, Ralf Gommers
They all depend on numpy, but are mostly independent of each other. The standard way of importing Numpy
and these Scipy modules is:
Scipy
The scipy package contains various toolboxes dedicated to common issues in scientific computing. Its
different submodules correspond to different applications, such as interpolation, integration, optimization, image processing, statistics, special functions, etc.
scipy can be compared to other standard scientific-computing libraries, such as the GSL (GNU Scientific
Library for C and C++), or Matlabs toolboxes. scipy is the core package for scientific routines in Python;
it is meant to operate efficiently on numpy arrays, so that numpy and scipy work hand in hand.
Before implementing a routine, it is worth checking if the desired data processing is not already implemented in Scipy. As non-professional programmers, scientists often tend to re-invent the wheel, which
leads to buggy, non-optimal, difficult-to-share and unmaintainable code. By contrast, Scipys routines
are optimized and tested, and should therefore be used when possible.
The main scipy namespace mostly contains functions that are really numpy functions (try scipy.cos is
np.cos). Those are exposed for historical reasons only; theres usually no reason to use import scipy in your
code.
Chapters contents
scipy.cluster
scipy.constants
scipy.fftpack
scipy.integrate
scipy.interpolate
scipy.io
scipy.linalg
scipy.ndimage
scipy.odr
scipy.optimize
scipy.signal
scipy.sparse
scipy.spatial
scipy.special
scipy.stats
Reading images:
B This tutorial is far from an introduction to numerical computing. As enumerating the different submodules
and functions in scipy would be very boring, we concentrate instead on a few examples to give a general idea
of how to use scipy for scientific computing.
See also:
Load text files: numpy.loadtxt()/numpy.savetxt()
101
102
Special functions are transcendental functions. The docstring of the scipy.special module is well-written,
so we wont list all functions here. Frequently used ones are:
0.45294236,
0.29654967])
The original matrix can be re-composed by matrix multiplication of the outputs of svd with np.dot:
Gamma function: scipy.special.gamma(), also note scipy.special.gammaln() which will give the
log of Gamma to a higher numerical precision.
SVD is commonly used in statistics and signal processing. Many other standard decompositions (QR,
LU, Cholesky, Schur), as well as solvers for linear systems, are available in scipy.linalg.
The scipy.linalg module provides standard linear algebra operations, relying on an underlying efficient
implementation (BLAS, LAPACK).
The scipy.linalg.det() function computes the determinant of a square matrix:
>>>
>>>
>>>
>>>
...
time_step = 0.02
period = 5.
time_vec = np.arange(0, 20, time_step)
sig = np.sin(2 * np.pi / period * time_vec) + \
0.5 * np.random.randn(time_vec.size)
The observer doesnt know the signal frequency, only the sampling time step of the signal sig. The
signal is supposed to come from a real function so the Fourier transform will be symmetric. The
scipy.fftpack.fftfreq() function will generate the sampling frequencies and scipy.fftpack.fft() will
compute the fast Fourier transform:
>>> from scipy import fftpack
>>> sample_freq = fftpack.fftfreq(sig.size, d=time_step)
>>> sig_fft = fftpack.fft(sig)
Because the resulting power is symmetric, only the positive part of the spectrum needs to be used for finding
the frequency:
Finally computing the inverse of a singular matrix (its determinant is zero) will raise LinAlgError:
>>> arr = np.array([[3, 2],
...
[6, 4]])
>>> linalg.inv(arr)
Traceback (most recent call last):
...
...LinAlgError: singular matrix
Traceback (most recent call last):
...
...LinAlgError: singular matrix
More advanced operations are available, for example singular-value decomposition (SVD):
103
104
600
Peak frequency
500
2
1
Amplitude
plower
400
300
200
100
0
0
0.050.100.150.200.250.300.350.400.45
5
10
15
Frequency [Hz]
20
0
1
2
3
0
25
10
Time [s]
15
20
numpy.fft
# check that correct freq is found
Numpy also has an implementation of FFT (numpy.fft). However, in general the scipy one should be
preferred, as it uses more efficient underlying implementations.
Now the high-frequency noise will be removed from the Fourier transformed signal:
>>> sig_fft[np.abs(sample_freq) > freq] = 0
105
106
80
f 1 (t ) =
hare
lynx
carrot
70
Population number ( 103 )
60
d t 0 K (t t 0 ) f 0 (t 0 )
f1 () = K () f0 ()
50
40
30
50
20
100
10
0
1900
1905
1910
Year
1915
150
1920
300
50
100
150
200
250
250
Power ( 103 )
200
150
100
50
0
0
10
Period
15
20
107
108
120
100
80
60
40
20
0
1. Examine the provided image moonlanding.png, which is heavily contaminated with periodic
noise. In this exercise, we aim to clean up the noise using the Fast Fourier Transform.
2. Load the image using pylab.imread().
3. Find and use the 2-D FFT function in scipy.fftpack, and plot the spectrum (Fourier transform
of ) the image. Do you have any trouble visualising the spectrum? If so, why?
4. The spectrum consists of high and low frequency components. The noise is contained in the highfrequency part of the spectrum, so set some of those components to zero (use array slicing).
5. Apply the inverse Fourier transform to see the resulting image.
10
10
This function has a global minimum around -1.3 and a local minimum around 3.8.
The general and efficient way to find a minimum for this function is to conduct a gradient descent starting
from a given initial point. The BFGS algorithm is a good way of doing this:
>>> optimize.fmin_bfgs(f, 0)
Optimization terminated successfully.
Current function value: -7.945823
Iterations: 5
Function evaluations: 24
Gradient evaluations: 8
array([-1.30644003])
A possible issue with this approach is that, if the function has local minima the algorithm may find these local
minima instead of the global minimum depending on the initial point:
If we dont know the neighborhood of the global minimum to choose the initial point, we need to resort to
costlier global optimization. To find the global minimum, we use scipy.optimize.basinhopping() (which
combines a local optimizer with stochastic sampling of starting points for the local optimizer):
20
>>> optimize.basinhopping(f, 0)
nfev: 1725
minimization_failures: 0
fun: -7.9458233756152845
x: array([-1.30644001])
message: ['requested number of basinhopping iterations completed successfully']
njev: 575
nit: 100
109
110
Another available (but much less efficient) global optimizer is scipy.optimize.brute() (brute force optimization on a grid). More efficient algorithms for different classes of global optimization problems exist, but
this is out of the scope of scipy. Some useful packages for global optimization are OpenOpt, IPOPT, PyGMO
and PyEvolve.
120
0.16.0.
To
find
the
local
minimum,
scipy.optimize.fminbound():
lets
constraint
the
variable
to
the
interval
80
f(x)
Finding minima of function is discussed in more details in the advanced chapter: Mathematical optimization:
finding minima of functions.
f(x)
Curve fit result
Minima
Roots
100
scipy used to contain the routine anneal, it has been deprecated since SciPy 0.14.0 and removed in SciPy
60
40
a point where f(x) = 0, of the function f above we can use for example
scipy.optimize.fsolve():
20
0
Note that only one root is found. Inspecting the plot of f reveals that there is a second root around -2.5. We
find the exact value of it by adjusting our initial guess:
>>> root2 = optimize.fsolve(f, -2.5)
>>> root2
array([-2.47948183])
20
10
0
x
10
In Scipy >= 0.11 unified interfaces to all minimization and root finding algorithms are available:
scipy.optimize.minimize(), scipy.optimize.minimize_scalar() and scipy.optimize.root().
They allow comparing various algorithms easily through the method keyword.
Curve fitting
You can find algorithms with the same functionalities for multi-dimensional problems in scipy.optimize.
Now if we know the functional form of the function from which the samples were drawn (x^2 + sin(x) in
this case) but not the amplitudes of the terms, we can find those by least squares curve fitting. First we have to
define the function to fit:
>>> def f2(x, a, b):
...
return a*x**2 + b*np.sin(x)
The temperature extremes in Alaska for each month, starting in January, are given by (in
degrees Celcius):
max: 17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18
min: -62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58
Now we have found the minima and roots of f and used curve fitting on it, we put all those resuls together in a
single plot:
111
112
>>> a = np.random.normal(size=1000)
>>> bins = np.arange(-4, 5)
>>> bins
array([-4, -3, -2, -1, 0, 1, 2, 3, 4])
>>> histogram = np.histogram(a, bins=bins, normed=True)[0]
>>> bins = 0.5*(bins[1:] + bins[:-1])
>>> bins
array([-3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5])
>>> from scipy import stats
>>> b = stats.norm.pdf(bins) # norm is a distribution
f(x, y)
2.01.51.0
0.50.0
x 0.51.01.5
2.0 1.0
0.40
0.35
0.30
0.25
0.20
0.15
0.10
0.05
x4 2
)x + x y + (4y 2 4)y 2
3
0.00
has multiple global and local minima. Find the global minima of this function.
Hints:
Variables can be restricted to -2 < x < 2 and -1 < y < 1.
Use numpy.meshgrid() and pylab.imshow() to find visually the regions.
Use scipy.optimize.fmin_bfgs() or another multi-dimensional minimizer.
How many global minima are there, and what is the function value at those points? What
happens for an initial guess of (x, y) = (0, 0)?
If we know that the random process belongs to a given family of random processes, such as normal processes,
we can do a maximum-likelihood fit of the observations to estimate the parameters of the underlying distribution. Here we fit a normal process to the observed data:
See the summary exercise on Non linear least squares curve fitting: application to point extraction in topographical lidar data for another, more advanced example.
Generate 1000 random variates from a gamma distribution with a shape parameter of 1, then plot a
histogram from those samples. Can you plot the pdf on top (it should match)?
Extra: the distributions have a number of useful methods. Explore them by reading the docstring or by
using IPython tab completion. Can you find the shape parameter of 1 back by using the fit method on
your random variates?
5.6.2 Percentiles
The median is the value with half of the observations below, and half above:
113
114
>>> np.median(a)
0.04041769593...
It is also called the percentile 50, because 50% of the observation are below it:
1.0
0.5
0.0
0.5
1.0
1.5
0.0
0.2
0.4
0.6
0.8
1.0
scipy.integrate also features routines for integrating Ordinary Differential Equations (ODE). In particular,
scipy.integrate.odeint() is a general-purpose integrator using LSODA (Livermore Solver for Ordinary
Differential equations with Automatic method switching for stiff and non-stiff problems), see the ODEPACK
Fortran library for more details.
A cubic interpolation can also be selected by providing the kind optional keyword argument:
measures
linear interp
cubic interp
115
116
As an introduction, let us solve the ODE dy/dt = -2y between t = 0..4, with the initial condition y(t=0)
= 1. First the function computing the derivative of the position needs to be defined:
>>> def calc_derivative(ypos, time, counter_arr):
...
counter_arr += 1
...
return -2 * ypos
...
For the scipy.integrate.odeint() solver the 2nd order equation needs to be transformed in a system of
two first-order equations for the vector Y=(y, y). It will be convenient to define nu = 2 eps * wo = c /
m and om = wo^2 = k/m:
An extra argument counter_arr has been added to illustrate that the function may be called several times for
a single time step, until solver convergence. The counter array is defined as:
>>> counter = np.zeros((1,), dtype=np.uint16)
Thus the function will calculate the velocity and acceleration by:
Thus the derivative function has been called more than 40 times (which was the number of time steps):
The final position and velocity are shown on the following Matplotlib figure:
>>> counter
array([129], dtype=uint16)
1.5
and the cumulative number of iterations for each of the 10 first time steps can be obtained by:
1.0
>>> info['nfe'][:10]
array([31, 35, 43, 49, 53, 57, 59, 63, 65, 69], dtype=int32)
0.5
Note that the solver requires more iterations for the first time step. The solution yvec for the trajectory can
now be plotted:
y
y'
0.0
0.5
1.0
1.0
y position [m]
1.5
0.8
2.0
0.6
2.5
0
10
0.4
There is no Partial Differential Equations (PDE) solver in Scipy. Some Python packages for solving PDEs are
available, such as fipy or SfePy.
0.2
0.0
0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0
Time [s]
Another example with scipy.integrate.odeint() will be a damped spring-mass oscillator (2nd order oscillator). The position of a mass attached to a spring obeys the 2nd order ODE y + 2 eps wo y + wo^2
y = 0 with wo^2 = k/m with k the spring constant, m the mass and eps=c/(2 m wo) with c the damping
coefficient. For this example, we choose the parameters as:
>>> mass = 0.5 # kg
>>> kspring = 4 # N/m
>>> cviscous = 0.4 # N s/m
117
118
Image processing routines may be sorted according to the category of processing they perform.
2
4
0
>>> plt.subplot(151)
<matplotlib.axes._subplots.AxesSubplot object at 0x...>
1.5
1.0
>>> plt.axis('off')
(-0.5, 1023.5, 767.5, -0.5)
0.5
>>> # etc.
0.0
5.10.2 Image filtering
0.5
1.0
1.5
0
Notice how on the side of the window the resampling is less accurate and has a rippling effect.
scipy.signal has many window functions: scipy.signal.hamming(), scipy.signal.bartlett(),
scipy.signal.blackman()...
scipy.signal
filtering
(median
filter
scipy.signal.medfilt(),
scipy.signal.wiener()), but we will discuss this in the image section.
has
Wiener
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
119
120
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])
>>> #Erosion removes objects smaller than the structure
>>> ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])
Dilation
>>> a = np.zeros((5, 5))
>>> a[2, 2] = 1
>>> a
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
>>> ndimage.binary_dilation(a).astype(a.dtype)
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 1., 1., 1., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 0., 0., 0., 0.]])
Opening
Elementary mathematical-morphology operations use a structuring element in order to modify other geometrical structures.
Let us first generate a structuring element
>>> el = ndimage.generate_binary_structure(2, 1)
>>> el
array([[False, True, False],
[...True, True, True],
[False, True, False]], dtype=bool)
>>> el.astype(np.int)
array([[0, 1, 0],
[1, 1, 1],
[0, 1, 0]])
Erosion
>>> a = np.zeros((7, 7), dtype=np.int)
>>> a[1:6, 2:5] = 1
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.binary_erosion(a).astype(a.dtype)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
Closing: ndimage.binary_closing
Exercise
Check that opening amounts to eroding, then dilating.
An opening operation removes small structures, while a closing operation fills small holes. Such operations
121
122
>>> areas
array([ 190.,
45., 424., 278., 459., 190., 549., 424.])
>>> maxima = ndimage.maximum(sig, labels, range(1, labels.max()+1))
>>> maxima
array([ 1.80238238,
1.13527605,
5.51954079,
2.49611818,
6.71673619,
1.80238238, 16.76547217,
5.51954079])
>>> ndimage.find_objects(labels==4)
[(slice(30L, 48L, None), slice(30L, 48L, None))]
>>> sl = ndimage.find_objects(labels==4)
>>> import pylab as pl
>>> pl.imshow(sig[sl[0]])
<matplotlib.image.AxesImage object at ...>
a = np.zeros((50, 50))
a[10:-10, 10:-10] = 1
a += 0.25 * np.random.standard_normal(a.shape)
mask = a>=0.5
opened_mask = ndimage.binary_opening(mask)
closed_mask = ndimage.binary_closing(opened_mask)
Exercise
Check that the area of the reconstructed square is smaller than the area of the initial square.
(The opposite would occur if the closing step was performed before the opening).
For gray-valued images, eroding (resp. dilating) amounts to replacing a pixel by the minimal (resp. maximal)
value among pixels covered by the structuring element centered on the pixel of interest.
>>> a = np.zeros((7, 7), dtype=np.int)
>>> a[1:6, 1:6] = 3
>>> a[4, 4] = 2; a[2, 3] = 1
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
[0, 3, 3, 3, 3, 3, 0],
[0, 3, 3, 1, 3, 3, 0],
[0, 3, 3, 3, 3, 3, 0],
[0, 3, 3, 3, 2, 3, 0],
[0, 3, 3, 3, 3, 3, 0],
[0, 0, 0, 0, 0, 0, 0]])
>>> ndimage.grey_erosion(a, size=(3, 3))
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 3, 2, 2, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])
Statistical approach
The annual maxima are supposed to fit a normal probability density function. However such function is not
going to be estimated because it gives a probability from a wind speed maxima. Finding the maximum wind
speed occurring every 50 years requires the opposite approach, the result needs to be found from a defined
probability. That is the quantile function role and the exercise goal will be to find it. In the current model, it is
supposed that the maximum wind speed occurring every 50 years is defined as the upper 2% quantile.
By definition, the quantile function is the inverse of the cumulative distribution function. The latter describes
the probability distribution of an annual maxima. In the exercise, the cumulative probability p_i for a given
year i is defined as p_i = i/(N+1) with N = 21, the number of measured years. Thus it will be possible to
calculate the cumulative probability of every measured wind speed maxima. From those experimental points,
the scipy.interpolate module will be very useful for fitting the quantile function. Finally the 50 years maxima is
going to be evaluated from the cumulative probability of the 2% quantile.
Now we look for various information about the objects in the image:
>>> labels, nb = ndimage.label(mask)
>>> nb
8
>>> areas = ndimage.sum(mask, labels, range(1, labels.max()+1))
See the summary exercise on Image processing application: counting bubbles and unmolten grains for a more
advanced example.
123
124
Following the cumulative probability definition p_i from the previous section, the corresponding values will
be:
>>> cprob = (np.arange(years_nb, dtype=np.float32) + 1)/(years_nb + 1)
The quantile function is now going to be evaluated from the full range of probabilities:
>>> nprob = np.linspace(0, 1, 1e2)
>>> fitted_max_speeds = quantile_func(nprob)
In the current model, the maximum wind speed occurring every 50 years is defined as the upper 2% quantile.
As a result, the cumulative probability value will be:
>>> fifty_prob = 1. - 0.02
So the storm wind speed occurring every 50 years can be guessed by:
125
126
The first step will be to find the annual maxima by using numpy and plot them as a matplotlib bar figure.
5.11.2 Non linear least squares curve fitting: application to point extraction in
topographical lidar data
The goal of this exercise is to fit a model to some data. The data used in this tutorial are lidar data and are
described in details in the following introductory paragraph. If youre impatient and want to practice now,
please skip it and go directly to Loading and visualization.
Introduction
Lidars systems are optical rangefinders that analyze property of scattered light to measure distances. Most of
them emit a short light impulsion towards a target and record the reflected signal. This signal is then processed
to extract the distance between the lidar system and the target.
Topographical lidar systems are such systems embedded in airborne platforms. They measure distances between the platform and the Earth, so as to deliver information on the Earths topography (see 1 for more de1 Mallet, C. and Bretar, F. Full-Waveform Topographic Lidar: State-of-the-Art. ISPRS Journal of Photogrammetry and Remote Sensing
64(1), pp.1-16, January 2009 http://dx.doi.org/10.1016/j.isprsjprs.2008.09.007
127
128
tails).
In this tutorial, the goal is to analyze the waveform recorded by the lidar system 2 . Such a signal contains peaks
whose center and amplitude permit to compute the position and some characteristics of the hit target. When
the footprint of the laser beam is around 1m on the Earth surface, the beam can hit multiple targets during the
two-way propagation (for example the ground and the top of a tree or building). The sum of the contributions
of each target hit by the laser beam then produces a complex signal with multiple peaks, each one containing
information about one target.
The signal is very simple and can be modeled as a single Gaussian function and an offset corresponding to the
background noise. To fit the signal with the function, we must:
define the model
propose an initial solution
call scipy.optimize.leastsq
One state of the art method to extract information from these data is to decompose them in a sum of Gaussian
functions where each function represents the contribution of a target hit by the laser beam.
Model
Therefore, we use the scipy.optimize module to fit a waveform to one or a sum of Gaussian functions.
t 2
B + A exp
where
coeffs[0] is B (noise)
coeffs[1] is A (amplitude)
coeffs[2] is (center)
coeffs[3] is (width)
Initial solution
An approximative initial solution that we can find from looking at the graph is for instance:
>>> x0 = np.array([3, 30, 15, 1], dtype=float)
Fit
scipy.optimize.leastsq minimizes the sum of squares of the function given as an argument. Basically, the
function to minimize is the residuals (the difference between the data and the model):
>>> def residuals(coeffs, y, t):
...
return y - model(t, coeffs)
So lets get our solution by calling scipy.optimize.leastsq() with the following arguments:
the function to minimize
an initial solution
the additional arguments to pass to the function
>>> from scipy.optimize import leastsq
>>> x, flag = leastsq(residuals, x0, args=(waveform_1, t))
>>> print(x)
[ 2.70363341 27.82020742 15.47924562
3.05636228]
As you can notice, this waveform is a 80-bin-length signal with a single peak.
2 The data used for this tutorial are part of the demonstration data available for the FullAnalyze software and were kindly provided by
129
130
Remark: from scipy v0.8 and above, you should rather use scipy.optimize.curve_fit() which takes the
model and the data as arguments, so you dont need to define the residuals any more.
Going further
Try with a more complex waveform (for instance data/waveform_2.npy) that contains three significant
peaks. You must adapt the model which is now a sum of Gaussian functions instead of only one Gaussian
peak.
In some cases, writing an explicit function to compute the Jacobian is faster than letting leastsq estimate it numerically. Create a function to compute the Jacobian of the residuals and use it as an input for
leastsq.
When we want to detect very small peaks in the signal, or when the initial guess is too far from a good
solution, the result given by the algorithm is often not satisfying. Adding constraints to the parameters
of the model enables to overcome such limitations. An example of a priori knowledge we can add is the
sign of our variables (which are all positive).
With the following initial solution:
5. Display an image in which the three phases are colored with three different colors.
6. Use mathematical morphology to clean the different phases.
7. Attribute labels to all bubbles and sand grains, and remove from the sand mask grains that are smaller than
10 pixels. To do so, use ndimage.sum or np.bincount to compute the grain sizes.
8. Compute the mean size of bubbles.
Proposed solution
4. Using the histogram of the filtered image, determine thresholds that allow to define masks for sand pixels,
glass pixels and bubble pixels. Other option (homework): write a function that determines automatically the
thresholds from the minima of the histogram.
you
can
get
with
131
132
5.11.4 Example of solution for the image processing exercise: unmolten grains in
glass
1. Open the image file MV_HFV_012.jpg and display it. Browse through the keyword arguments in the
docstring of imshow to display the image with the right orientation (origin in the bottom left corner,
and not the upper left corner as for standard arrays).
4. Using the histogram of the filtered image, determine thresholds that allow to define masks for sand pixels, glass pixels and bubble pixels. Other option (homework): write a function that determines automatically the thresholds from the minima of the histogram.
2. Crop the image to remove the lower panel with measure information.
>>> dat = dat[:-60]
3. Slightly filter the image with a median filter in order to refine its histogram. Check how the histogram
changes.
>>> filtdat = ndimage.median_filter(dat, size=(7,7))
>>> hi_dat = np.histogram(dat, bins=np.arange(256))
>>> hi_filtdat = np.histogram(filtdat, bins=np.arange(256))
5. Display an image in which the three phases are colored with three different colors.
>>> phases = void.astype(np.int) + 2*glass.astype(np.int) + 3*sand.astype(np.int)
133
134
(1699.875, 65.0)
7. Attribute labels to all bubbles and sand grains, and remove from the sand mask grains that are smaller
than 10 pixels. To do so, use ndimage.sum or np.bincount to compute the grain sizes.
>>>
>>>
>>>
>>>
135
136
and you may want to read directly the documentation on the wiki instead of the official documentation
website. Note that anyone can create an account on the wiki and write better documentation; this is an
easy way to contribute to an open-source project and improve the tools you are using!
Scipy central http://central.scipy.org/ gives recipes on many common problems frequently encoun-
np.version
np.void
np.void0
np.vsplit
np.vstack
In Ipython it is not possible to open a separated window for help and documentation; however one can always open a second Ipython shell just to display help and docstrings...
Matplotlibs website http://matplotlib.org/ features a very nice gallery with a large number of plots, each
of them shows both the source code and the resulting plot. This is very useful for learning by example.
More standard documentation is also available.
Finally, two more technical possibilities are useful as well:
In Ipython, the magical function %psearch search for objects matching patterns. This is useful if, for
example, one does not know the exact name of a function.
In [3]: import numpy as np
In [4]: %psearch np.diag*
np.diag
np.diagflat
np.diagonal
If everything listed above fails (and Google doesnt have the answer)... dont despair! Write to the mailinglist suited to your problem: you should have a quick answer if you describe your problem well. Experts
on scientific python often give very enlightening explanations on the mailing-list.
Numpys and Scipys documentation is enriched and updated on a regular basis by users on a wiki
http://docs.scipy.org/doc/numpy/. As a result, some docstrings are clearer or more detailed on the wiki,
137
138
SciPy Users List (scipy-user@scipy.org): scientific computing with Python, high-level data processing, in particular with the scipy package.
matplotlib-users@lists.sourceforge.net for plotting with matplotlib.
Part II
Advanced topics
139
140
This part of the Scipy lecture notes is dedicated to advanced usage. It strives to educate the proficient Python
coder to be an expert and tackles various specific topics.
141
142
A second way in which iterator objects are created is through generator expressions, the basis for list comprehensions. To increase clarity, a generator expression must always be enclosed in parentheses or an expression.
If round parentheses are used, then a generator iterator is created. If rectangular parentheses are used, the process is short-circuited and we get a list.
>>> (i for
<generator
>>> [i for
[1, 2, 3]
>>> list(i
[1, 2, 3]
i in nums)
object <genexpr> at 0x...>
i in nums]
for i in nums)
The list comprehension syntax also extends to dictionary and set comprehensions. A set is created when the
generator expression is enclosed in curly braces. A dict is created when the generator expression contains
pairs of the form key:value:
>>> {i for i in range(3)}
set([0, 1, 2])
>>> {i:i**2 for i in range(3)}
{0: 0, 1: 1, 2: 4}
One gotcha should be mentioned: in old Pythons the index variable (i) would leak, and in versions >= 3 this is
fixed.
7.1.3 Generators
Generators
A generator is a function that produces a sequence of results instead of a single value.
David Beazley A Curious Course on Coroutines and Concurrency
call last):
1, in <module>
call last):
1, in <module>
When used in a loop, StopIteration is swallowed and causes the loop to finish. But with explicit invocation,
we can see that once the iterator is exhausted, accessing it raises an exception.
Using the for..in loop also uses the __iter__ method. This allows us to transparently start the iteration over a
sequence. But if we already have the iterator, we want to be able to use it in an for loop in the same way. In
order to achieve this, iterators in addition to next are also required to have a method called __iter__ which
returns the iterator (self).
Support for iteration is pervasive in Python: all sequences and unordered containers in the standard library
allow this. The concept is also stretched to other things: e.g. file objects support iteration over lines.
>>> f = open('/etc/fstab')
>>> f is f.__iter__()
True
The file is an iterator itself and its __iter__ method doesnt create a separate object: only a single thread of
sequential access is allowed.
143
A third way to create iterator objects is to call a generator function. A generator is a function containing the
keyword yield. It must be noted that the mere presence of this keyword completely changes the nature of the
function: this yield statement doesnt have to be invoked, or even reachable, but causes the function to be
marked as a generator. When a normal function is called, the instructions contained in the body start to be
executed. When a generator is called, the execution stops before the first instruction in the body. An invocation
of a generator function creates a generator object, adhering to the iterator protocol. As with normal function
invocations, concurrent and recursive invocations are allowed.
When next is called, the function is executed until the first yield. Each encountered yield statement gives a
value becomes the return value of next. After executing the yield statement, the execution of this function is
suspended.
>>> def f():
...
yield 1
...
yield 2
>>> f()
<generator object f at 0x...>
>>> gen = f()
>>> next(gen)
1
>>> next(gen)
2
>>> next(gen)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
144
Lets go over the life of the single invocation of the generator function.
>>> def f():
...
print("-...
yield 3
...
print("-...
yield 4
...
print("->>> gen = f()
>>> next(gen)
-- start -3
>>> next(gen)
-- middle -4
>>> next(gen)
-- finished -Traceback (most
...
StopIteration
Traceback (most
...
StopIteration
start --")
middle --")
Unlike raise (which immediately raises an exception from the current execution point), throw() first resumes
the generator, and only then raises the exception. The word throw was picked because it is suggestive of putting
the exception in another location, and is associated with exceptions in other languages.
finished --")
What happens when an exception is raised inside the generator? It can be either raised explicitly or when
executing some statements or it can be injected at the point of a yield statement by means of the throw()
method. In either case, such an exception propagates in the standard manner: it can be intercepted by an
except or finally clause, or otherwise it causes the execution of the generator function to be aborted and
propagates in the caller.
For completeness sake, its worth mentioning that generator iterators also have a close() method, which can
be used to force a generator that would otherwise be able to provide more values to finish immediately. It
allows the generator __del__ method to destroy objects holding the state of generator.
Lets define a generator which just prints what is passed in through send and throw.
Contrary to a normal function, where executing f() would immediately cause the first print to be executed,
gen is assigned without executing any statements in the function body. Only when gen.next() is invoked by
next, the statements up to the first yield are executed. The second next prints -- middle -- and execution
halts on the second yield. The third next prints -- finished -- and falls of the end of the function. Since
no yield was reached, an exception is raised.
What happens with the function after a yield, when the control passes to the caller? The state of each generator
is stored in the generator object. From the point of view of the generator function, is looks almost as if it was
running in a separate thread, but this is just an illusion: execution is strictly single-threaded, but the interpreter
keeps and restores the state in between the requests for the next value.
Why are generators useful? As noted in the parts about iterators, a generator function is just a different way to
create an iterator object. Everything that can be done with yield statements, could also be done with next
methods. Nevertheless, using a function and having the interpreter perform its magic to create an iterator
has advantages. A function can be much shorter than the definition of a class with the required next and
__iter__ methods. What is more important, it is easier for the author of the generator to understand the state
which is kept in local variables, as opposed to instance attributes, which have to be used to pass data between
consecutive invocations of next on an iterator object.
A broader question is why are iterators useful? When an iterator is used to power a loop, the loop becomes very
simple. The code to initialise the state, to decide if the loop is finished, and to find the next value is extracted
into a separate place. This highlights the body of the loop the interesting part. In addition, it is possible to
reuse the iterator code in other places.
next or __next__?
In Python 2.x, the iterator method to retrieve the next value is called next. It is invoked implicitly
through the global function next, which means that it should be called __next__. Just like the global
function iter calls __iter__. This inconsistency is corrected in Python 3.x, where it.next becomes
it.__next__. For other generator methods send and throw the situation is more complicated,
because they are not called implicitly by the interpreter. Nevertheless, theres a proposed syntax extension to allow continue to take an argument which will be passed to send of the loops iterator. If this
extension is accepted, its likely that gen.send will become gen.__send__. The last of generator methods, close, is pretty obviously named incorrectly, because it is already invoked implicitly.
The second of the new methods is throw(type, value=None, traceback=None) which is equivalent to:
145
146
name of the decorated function doubling as a temporary variable must be used at least three times, which is
prone to errors. Nevertheless, the example above is equivalent to:
This is a preview of PEP 380 (not yet implemented, but accepted for Python 3.3).
Lets say we are writing a generator and we want to yield a number of values generated by a second generator,
a subgenerator. If yielding of values is the only concern, this can be performed without much difficulty using
a loop such as
subgen = some_other_generator()
for v in subgen:
yield v
However, if the subgenerator is to interact properly with the caller in the case of calls to send(), throw()
and close(), things become considerably more difficult. The yield statement has to be guarded by a
try..except..finally structure similar to the one defined in the previous section to debug the generator function. Such code is provided in PEP 380, here it suffices to say that new syntax to properly yield from a subgenerator is being introduced in Python 3.3:
yield from some_other_generator()
This behaves like the explicit loop above, repeatedly yielding values from some_other_generator until it is
exhausted, but also forwards send, throw and close to the subgenerator.
7.2 Decorators
Summary
This amazing feature appeared in the language almost apologetically and with concern that it might not
be that useful.
Bruce Eckel An Introduction to Python Decorators
def function():
pass
function = decorator(function)
#
#
Decorators can be stacked the order of application is bottom-to-top, or inside-out. The semantics are such
that the originally defined function is used as an argument for the first decorator, whatever is returned by
the first decorator is used as an argument for the second decorator, ..., and whatever is returned by the last
decorator is attached under the name of the original function.
The decorator syntax was chosen for its readability. Since the decorator is specified before the header of the
function, it is obvious that its is not a part of the function body and its clear that it can only operate on the
whole function. Because the expression is prefixed with @ is stands out and is hard to miss (in your face,
according to the PEP :) ). When more than one decorator is applied, each one is placed on a separate line in an
easy to read way.
Since a function or a class are objects, they can be passed around. Since they are mutable objects, they can be
modified. The act of altering a function or class object after it has been constructed but before is is bound to
its name is called decorating.
There are two things hiding behind the name decorator one is the function which does the work of decorating, i.e. performs the real work, and the other one is the expression adhering to the decorator syntax, i.e. an
at-symbol and the name of the decorating function.
The only requirement on decorators is that they can be called with a single argument. This means that decorators can be implemented as normal functions, or as classes with a __call__ method, or in theory, even as
lambda functions.
Lets compare the function and class approaches. The decorator expression (the part after @) can be either just
a name, or a call. The bare-name approach is nice (less to type, looks cleaner, etc.), but is only possible when
no arguments are needed to customise the decorator. Decorators written as functions can be used in those
two cases:
#
#
Before the decorator syntax was implemented (PEP 318), it was possible to achieve the same effect by assigning the function or class object to a temporary variable and then invoking the decorator explicitly and then
assigning the return value to the name of the function. This sounds like more typing, and it is, and also the
7.2. Decorators
7.2. Decorators
147
148
Contrary to normal rules (PEP 8) decorators written as classes behave more like functions and therefore their
name often starts with a lowercase letter.
...
return _decorator
>>> @decorator_with_arguments("abc")
... def function():
...
print("inside function")
defining the decorator
doing decoration, 'abc'
>>> function()
inside function
In reality, it doesnt make much sense to create a new class just to have a decorator which returns the original
function. Objects are supposed to hold state, and such decorators are more useful when the decorator returns
a new object.
The two trivial decorators above fall into the category of decorators which return the original function. If they
were to return a new function, an extra level of nestedness would be required. In the worst case, three levels of
nested functions.
>>> def replacing_decorator_with_args(arg):
...
print("defining the decorator")
...
def _decorator(function):
...
# in this inner function, arg is available too
...
print("doing decoration, %r " % arg)
...
def _wrapper(*args, **kwargs):
...
print("inside wrapper, %r %r " % (args, kwargs))
...
return function(*args, **kwargs)
...
return _wrapper
...
return _decorator
>>> @replacing_decorator_with_args("abc")
... def function(*args, **kwargs):
...
print("inside function, %r %r " % (args, kwargs))
...
return 14
defining the decorator
doing decoration, 'abc'
>>> function(11, 12)
inside wrapper, (11, 12) {}
inside function, (11, 12) {}
14
A decorator like this can do pretty much anything, since it can modify the original function object and mangle
the arguments, call the original function or not, and afterwards mangle the return value.
The _wrapper function is defined to accept all positional and keyword arguments. In general we cannot know
what arguments the decorated function is supposed to accept, so the wrapper function just passes everything
to the wrapped function. One unfortunate consequence is that the apparent argument list is misleading.
Compared to decorators defined as functions, complex decorators defined as classes are simpler. When an
object is created, the __init__ method is only allowed to return None, and the type of the created object
cannot be changed. This means that when a decorator is defined as a class, it doesnt make much sense to use
the argument-less form: the final decorated object would just be an instance of the decorating class, returned
by the constructor call, which is not very useful. Therefore its enough to discuss class-based decorators where
arguments are given in the decorator expression and the decorator __init__ method is used for decorator
construction.
7.2.3 Copying the docstring and other attributes of the original function
When a new function is returned by the decorator to replace the original function, an unfortunate consequence is that the original function name, the original docstring, the original argument list are lost. Those
attributes of the original function can partially be transplanted to the new function by setting __doc__ (the
docstring), __module__ and __name__ (the full name of the function), and __annotations__ (extra information about arguments and the return value of the function available in Python 3). This can be done automatically by using functools.update_wrapper.
7.2. Decorators
149
7.2. Decorators
150
staticmethod is applied to methods to make them static, i.e. basically a normal function, but accessible through the class namespace. This can be useful when the function is only needed inside this class
(its name would then be prefixed with _), or when we want the user to think of the method as connected
to the class, despite an implementation which doesnt require this.
functools.update_wrapper(wrapper, wrapped)
Update a wrapper function to look like the wrapped function.
>>> import functools
>>> def replacing_decorator_with_args(arg):
...
print("defining the decorator")
...
def _decorator(function):
...
print("doing decoration, %r " % arg)
...
def _wrapper(*args, **kwargs):
...
print("inside wrapper, %r %r " % (args, kwargs))
...
return function(*args, **kwargs)
...
return functools.update_wrapper(_wrapper, function)
...
return _decorator
>>> @replacing_decorator_with_args("abc")
... def function():
...
"extensive documentation"
...
print("inside function")
...
return 14
defining the decorator
doing decoration, 'abc'
>>> function
<function function at 0x...>
>>> print(function.__doc__)
extensive documentation
property is the pythonic answer to the problem of getters and setters. A method decorated with
property becomes a getter which is automatically called on attribute access.
>>> class A(object):
...
@property
...
def a(self):
...
"an important attribute"
...
return "a value"
>>> A.a
<property object at 0x...>
>>> A().a
'a value'
In this example, A.a is an read-only attribute. It is also documented: help(A) includes the docstring for
attribute a taken from the getter method. Defining a as a property allows it to be a calculated on the fly,
and has the side effect of making it read-only, because no setter is defined.
To have a setter and a getter, two methods are required, obviously. Since Python 2.6 the following syntax
is preferred:
One important thing is missing from the list of attributes which can be copied to the replacement function: the argument list. The default values for arguments can be modified through the __defaults__,
__kwdefaults__ attributes, but unfortunately the argument list itself cannot be set as an attribute. This
means that help(function) will display a useless argument list which will be confusing for the user of the
function. An effective but ugly way around this problem is to create the wrapper dynamically, using eval. This
can be automated by using the external decorator module. It provides support for the decorator decorator,
which takes a wrapper and turns it into a decorator which preserves the function signature.
To sum things up, decorators should always use functools.update_wrapper or some other means of copying function attributes.
class Rectangle(object):
def __init__(self, edge):
self.edge = edge
@property
def area(self):
"""Computed area.
Setting this updates the edge length to the proper value.
"""
return self.edge**2
@area.setter
def area(self, area):
self.edge = area ** 0.5
The way that this works, is that the property decorator replaces the getter method with a property
object. This object in turn has three methods, getter, setter, and deleter, which can be used as
decorators. Their job is to set the getter, setter and deleter of the property object (stored as attributes
fget, fset, and fdel). The getter can be set like in the example above, when creating the object. When
defining the setter, we already have the property object under area, and we add the setter to it by using
the setter method. All this happens when we are creating the class.
Afterwards, when an instance of the class has been created, the property object is special. When the
interpreter executes attribute access, assignment, or deletion, the job is delegated to the methods of the
property object.
To make everything crystal clear, lets define a debug example:
>>> class D(object):
...
@property
...
def a(self):
...
print("getting 1")
...
return 1
...
@a.setter
...
def a(self, value):
...
print("setting %r " % value)
...
@a.deleter
...
def a(self):
@classmethod
def fromfile(cls, file):
data = numpy.load(file)
return cls(data)
7.2. Decorators
151
7.2. Decorators
152
...
print("deleting")
>>> D.a
<property object at 0x...>
>>> D.a.fget
<function ...>
>>> D.a.fset
<function ...>
>>> D.a.fdel
<function ...>
>>> d = D()
# ... varies, this is not the same `a` function
>>> d.a
getting 1
1
>>> d.a = 2
setting 2
>>> del d.a
deleting
>>> d.a
getting 1
1
Properties are a bit of a stretch for the decorator syntax. One of the premises of the decorator syntax
that the name is not duplicated is violated, but nothing better has been invented so far. It is just good
style to use the same name for the getter, setter, and deleter methods.
Some newer examples include:
functools.lru_cache memoizes an arbitrary function maintaining a limited cache of arguments:answer pairs (Python 3.2)
functools.total_ordering is a class decorator which fills in missing ordering methods (__lt__,
__gt__, __le__, ...) based on a single available one (Python 2.7).
Lets say we want to print a deprecation warning on stderr on the first invocation of a function we dont like
anymore. If we dont want to modify the function, we can use a decorator:
class deprecated(object):
"""Print a deprecation warning once on first use of the function.
This is fine, as long as the body of the loop is fairly compact. Once it becomes more complicated, as often
happens in real code, this becomes pretty unreadable. We could simplify this by using yield statements, but
then the user would have to explicitly call list(find_answers()).
def vectorized(generator_func):
def wrapper(*args, **kwargs):
return list(generator_func(*args, **kwargs))
return functools.update_wrapper(wrapper, generator_func)
>>> @deprecated()
# doctest: +SKIP
... def f():
...
pass
>>> f()
# doctest: +SKIP
f is deprecated
"""
def __call__(self, func):
self.func = func
self.count = 0
return self._wrapper
def _wrapper(self, *args, **kwargs):
self.count += 1
if self.count == 1:
print self.func.__name__, 'is deprecated'
return self.func(*args, **kwargs)
7.2. Decorators
def find_answers():
answers = []
while True:
ans = look_for_next_answer()
if ans is None:
break
answers.append(ans)
return answers
>>> @deprecated
# doctest: +SKIP
153
7.2. Decorators
154
exception is passed to __exit__, which is described below in the next subsection. In the normal case,
exceptions can be ignored, just like in a finally clause, and will be rethrown after __exit__ is finished.
@classmethod
def plugin(cls, plugin):
cls.PLUGINS.append(plugin)
Lets say we want to make sure that a file is closed immediately after we are done writing to it:
@WordProcessor.plugin
class CleanMdashesExtension(object):
def cleanup(self, text):
return text.replace('—', u'\N{em dash}')
Here we use a decorator to decentralise the registration of plugins. We call our decorator with a noun, instead
of a verb, because we use it to declare that our class is a plugin for WordProcessor. Method plugin simply
appends the class to the list of plugins.
A word about the plugin itself: it replaces HTML entity for em-dash with a real Unicode em-dash character.
It exploits the unicode literal notation to insert a character by using its name in the unicode database (EM
DASH). If the Unicode character was inserted directly, it would be impossible to distinguish it from an endash in the source of a program.
See also:
Here we have made sure that the f.close() is called when the with block is exited. Since closing files is such
a common operation, the support for this is already present in the file class. It has an __exit__ method
which calls close and can be used as a context manager itself:
>>> with open('/tmp/file', 'a') as f:
...
f.write('more contents\n')
The common use for try..finally is releasing resources. Various different cases are implemented similarly:
in the __enter__ phase the resource is acquired, in the __exit__ phase it is released, and the exception, if
thrown, is propagated. As with files, theres often a natural operation to perform after the object has been used
and it is most convenient to have the support built in. With each release, Python provides support in more
places:
http://pypi.python.org/pypi/decorator
Bruce Eckel
locks
multiprocessing.RLock lock and unlock
multiprocessing.Semaphore
A context manager is an object with __enter__ and __exit__ methods which can be used in the with statement:
with manager as var:
do_something(var)
var = manager.__enter__()
try:
do_something(var)
finally:
manager.__exit__()
parallel programming
concurrent.futures.ThreadPoolExecutor invoke in parallel then kill thread pool (py >= 3.2)
concurrent.futures.ProcessPoolExecutor invoke in parallel then kill process pool (py >=
3.2)
In other words, the context manager protocol defined in PEP 343 permits the extraction of the boring part of a
try..except..finally structure into a separate class leaving only the interesting do_something block.
1. The __enter__ method is called first. It can return a value which will be assigned to var. The as-part is
optional: if it isnt present, the value returned by __enter__ is simply ignored.
2. The block of code underneath with is executed. Just like with try clauses, it can either execute successfully to the end, or it can break, continue or return, or it can throw an exception. Either way, after the
block is finished, the __exit__ method is called. If an exception was thrown, the information about the
When an exception is thrown in the with-block, it is passed as arguments to __exit__. Three arguments are
used, the same as returned by sys.exc_info(): type, value, traceback. When no exception is thrown, None is
used for all three arguments. The context manager can swallow the exception by returning a true value from
155
156
__exit__. Exceptions can be easily ignored, because if __exit__ doesnt use return and just falls of the end,
None is returned, a false value, and therefore the exception is rethrown after __exit__ is finished.
The ability to catch exceptions opens interesting possibilities. A classic example comes from unit-tests we
want to make sure that some code throws the right kind of exception:
class assert_raises(object):
# based on pytest and unittest.TestCase
def __init__(self, type):
self.type = type
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
if type is None:
raise AssertionError('exception expected')
if issubclass(type, self.type):
return True # swallow the expected exception
raise AssertionError('wrong exception type')
return
except Exception as value:
raise AssertionError('wrong exception type')
else:
raise AssertionError('exception expected')
with assert_raises(KeyError):
{}['foo']
The contextlib.contextmanager helper takes a generator and turns it into a context manager. The generator has to obey some rules which are enforced by the wrapper function most importantly it must yield
exactly once. The part before the yield is executed from __enter__, the block of code protected by the context manager is executed when the generator is suspended in yield, and the rest is executed in __exit__. If
an exception is thrown, the interpreter hands it to the wrapper through __exit__ arguments, and the wrapper function then throws it at the point of the yield statement. Through the use of generators, the context
manager is shorter and simpler.
Lets rewrite the closing example as a generator:
@contextlib.contextmanager
def closing(obj):
try:
yield obj
finally:
obj.close()
157
158
8
Chapter contents
Advanced Numpy
Life of ndarray
Its...
Block of memory
Data types
Indexing scheme: strides
Findings in dissection
Universal functions
What they are?
Exercise: building an ufunc from scratch
Solution: building an ufunc from scratch
Generalized ufuncs
Interoperability features
Sharing multidimensional, typed data
The old buffer protocol
The old buffer protocol
Array interface protocol
Array siblings: chararray, maskedarray, matrix
chararray: vectorized string operations
masked_array missing data
recarray: purely convenience
matrix: convenience?
Summary
Contributing to Numpy/Scipy
Why
Reporting bugs
Contributing to documentation
Contributing features
How to help, in general
In this section, numpy will be imported as follows:
>>> import numpy as np
159
160
>>> x[0] = 9
>>> y
array([9, 2, 3])
x is a string (in Python 3 a bytes), we can represent its data as an array of ints:
>>> y = np.frombuffer(x, dtype=np.int8)
>>> y.data
<... at ...>
>>> y.base is x
True
typedef struct PyArrayObject {
PyObject_HEAD
>>> y.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : False
WRITEABLE : False
ALIGNED : True
UPDATEIFCOPY : False
/* Block of memory */
char *data;
/* Data type descriptor */
PyArray_Descr *descr;
The owndata and writeable flags indicate status of the memory block.
/* Indexing scheme */
int nd;
npy_intp *dimensions;
npy_intp *strides;
/* Other stuff */
PyObject *base;
int flags;
PyObject *weakreflist;
} PyArrayObject;
itemsize
byteorder
fields
shape
>>> np.dtype(int).type
<type 'numpy.int64'>
>>> np.dtype(int).itemsize
8
>>> np.dtype(int).byteorder
'='
>>> x.__array_interface__
{'data': (35828928, False),
'descr': [('', '<i4')],
'shape': (4,),
'strides': None,
'typestr': '<i4',
'version': 3}
161
162
chunk_id
chunk_size
format
fmt_id
fmt_size
audio_fmt
num_channels
sample_rate
byte_rate
block_align
bits_per_sample
data_id
data_size
"RIFF"
4-byte unsigned little-endian integer
Exercise
"WAVE"
"fmt "
Mini-exercise, make a sparse dtype by using offsets, and only some of the fields:
and use that to read the sample rate, and data_id (as sub-array).
"data"
See also:
on assignment
wavreader.py
on array construction
>>> wav_header_dtype['format']
dtype('S4')
on arithmetic
>>> wav_header_dtype.fields
etc.
dict_proxy({'block_align': (dtype('uint16'), 32), 'format': (dtype('S4'), 8), 'data_id': (dtype(('S1', (2, 2))), 36), 'fmt_id': (dtype('S4'),
12), 'byte_rate': (dtype('uint32'), 28), 'chunk_id': (dtype('S4'), 0), 'num_channels': (dtype('u
>>> wav_header_dtype.fields['format']
and manually: .astype(dtype)
(dtype('S4'), 8)
data re-interpretation
The first element is the sub-dtype in the structured data, corresponding to the name format
manually: .view(dtype)
The second one is its offset (in bytes) from the beginning of the item
Casting
163
164
.view() makes views, does not copy (or alter) the memory block
only changes the dtype (and adjusts array shape):
>>> x[1] = 5
>>> y
array([328193], dtype=int32)
>>> y.base is x
True
Mini-exercise: data re-interpretation
See also:
view-colors.py
>>>
>>>
>>>
>>>
>>>
How to make a (10, 10) structured array with field names r, g, b, a without copying data?
>>> y = ...
0x02
where the last three dimensions are the R, B, and G, and alpha channels.
Re-interpretation / viewing
0x01
||
0x03
||
0x04
>>>
>>>
>>>
>>>
4 of uint8, OR,
4 of int8, OR,
2 of int16, OR,
assert
assert
assert
assert
(y['r']
(y['g']
(y['b']
(y['a']
==
==
==
==
1).all()
2).all()
3).all()
4).all()
Solution
1 of int32, OR,
1 of float32, OR,
...
How to switch from one to another?
1. Switch the dtype:
>>> x = np.array([1, 2, 3, 4], dtype=np.uint8)
>>> x.dtype = "<i2"
>>> x
array([ 513, 1027], dtype=int16)
>>> 0x0201, 0x0403
(513, 1027)
0x01
0x02
||
0x03
0x04
0x01
0x02
0x03
0x04
165
166
>>> str(x.data)
'\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x06\x00'
What happened?
... we need to look into what x[0,1] actually means
shape = (d 1 , d 2 , ..., d n )
strides = (s 1 , s 2 , ..., s n )
s Cj = d j +1 d j +2 ...d n itemsize
s Fj = d 1 d 2 ...d j 1 itemsize
Main point
The question:
Transposition does not affect the memory layout of the data, only strides
>>>
(2,
>>>
(1,
>>> str(x.data)
'\x01\x02\x03\x04'
>>> str(y.data)
'\x01\x03\x02\x04'
x.strides
1)
byte_offset = 3*1 + 1*2
x.flat[byte_offset]
x.strides
1)
y.strides
2)
# to find x[1, 2]
x[1, 2]
Everything can be represented by changing only shape, strides, and possibly adjusting the data
pointer!
- simple, **flexible**
167
168
>>> y = x[2:]
>>> y.__array_interface__['data'][0] - x.__array_interface__['data'][0]
8
Spoiler
But: not all reshaping operations can be represented by playing with strides:
>>>
>>>
>>>
(1,
a = np.arange(6, dtype=np.int8).reshape(3, 2)
b = a.T
b.strides
2)
Broadcasting
Doing something useful with it: outer product of [1, 2, 3, 4] and [5, 6, 7]
>>> str(a.data)
'\x00\x01\x02\x03\x04\x05'
>>> b
array([[0, 2, 4],
[1, 3, 5]], dtype=int8)
>>> c = b.reshape(3*2)
>>> c
array([0, 2, 4, 1, 3, 5], dtype=int8)
Here, there is no way to represent the array c given one stride and the block of memory for a. Therefore, the
reshape operation needs to make a copy here.
Stride manipulation
>>> from numpy.lib.stride_tricks import as_strided
>>> help(as_strided)
as_strided(x, shape=None, strides=None)
Make an ndarray from the given array with the given shape and strides
B
y2
5, 10, 15, 20],
6, 12, 18, 24],
7, 14, 21, 28]], dtype=int16)
as_strided does not check that you stay inside the memory block bounds...
See also:
stride-fakedims.py
Exercise
See also:
169
170
stride-diagonals.py
Challenge
Pick diagonal entries of the matrix: (assume C memory order):
>>> x = np.array([[1, 2, 3],
...
[4, 5, 6],
...
[7, 8, 9]], dtype=np.int32)
In [1]: x = np.zeros((20000,))
In [2]: y = np.zeros((20000*67,))[::67]
(Hint to the last two: slicing first moves the point where striding starts from.)
Solution
Pick diagonals:
>>> x_diag = as_strided(x, shape=(3, ), strides=((3+1)*x.itemsize, ))
>>> x_diag
array([1, 5, 9], dtype=int32)
Using np.diag
>>> y = np.diag(x, k=1)
>>> y
array([2, 6], dtype=int32)
However,
>>> y.flags.owndata
False
Note This behavior has changed: before numpy 1.9, np.diag would make a copy.
If many array items consecutively operated on fit in a single block (small stride):
See also:
stride-diagonals.py
faster
Challenge
See also:
>>> x = np.arange(5*5*5*5).reshape(5, 5, 5, 5)
>>> s = 0
>>> for i in range(5):
...
for j in range(5):
...
s += x[j, i, j, i]
>>> a -= b
Solution
171
172
1. Provided by user
void ufunc_loop(void **args, int *dimensions, int *steps, void *data)
{
/*
* int8 output = elementwise_function(int8 input_1, int8 input_2)
*
* This function must compute the ufunc for many values at once,
* in the way shown below.
*/
char *input_1 = (char*)args[0];
char *input_2 = (char*)args[1];
char *output = (char*)args[2];
int i;
Making it easier
3. ufunc_loop is of very generic form, and Numpy provides pre-made ones
PyUfunc_f_f
PyUfunc_ff_f
PyUfunc_d_d
PyUfunc_dd_d
PyUfunc_D_D
PyUfunc_DD_D
Examples:
np.add, np.subtract, scipy.special.*, ...
173
174
#
# TODO: write the Mandelbrot iteration for one point here,
#
as you would write it in Python.
#
#
Say, use 100 as the maximum number of iterations, and 1000
#
as the cutoff for z.real**2 + z.imag**2.
#
where c = x + i y is a complex number. This iteration is repeated if z stays finite no matter how long the
iteration runs, c belongs to the Mandelbrot set.
Make ufunc called mandel(z0, c) that computes:
z = z0
for k in range(iterations):
z = z*z + c
say, 100 iterations or until z.real**2 + z.imag**2 > 1000. Use it to determine which c are in the
Mandelbrot set.
Write it in Cython
See also:
mandel.pyx, mandelplot.py
#
# Fix the parts marked by TODO
#
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
The litany below is particularly long, but you don't really need to
read this part; it just pulls in stuff from the Numpy C headers.
----------------------------------------------------------
#
# Compile this file by (Cython >= 0.12 required because of the complex vars)
#
#
cython mandel.pyx
#
python setup.py build_ext -i
#
# and try it out with, in this directory,
#
#
>>> import mandel
#
>>> mandel.mandel(0, 1 + 2j)
#
#
#
#
#
#
#
#
#
#
#
#
#
#
import_array()
175
176
import_ufunc()
# The actual ufunc declaration
# ---------------------------cdef PyUFuncGenericFunction loop_func[1]
cdef char input_output_types[3]
cdef void *elementwise_funcs[1]
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
Type codes:
=======================================================
``float elementwise_func(float input_1)``
``float elementwise_func(float input_1, float input_2)``
``double elementwise_func(double input_1)``
``double elementwise_func(double input_1, double input_2)``
``elementwise_func(complex_double *input, complex_double* complex_double)``
``elementwise_func(complex_double *in1, complex_double *in2, complex_double* out)``
=======================================================
#
#
#
#
#
#
#
#
#
#
#
#
#
mandel = PyUFunc_FromFuncAndData(
loop_func,
elementwise_funcs,
input_output_types,
1, # number of supported input types
TODO, # number of input args
TODO, # number of output args
0, # `identity` element, never mind this
"mandel", # function name
"mandel(z, c) -> computes z*z + c", # docstring
0 # unused
)
# Straightforward iteration
for k in range(100):
z = z*z + c
if z.real**2 + z.imag**2 > 1000:
break
# Return the answer for this point
z_out[0] = z
177
178
c = x[None,:] + 1j*y[:,None]
z = mandel.mandel(c, c)
import matplotlib.pyplot as plt
plt.imshow(abs(z)**2 < 1000, extent=[-1.7, 0.6, -1.4, 1.4])
plt.gray()
plt.show()
loop_func[0] = PyUFunc_DD_D
input_output_types[0] = NPY_CDOUBLE
input_output_types[1] = NPY_CDOUBLE
input_output_types[2] = NPY_CDOUBLE
elementwise_funcs[0] = <void*>mandel_single_point
mandel = PyUFunc_FromFuncAndData(
loop_func,
elementwise_funcs,
input_output_types,
1, # number of supported input types
2, # number of input args
1, # number of output args
0, # `identity` element, never mind this
"mandel", # function name
"mandel(z, c) -> computes iterated z*z + c", # docstring
0 # unused
)
"""
Plot Mandelbrot
================
"""
loop_funcs[1] = PyUFunc_FF_F
input_output_types[3] = NPY_CFLOAT
input_output_types[4] = NPY_CFLOAT
input_output_types[5] = NPY_CFLOAT
elementwise_funcs[1] = <void*>mandel_single_point_singleprec
import numpy as np
import mandel
x = np.linspace(-1.7, 0.6, 1000)
y = np.linspace(-1.4, 1.4, 1000)
mandel = PyUFunc_FromFuncAndData(
loop_func,
elementwise_funcs,
input_output_types,
179
180
output = elementwise_function(input)
Both output and input can be a single array element only.
int i;
generalized ufunc
i.e.
scalar
(n, n) -> ()
Matrix product:
input_1 shape = (m, n)
input_2 shape = (n, p)
output shape = (m, p)
input_1 += steps[0];
input_2 += steps[1];
output += steps[2];
Status in Numpy
Suppose you
1. Write a library than handles (multidimensional) binary data,
2. Want to make it easy to manipulate the data with Numpy, or whatever other library,
... but we dont ship with public g-ufuncs, except for testing, ATM
Currently, 3 solutions:
the last two dimensions became core dimensions, and are modified as per the signature
matrix multiplication this way could be useful for operating on many small matrices at once
181
182
Q:
Check what happens if data is now modified, and img saved again.
Multidimensional buffers
#
# Modify the original data, and save again.
#
# It turns out that PIL, which knows next to nothing about Numpy,
# happily shares the same data.
#
x[:,:,1] = 254
img.save('test2.png')
::
183
184
True False],
>>> mx[1] = 9
>>> mx
masked_array(data = [1 9 3 -- 5],
mask = [False False False
fill_value = 999999)
True False],
>>> mx.mask
array([False, False, False,
The masked entries can be filled with a given value to get an usual array back:
>>> x2 = mx.filled(-1)
>>> x2
array([ 1, 9, 3, -1,
.view() has a second meaning: it can make an ndarray an instance of a specialized ndarray subclass
5])
Domain-aware functions
Streamlined and more seamless support for dealing with missing data in arrays is making its way into Numpy
1.7. Stay tuned!
>>> mx.mean()
2.75
>>> np.mean(mx)
2.75
B Not all Numpy functions respect masks, for instance np.dot, so check the return types.
3, -99,
5])
185
186
>>> arr = np.array([('a', 1), ('b', 2)], dtype=[('x', 'S1'), ('y', int)])
>>> arr2 = arr.view(np.recarray)
>>> arr2.x
chararray(['a', 'b'],
dtype='|S1')
>>> arr2.y
array([1, 2])
>>> populations.mean(axis=0)
masked_array(data = [40472.72727272727 18627.272727272728 42400.0],
mask = [False False False],
fill_value = 1e+20)
>>> populations.std(axis=0)
masked_array(data = [21087.656489006717 15625.799814240254 3322.5062255844787],
mask = [False False False],
fill_value = 1e+20)
8.5 Summary
80000
70000
60000
50000
8.6.1 Why
40000
Theres a bug?
30000
20000
10000
0
1900
1905
1910
1915
http://projects.scipy.org/numpy
1920
http://projects.scipy.org/scipy
Click the Register link to get an account
Mailing lists ( scipy.org/Mailing_Lists )
If youre unsure
187
8.5. Summary
188
To: scipy-dev@scipy.org
Hi,
>>> np.random.permutation(12)
array([ 6, 11, 4, 10, 2, 8, 1, 7, 9, 3, 0, 5])
>>> np.random.permutation(12.)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mtrand.pyx", line 3311, in mtrand.RandomState.permutation
File "mtrand.pyx", line 3254, in mtrand.RandomState.shuffle
TypeError: len() of unsized object
Edit
2. Edit sources and send patches (as for bugs)
I'm using Numpy 1.4.1, built from the official tarball, on Windows
64 with Visual studio 2008, on Python.org 64-bit Python.
http://projects.scipy.org/numpy/wiki/GitMirror
http://www.spheredev.org/wiki/Git_for_the_lazy
3. Version of Numpy/Scipy
>>> print(np.__version__)
1...
>>> print(np.__file__)
/...
svn/trunk
<edit stuff>
git commit -a
1. Documentation editor
http://docs.scipy.org/doc/numpy
Registration
Register an account
Subscribe to scipy-dev mailing list (subscribers-only)
189
190
CHAPTER
Debugging code
http://scipy.org/Developer_Zone/UG_Toc
This section explores tools to understand better your code base: debugging, to find and fix bugs.
It is not specific to the scientific Python community, but the strategies that we will employ are tailored to its
needs.
numpy-discussion list
scipy-dev list
Prerequisites
Numpy
IPython
nosetests (http://readthedocs.org/docs/nose/en/latest/)
pyflakes (http://pypi.python.org/pypi/pyflakes)
gdb for the C-debugging part.
Chapter contents
Avoiding bugs
Coding best practices to avoid getting in trouble
pyflakes: fast static analysis
Debugging workflow
Using the Python debugger
Invoking the debugger
Debugger commands and interaction
Debugging segmentation faults using gdb
191
192
pychecker
pyflakes
pep8
flake8
In vim
Fast, simple
Another good recommendation is the flake8 tool which is a combination of pyflakes and pep8. Thus, in
addition to the types of errors that pyflakes catches, flake8 detects violations of the recommendation in PEP8
style guide.
Integrating pyflakes (or flake8) in your editor or IDE is highly recommended, it does yield productivity gains.
In TextMate
Menu: TextMate -> Preferences -> Advanced -> Shell variables, add a shell variable:
TM_PYCHECKER = /Library/Frameworks/Python.framework/Versions/Current/bin/pyflakes
FileType
FileType
FileType
FileType
on
193
194
(file-name-directory buffer-file-name))))
(list "pyflakes" (list local-file))))
(add-to-list 'flymake-allowed-file-name-masks
'("\\.py\\'" flymake-pyflakes-init)))
Postmortem
If you do have a non trivial bug, this is when debugging strategies kick in. There is no silver bullet. Yet, strategies
help:
For debugging a given problem, the favorable situation is when the problem is isolated in a
small number of lines of code, outside framework or application code, with short modify-runfail cycles
1. Make it fail reliably. Find a test case that makes the code fail every time.
2. Divide and Conquer. Once you have a failing test case, isolate the failing code.
Which module.
Which function.
/home/varoquau/dev/scipy-lecture-notes/advanced/debugging/index_error.py in index_error()
3 def index_error():
4
lst = list('foobar')
----> 5
print lst[len(lst)]
6
7 if __name__ == '__main__':
Once you have gone through this process: isolated a tight piece of code reproducing the bug and fix the bug
using this piece of code, add the corresponding code to your test suite.
ipdb> list
1 """Small snippet to raise an IndexError."""
2
3 def index_error():
4
lst = list('foobar')
----> 5
print lst[len(lst)]
6
7 if __name__ == '__main__':
8
index_error()
9
ipdb> len(lst)
6
ipdb> print lst[len(lst)-1]
r
ipdb> quit
Set breakpoints.
print
Yes, print statements do work as a debugging tool. However to inspect runtime, it is often more efficient
to use the debugger.
In [2]: %debug
> /home/varoquau/dev/scipy-lecture-notes/advanced/debugging/index_error.py(5)index_error()
4
lst = list('foobar')
----> 5
print lst[len(lst)]
6
195
In [3]:
196
2--> 34
35
Step-by-step execution
Situation: You believe a bug exists in a module but are not sure where.
For instance we are trying to debug wiener_filtering.py. Indeed the code runs, but the filtering does not
work well.
noisy_img = noisy_img
denoised_img = local_mean(noisy_img, size=size)
Step into code with n(ext) and s(tep): next jumps to the next statement in the current execution
context, while step will go across execution contexts, i.e. enable exploring inside function calls:
ipdb> s
> /home/varoquau/dev/scipy-lecture-notes/advanced/optimizing/wiener_filtering.py(35)iterated_wiener()
2
34
noisy_img = noisy_img
---> 35
denoised_img = local_mean(noisy_img, size=size)
36
l_var = local_var(noisy_img, size=size)
ipdb> n
> /home/varoquau/dev/scipy-lecture-notes/advanced/optimizing/wiener_filtering.py(36)iterated_wiener()
35
denoised_img = local_mean(noisy_img, size=size)
---> 36
l_var = local_var(noisy_img, size=size)
37
for i in range(3):
Oh dear, nothing but integers, and 0 variation. Here is our bug, we are doing integer arithmetic.
Run the script in IPython with the debugger using %run -d wiener_filtering.p :
In [1]: %run -d wiener_filtering.py
*** Blank or comment
*** Blank or comment
*** Blank or comment
Breakpoint 1 at /home/varoquau/dev/scipy-lecture-notes/advanced/optimizing/wiener_filtering.py:4
NOTE: Enter 'c' at the ipdb> prompt to start your script.
> <string>(1)<module>()
197
198
When we run the wiener_filtering.py file, the following warnings are raised:
For stepping through code and inspecting variables, you might find it more convenient to use a
graphical debugger such as winpdb.
Alternatively, pudb is a good semi-graphical debugger with a text user interface in the console.
Also, the pydbgr project is probably worth looking at.
We can turn these warnings in exception, which enables us to do post-mortem debugging on them, and
find our problem more quickly:
In [3]: np.seterr(all='raise')
Out[3]: {'divide': 'print', 'invalid': 'print', 'over': 'print', 'under': 'ignore'}
In [4]: %run wiener_filtering.py
--------------------------------------------------------------------------FloatingPointError
Traceback (most recent call last)
/home/esc/anaconda/lib/python2.7/site-packages/IPython/utils/py3compat.pyc in execfile(fname, *where)
176
else:
177
filename = fname
--> 178
__builtin__.execfile(filename, *where)
/home/esc/physique-cuso-python-2013/scipy-lecture-notes/advanced/debugging/wiener_filtering.py in <module>()
55 pl.matshow(noisy_face[cut], cmap=pl.cm.gray)
56
---> 57 denoised_face = iterated_wiener(noisy_face)
58 pl.matshow(denoised_face[cut], cmap=pl.cm.gray)
59
You cannot name the variables the way you want. For instance, if in you cannot override the variables in the
current frame with the same name: use different names than your local variable when typing code in the
debugger.
pdef
pdoc
pinfo
pp
q
quit
r
restart
return
run
s
step
tbreak
u
unalias
unt
until
up
w
whatis
where
199
If you have a segmentation fault, you cannot debug it with pdb, as it crashes the Python interpreter before it
can drop in the debugger. Similarly, if you have a bug in C code embedded in Python, pdb is useless. For this
we turn to the gnu debugger, gdb, available on Linux.
Before we start with gdb, let us add a few Python-specific tools to it. For this we add a few macros to our
~/.gbdinit. The optimal choice of macro depends on your Python version and your gdb version. I have
added a simplified version in gdbinit, but feel free to read DebuggingWithGdb.
200
To debug with gdb the Python script segfault.py, we can run the script in gdb as follows
def make_big_array(small_array):
big_array = stride_tricks.as_strided(small_array,
shape=(2e6, 2e6), strides=(32, 32))
return big_array
$ gdb python
...
(gdb) run segfault.py
Starting program: /usr/bin/python segfault.py
[Thread debugging using libthread_db enabled]
def print_big_array(small_array):
big_array = make_big_array(small_array)
Thus the segfault happens when printing big_array[-10:]. The reason is simply that big_array has been
allocated with its end outside the program memory.
For a list of Python-specific commands defined in the gdbinit, read the source of this file.
We get a segfault, and gdb captures it for post-mortem debugging in the C level stack (not the Python call
stack). We can debug the C call stack using gdbs commands:
(gdb) up
#1 0x004af4f5 in _copy_from_same_shape (dest=<value optimized out>,
src=<value optimized out>, myfunc=0x496780 <_strided_byte_copy>,
swap=0)
at numpy/core/src/multiarray/ctors.c:748
748
myfunc(dit->dataptr, dest->strides[maxaxis],
Wrap up exercise
The following script is well documented and hopefully legible. It seeks to answer a problem of actual
interest for numerical computing, but it does not work... Can you debug it?
Python source code: to_debug.py
As you can see, right now, we are in the C code of numpy. We would like to know what is the Python code that
triggers this segfault, so we go up the stack until we hit the Python execution loop:
(gdb) up
#8 0x080ddd23 in call_function (f=
Frame 0x85371ec, for file /home/varoquau/usr/lib/python2.6/site-packages/numpy/core/arrayprint.py, line 156, in _leading_trailing (a=<numpy.ndarray at remote 0x85371b0>, _nc=<module at remote 0xb7f93a64>), throwflag=0)
at ../Python/ceval.c:3750
3750
../Python/ceval.c: No such file or directory.
in ../Python/ceval.c
(gdb) up
#9 PyEval_EvalFrameEx (f=
Frame 0x85371ec, for file /home/varoquau/usr/lib/python2.6/site-packages/numpy/core/arrayprint.py, line 156, in _leading_trailing (a=<numpy.ndarray at remote 0x85371b0>, _nc=<module at remote 0xb7f93a64>), throwflag=0)
at ../Python/ceval.c:2412
2412
in ../Python/ceval.c
(gdb)
Once we are in the Python execution loop, we can use our special Python helper function. For instance we can
find the corresponding Python code:
(gdb) pyframe
/home/varoquau/usr/lib/python2.6/site-packages/numpy/core/arrayprint.py (158): _leading_trailing
(gdb)
This is numpy code, we need to go up until we find code that we have written:
(gdb) up
...
(gdb) up
#34 0x080dc97a in PyEval_EvalFrameEx (f=
Frame 0x82f064c, for file segfault.py, line 11, in print_big_array (small_array=<numpy.ndarray at remote 0x853ecf0>, big_array=<numpy.ndarray at remote 0x853ed20>), throwflag=0) at ../Python/ceval.c:1630
1630
../Python/ceval.c: No such file or directory.
in ../Python/ceval.c
(gdb) pyframe
segfault.py (12): print_big_array
201
202
10
No optimization without measuring!
Measure: profiling, timing
Youll have surprises: the fastest code is not always what you think
Optimizing code
10.2.1 Timeit
In IPython, use timeit (https://docs.python.org/library/timeit.html) to time elementary operations:
In [1]: import numpy as np
In [2]: a = np.arange(1000)
In [3]: %timeit a ** 2
100000 loops, best of 3: 5.73 us per loop
Donald Knuth
Premature optimization is the root of all evil
In [5]: %timeit a * a
100000 loops, best of 3: 5.56 us per loop
Prerequisites
For long running calls, using %time instead of %timeit; it is less precise but faster
line_profiler
10.2.2 Profiler
Chapters contents
Useful when you have a large program to profile, for example the following file:
Optimization workflow
Profiling Python code
Timeit
Profiler
Line-profiler
Making code go faster
Algorithmic optimization
* Example of the SVD
Writing faster numerical code
Additional Links
# For this example to run, you also need the 'ica.py' file
import numpy as np
from scipy import linalg
from ica import fastica
def test():
data = np.random.random((5000, 100))
u, s, v = linalg.svd(data)
pca = np.dot(u[:, :10].T, data)
results = fastica(pca.T, whiten=False)
if __name__ == '__main__':
test()
This is a combination of two unsupervised learning techniques, principal component analysis (PCA) and independent component analysis (ICA). PCA is a technique for dimensionality reduction, i.e. an algorithm to
explain the observed variance in your data using less dimensions. ICA is a source seperation technique, for example to unmix multiple signals that have been recorded through multiple sensors. Doing a PCA first and then
an ICA can be useful if you have more sensors than signals. For more information see: the FastICA example
from scikits-learn.
To run it, you also need to download the ica module. In IPython we can time the script:
In [1]: %run -t demo.py
203
204
User :
System:
14.3929 s.
0.256016 s.
u, s, v = linalg.svd(data)
pca = np.dot(u[:, :10], data)
results = fastica(pca.T, whiten=False)
Then we run the script using the kernprof.py program, with switches -l, --line-by-line and -v, --view
to use the line-by-line profiler and view the results in addition to saving them:
$ kernprof.py -l -v demo.py
percall
14.457
0.054
0.017
0.000
0.002
0.000
0.000
0.000
0.000
0.001
0.001
0.000
0.000
0.000
0.000
0.000
0.000
0.000
0.000
0.000
0.000
0.000
0.000
cumtime
14.479
0.054
0.021
0.011
0.005
0.001
0.001
0.001
0.001
0.008
14.551
0.001
0.004
0.002
0.000
14.551
0.000
0.000
0.001
0.001
0.000
0.000
0.008
percall
14.479
0.054
0.021
0.000
0.002
0.000
0.000
0.000
0.000
0.008
14.551
0.000
0.001
0.000
0.000
14.551
0.000
0.000
0.000
0.000
0.000
0.000
0.008
filename:lineno (function)
decomp.py:849 (svd)
{method 'random_sample' of 'mtrand.RandomState' objects}
function_base.py:645 (asarray_chkfinite)
{numpy.core._dotblas.dot}
{method 'any' of 'numpy.ndarray' objects}
ica.py:195 (gprime)
ica.py:192 (g)
{numpy.linalg.lapack_lite.dsyevd}
twodim_base.py:204 (diag)
ica.py:69 (_ica_par)
{execfile}
defmatrix.py:239 (__array_finalize__)
ica.py:58 (_sym_decorrelation)
linalg.py:841 (eigh)
{isinstance}
demo.py:1 (<module>)
numeric.py:180 (asarray)
defmatrix.py:193 (__new__)
defmatrix.py:43 (asmatrix)
defmatrix.py:287 (__mul__)
{numpy.core.multiarray.zeros}
{method 'transpose' of 'numpy.ndarray' objects}
ica.py:97 (fastica)
Clearly the svd (in decomp.py) is what takes most of our time, a.k.a. the bottleneck. We have to find a way to
make this step go faster, or to avoid this step (algorithmic optimization). Spending time on the rest of the code
is useless.
The SVD is taking all the time. We need to optimise this line.
Using the -o switch will output the profiler results to the file demo.prof to view with an external tool.
This can be useful if you wish to process the profiler output with a visualization tool.
10.2.3 Line-profiler
In both examples above, the SVD - Singular Value Decomposition - is what takes most of the time. Indeed, the
computational cost of this algorithm is roughly n 3 in the size of the input matrix.
However, in both of these example, we are not using all the output of the SVD, but only the first few rows of
its first return argument. If we use the svd implementation of scipy, we can ask for an incomplete version of
the SVD. Note that implementations of linear algebra in scipy are richer then those in numpy and should be
preferred.
In [3]: %timeit np.linalg.svd(data)
1 loops, best of 3: 14.5 s per loop
The profiler tells us which function takes most of the time, but not where it is called.
For this, we use the line_profiler: in the source file, we decorate a few functions that we want to inspect with
@profile (no need to import it)
@profile
def test():
data = np.random.random((5000, 100))
205
206
note: we need global a in the timeit so that it work, as it is assigning to a, and thus considers it as a
local variable.
demo.prof.pdf
demo.prof.png
demo.py
demo.py.lprof
In [3]: %timeit a + 1
10 loops, best of 3: 112 ms per loop
demo.pyc
demo.test
Memory access is cheaper when it is grouped: accessing a big array in a continuous way is much faster
than random access. This implies amongst other things that smaller strides are faster (see CPU cache
effects):
Real incomplete SVDs, e.g. computing only the first 10 eigenvectors, can be computed with arpack, available
in scipy.sparse.linalg.eigsh.
This is the reason why Fortran ordering or C ordering may make a big difference on operations:
In [5]: a = np.random.rand(20, 2**18)
In [6]: b = np.random.rand(20, 2**18)
In [7]: %timeit np.dot(b, a.T)
1 loops, best of 3: 194 ms per loop
In [8]: c = np.ascontiguousarray(a.T)
A complete discussion on advanced use of numpy is found in chapter Advanced Numpy, or in the article The
NumPy array: a structure for efficient numerical computation by van der Walt et al. Here we discuss only some
commonly encountered tricks to make code faster.
Note that copying the data to work around this effect may not be worth it:
In [10]: %timeit c = np.ascontiguousarray(a.T)
10 loops, best of 3: 106 ms per loop
Using numexpr can be useful to automatically optimize code for such effects.
Broadcasting
The last resort, once you are sure that all the high-level optimizations have been explored, is to transfer
the hot spots, i.e. the few lines or functions in which most of the time is spent, to compiled code. For
compiled code, the preferred option is to use Cython: it is easy to transform exiting Python code in
compiled code, and with a good use of the numpy support yields efficient code on numpy arrays, for
instance by unrolling loops.
In place operations
In [1]: a = np.zeros(1e7)
In [2]: %timeit global a ; a = 0*a
10 loops, best of 3: 111 ms per loop
B For all the above: profile and time your choices. Dont base your optimization on theoretical considerations.
207
208
CHAPTER
11
If you need to profile memory usage, you could try the memory_profiler
If you need to profile down into C extensions, you could try using gperftools from Python with yep.
If you would like to track performace of your code across time, i.e. as you make new commits to your
repository, you could try: vbench
11.1 Introduction
(dense) matrix is:
mathematical object
data structure for storing a 2D array of values
important features:
memory allocated once for all items
usually a contiguous chunk, think NumPy ndarray
fast access to individual items (*)
209
210
cons: depends on actual storage scheme, (*) usually does not hold
11.1.4 Prerequisites
recent versions of
numpy
scipy
matplotlib (optional)
ipython (the enhancements come handy)
example plots:
11.1. Introduction
211
212
* passing a sparse matrix object to NumPy functions expecting ndarray/matrix does not
work
use:
rather specialized
Examples
...
attributes:
mtx.A - same as mtx.toarray()
mtx.T - transpose (same as mtx.transpose())
mtx.H - Hermitian (conjugate) transpose
mtx.real - real part of complex matrix
mtx.imag - imaginary part of complex matrix
mtx.size - the number of nonzeros (same as self.getnnz())
mtx.shape - the number of rows and columns (tuple)
data usually stored in NumPy arrays
sparse matrix
213
214
offset: row
2:
1:
0:
-1:
-2:
-3:
9
--10-----1 . 11 .
5 2 . 12
. 6 3 .
. . 7 4
---------8
matrix-vector multiplication
>>> vec = np.ones((4, ))
>>> vec
array([ 1., 1., 1., 1.])
>>> mtx * vec
array([ 12., 19.,
9., 11.])
>>> mtx.toarray() * vec
array([[ 1.,
0., 11.,
0.],
[ 5.,
2.,
0., 12.],
[ 0.,
6.,
3.,
0.],
[ 0.,
0.,
7.,
4.]])
keys are (row, column) index tuples (no duplicate entries allowed)
1.,
0.,
constructor accepts:
dense matrix (array)
1.],
1.]])
sparse matrix
215
216
sparse matrix
shape tuple (create empty matrix)
use:
Examples
use:
facilitates fast conversion among sparse formats
when converting to other format (usually CSR or CSC), duplicate entries are summed together
no slicing...:
>>> mtx[2, 3]
Traceback (most recent call last):
...
TypeError: 'coo_matrix' object ...
constructor accepts:
dense matrix (array)
217
218
indices[indptr[i]:indptr[i+1]]
constructor accepts:
* nonzero values of the i-th column are data[indptr[i]:indptr[i+1]] with row indices indices[indptr[i]:indptr[i+1]]
indices[indptr[j]:indptr[j+1]]
use:
Examples
sparse matrix
shape tuple (create empty matrix)
(data, ij) tuple
(data, indices, indptr) tuple
219
220
Examples
many arithmetic operations considerably more efficient than CSR for sparse matrices with dense submatrices
use:
like CSR
Examples
create empty BSR matrix with (1, 1) block size (like CSR...):
>>> mtx = sparse.bsr_matrix((3, 4), dtype=np.int8)
>>> mtx
<3x4 sparse matrix of type '<... 'numpy.int8'>'
with 0 stored elements (blocksize = 1x1) in Block Sparse Row format>
>>> mtx.todense()
matrix([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)
a bug?
create using (data, ij) tuple with (1, 1) block size (like CSR...):
>>> row = np.array([0, 0, 1, 2, 2, 2])
>>> col = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> mtx = sparse.bsr_matrix((data, (row, col)), shape=(3, 3))
>>> mtx
<3x3 sparse matrix of type '<... 'numpy.int64'>'
with 6 stored elements (blocksize = 1x1) in Block Sparse Row format>
>>> mtx.todense()
matrix([[1, 0, 2],
[0, 0, 3],
[4, 5, 6]]...)
>>> mtx.data
array([[[1]],
[[2]],
[[3]],
constructor accepts:
[[4]],
[[5]],
sparse matrix
221
222
[[6]]]...)
>>> mtx.indices
array([0, 2, 2, 0, 1, 2], dtype=int32)
>>> mtx.indptr
array([0, 2, 3, 6], dtype=int32)
create using (data, indices, indptr) tuple with (2, 2) block size:
[[2, 2],
[2, 2]],
[[3, 3],
[3, 3]],
included in SciPy
real and complex systems
[[4, 4],
[4, 4]],
[[5, 5],
[5, 5]],
[[6, 6],
[6, 6]]])
11.2.3 Summary
Examples
format
matrix *
vector
get
item
fancy
get
set
item
fancy
set
solvers
note
DIA
yes
yes
yes
yes
DOK
python
yes
yes
yes
COO
sparsetools
sparsetools
sparsetools
sparsetools
one axis
only
.
yes
yes
slow
iterative
iterative
iterative
iterative
any
LIL
sparsetools
via CSR
yes
yes
slow
any
specialized
CSR
CSC
BSR
223
both superlu and umfpack can be used (if the latter is installed) as follows:
prepare a linear system:
>>> import numpy as np
>>> from scipy import sparse
>>> mtx = sparse.spdiags([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1], 5, 5)
>>> mtx.todense()
matrix([[ 1, 5, 0, 0, 0],
[ 0, 2, 8, 0, 0],
[ 0, 0, 3, 9, 0],
[ 0, 0, 0, 4, 10],
[ 0, 0, 0, 0, 5]])
>>> rhs = np.array([1, 2, 3, 4, 5], dtype=np.float32)
224
examples/direct_solve.py
Common Parameters
mandatory:
A [{sparse matrix, dense matrix, LinearOperator}] The N-by-N matrix of the linear system.
b [{array, matrix}] Right hand side of the linear system. Has shape (N,) or (N,1).
optional:
x0 [{array, matrix}] Starting guess for the solution.
tol [float] Relative tolerance to achieve before terminating.
maxiter [integer] Maximum number of iterations. Iteration will stop after maxiter steps even if the specified tolerance has not been achieved.
"""
Solve a linear system
=======================
M [{sparse matrix, dense matrix, LinearOperator}] Preconditioner for A. The preconditioner should approximate the inverse of A. Effective preconditioning dramatically improves the rate of convergence, which implies that fewer iterations are needed to reach a given error tolerance.
callback [function] User-supplied function to call after each iteration. It is called as callback(xk), where
xk is the current solution vector.
LinearOperator Class
from scipy.sparse.linalg.interface import LinearOperator
rand = np.random.rand
useful abstraction that enables using dense and sparse matrices within the solvers, as well as matrix-free
solutions
has shape and matvec() (+ some optional parameters)
plt.clf()
plt.spy(mtx, marker='.', markersize=2)
plt.show()
example:
>>>
>>>
>>>
...
...
>>>
mtx = mtx.tocsr()
rhs = rand(1000)
x = linsolve.spsolve(mtx, rhs)
225
import numpy as np
from scipy.sparse.linalg import LinearOperator
def mv(v):
return np.array([2*v[0], 3*v[1]])
A = LinearOperator((2, 2), matvec=mv)
226
>>> A
<2x2 LinearOperator with unspecified dtype>
>>> A.matvec(np.ones(2))
array([ 2., 3.])
>>> A * np.ones(2)
array([ 2., 3.])
pylab.figure(figsize=(9,9))
for i in range(K):
pylab.subplot(3, 3, i+1)
pylab.title('Eigenvector %d ' % i)
pylab.pcolor(V[:,i].reshape(N,N))
pylab.axis('equal')
pylab.axis('off')
pylab.show()
examples/pyamg_with_lobpcg.py
problem specific
examples/lobpcg_sakurai.py
output:
$ python examples/lobpcg_sakurai.py
Results by LOBPCG for n=2500
[ 0.06250083
0.06250028
0.06250007]
Exact eigenvalues
arpack * a collection of Fortran77 subroutines designed to solve large scale eigenvalue problems
lobpcg (Locally Optimal Block Preconditioned Conjugate Gradient Method) * works very well in combination with PyAMG * example by Nathan Bell:
[ 0.06250005
0.0625002
0.06250044]
"""
Compute eigenvectors and eigenvalues using a preconditioned eigensolver
========================================================================
In this example Smoothed Aggregation (SA) is used to precondition
the LOBPCG eigensolver on a two-dimensional Poisson problem with
Dirichlet boundary conditions.
"""
import scipy
from scipy.sparse.linalg import lobpcg
from pyamg import smoothed_aggregation_solver
from pyamg.gallery import poisson
N = 100
K = 9
A = poisson((N,N), format='csr')
# create the AMG hierarchy
ml = smoothed_aggregation_solver(A)
# initial approximation to the K eigenvectors
X = scipy.rand(A.shape[0], K)
# preconditioner based on ml
M = ml.aspreconditioner()
# compute eigenvalues and eigenvectors with LOBPCG
W,V = lobpcg(A, X, M=M, tol=1e-8, largest=False)
#plot the eigenvectors
import pylab
227
228
CHAPTER
12
PyAMG
algebraic multigrid solvers
https://github.com/pyamg/pyamg
Pysparse
229
230
Need to know the shape and dtype of the image (how to separate data bytes).
For large data, use np.memmap for memory mapping:
>>> face_memmap = np.memmap('face.raw', dtype=np.uint8, shape=(768, 1024, 3))
(data are read from the file, and not loaded into memory)
Working on a list of image files
>>>
...
...
>>>
>>>
>>>
for i in range(10):
im = np.random.random_integers(0, 255, 10000).reshape((100, 100))
misc.imsave('random_%02d .png' % i, im)
from glob import glob
filelist = glob('random*.png')
filelist.sort()
231
232
See also:
3-D visualization: Mayavi
See 3D plotting with Mayavi.
Image plane widgets
Isosurfaces
...
233
234
12.4.1 Blurring/smoothing
np.histogram
Exercise
Open as an array the scikit-image logo (http://scikit-image.org/_static/img/logo.png), or an image that you have on your computer.
Crop a meaningful part of the image, for example the python circle in the logo.
Display the image array using matplotlib. Change the interpolation method and zoom to see the
difference.
Transform your image to greyscale
Increase the contrast of the image by changing its minimum and maximum values. Optional: use
scipy.stats.scoreatpercentile (read the docstring!) to saturate 5% of the darkest pixels and
5% of the lightest pixels.
Save the array to two different file formats (png, jpg, tiff)
>>>
>>>
>>>
>>>
Uniform filter
>>> local_mean = ndimage.uniform_filter(face, size=11)
12.4.2 Sharpening
face = misc.face(gray=True)
lx, ly = face.shape
# Cropping
crop_face = face[lx / 4: - lx / 4, ly / 4: - ly / 4]
# up <-> down flip
flip_ud_face = np.flipud(face)
# rotation
rotate_face = ndimage.rotate(face, 45)
rotate_face_noreshape = ndimage.rotate(face, 45, reshape=False)
12.4.3 Denoising
Noisy face:
>>>
>>>
>>>
>>>
235
236
A Gaussian filter smoothes the noise out... and the edges as well:
>>> el = ndimage.generate_binary_structure(2, 1)
>>> el
array([[False, True, False],
[ True, True, True],
[False, True, False]], dtype=bool)
>>> el.astype(np.int)
array([[0, 1, 0],
[1, 1, 1],
[0, 1, 0]])
im = np.zeros((20, 20))
im[5:-5, 5:-5] = 1
im = ndimage.distance_transform_bf(im)
im_noise = im + 0.2 * np.random.randn(*im.shape)
im_med = ndimage.median_filter(im_noise, 3)
Erosion = minimum filter. Replace the value of a pixel by the minimal value covered by the structuring element.:
237
238
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]])
>>> # Opening can also smooth corners
>>> ndimage.binary_opening(a).astype(np.int)
array([[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]])
>>>
>>>
>>>
>>>
>>>
np.random.seed(2)
im = np.zeros((64, 64))
x, y = (63*np.random.random((2, 8))).astype(np.int)
im[x, y] = np.arange(8)
Many other mathematical morphology operations: hit and miss transform, tophat, etc.
im = np.zeros((256, 256))
im[64:-64, 64:-64] = 1
239
240
12.5.2 Segmentation
Exercise
Histogram-based segmentation (no spatial information)
>>>
>>>
>>>
>>>
>>>
>>>
>>>
Check how a first denoising step (e.g. with a median filter) modifies the histogram, and check that the
resulting histogram-based segmentation is more accurate.
n = 10
l = 256
im = np.zeros((l, l))
np.random.seed(1)
points = l*np.random.random((2, n**2))
im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
im = ndimage.gaussian_filter(im, sigma=l/(4.*n))
See also:
More advanced segmentation algorithms are found in the scikit-image: see Scikit-image: image processing.
See also:
Other Scientific Packages provide algorithms that can be useful for image processing. In this example, we use
the spectral clustering function of the scikit-learn in order to segment glued objects.
>>> l = 100
>>> x, y = np.indices((l, l))
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
circle1
circle2
circle3
circle4
>>>
>>>
>>>
>>>
# 4 circles
img = circle1 + circle2 + circle3 + circle4
mask = img.astype(bool)
img = img.astype(float)
>>>
>>>
>>>
>>>
img += 1 + 0.2*np.random.randn(*img.shape)
# Convert the image into a graph with the value of the gradient on
# the edges.
graph = image.img_to_graph(img, mask=mask)
=
=
=
=
(x
(x
(x
(x
center1[0])**2
center2[0])**2
center3[0])**2
center4[0])**2
+
+
+
+
(y
(y
(y
(y
center1[1])**2
center2[1])**2
center3[1])**2
center4[1])**2
<
<
<
<
radius1**2
radius2**2
radius3**2
radius4**2
Exercise
Check that reconstruction operations (erosion + propagation) produce a better result than opening/closing:
>>> eroded_img = ndimage.binary_erosion(binary_img)
>>> reconstruct_img = ndimage.binary_propagation(eroded_img, mask=binary_img)
>>> tmp = np.logical_not(reconstruct_img)
>>> eroded_tmp = ndimage.binary_erosion(tmp)
>>> reconstruct_final = np.logical_not(ndimage.binary_propagation(eroded_tmp, mask=tmp))
>>> np.abs(mask - close_img).mean()
0.00727836...
>>> np.abs(mask - reconstruct_final).mean()
0.00059502...
241
242
>>> remove_pixel.shape
(256, 256)
>>> label_im[remove_pixel] = 0
>>> plt.imshow(label_im)
<matplotlib.image.AxesImage object at 0x...>
n = 10
l = 256
im = np.zeros((l, l))
points = l*np.random.random((2, n**2))
im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
im = ndimage.gaussian_filter(im, sigma=l/(4.*n))
mask = im > im.mean()
243
244
>>>
>>>
>>>
>>>
...
>>>
sx, sy = f.shape
X, Y = np.ogrid[0:sx, 0:sy]
regions = (sy//6) * (X//4) + (Y//6) # note that we use broadcasting
block_mean = ndimage.mean(f, labels=regions, index=np.arange(1,
regions.max() +1))
block_mean.shape = (sx // 4, sy // 6)
When regions are regular blocks, it is more efficient to use stride tricks (Example: fake dimensions with strides).
Non-regularly-spaced blocks: radial mean:
>>>
>>>
>>>
>>>
>>>
sx, sy = f.shape
X, Y = np.ogrid[0:sx, 0:sy]
r = np.hypot(X - sx/2, Y - sy/2)
rbin = (20* r/r.max()).astype(np.int)
radial_mean = ndimage.mean(f, labels=rbin, index=np.arange(1, rbin.max() +1))
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
np.random.seed(1)
n = 10
l = 256
im = np.zeros((l, l))
points = l*np.random.random((2, n**2))
im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
im = ndimage.gaussian_filter(im, sigma=l/(4.*n))
mask = im > im.mean()
granulo = granulometry(mask, sizes=np.arange(2, 19, 4))
Other measures
Correlation function, Fourier/wavelet spectrum, etc.
One example with mathematical morphology: granulometry
>>> def disk_structure(n):
...
struct = np.zeros((2 * n + 1, 2 * n + 1))
...
x, y = np.indices((2 * n + 1, 2 * n + 1))
...
mask = (x - n)**2 + (y - n)**2 <= n**2
...
struct[mask] = 1
...
return struct.astype(np.bool)
...
>>>
>>> def granulometry(data, sizes=None):
...
s = max(data.shape)
...
if sizes == None:
...
sizes = range(1, s/2, 2)
...
granulo = [ndimage.binary_opening(data, \
...
structure=disk_structure(n)).sum() for n in sizes]
...
return granulo
...
>>>
See also:
More on image-processing:
The chapter on Scikit-image
245
246
Other, more powerful and complete modules: OpenCV (Python bindings), CellProfiler, ITK with Python
bindings
13
247
248
A convex function:
f is above all its tangents.
equivalently, for two point A, B, f(C) lies below
the segment [f(A), f(B])], if A < C < B
A non-convex function
Optimizing convex functions is easy. Optimizing non-convex functions can be very hard.
It can be proven that for a convex function a local minimum is also a global minimum. Then, in some sense,
the minimum is unique.
Not all optimization problems are equal. Knowing your problem enables you to choose the right tool.
Dimensionality of the problem
The scale of an optimization problem is pretty much set by the dimensionality of the problem, i.e. the
number of scalar variables on which the search is performed.
A smooth function:
The gradient is defined everywhere, and is a continuous
function
A non-smooth function
Optimizing smooth functions is easier (true in the context of black-box optimization, otherwise Linear Programming is an example of methods which deal very efficiently with piece-wise linear functions).
249
250
Brents
method
can
also
scipy.optimize.fminbound()
13.1.4 Constraints
be
used
for
optimization
constrained
to
an
interval
using
251
252
the valley. The conjugate gradient solves this problem by adding a friction term: each step depends on the two
last values of the gradient and sharp turns are reduced.
Also, it clearly can be advantageous to take bigger steps. This is done in gradient descent code using a line
search.
Table 13.2: Adaptive step gradient descent
An ill-conditionned
non-quadratic function.
A well-conditionned quadratic
function.
An ill-conditionned very
non-quadratic function.
Methods based on conjugate gradient are named with cg in scipy. The simple conjugate gradient method to
minimize a function is scipy.optimize.fmin_cg():
>>> def f(x):
# The rosenbrock function
...
return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
>>> optimize.fmin_cg(f, [2, 2])
Optimization terminated successfully.
Current function value: 0.000000
Iterations: 13
Function evaluations: 120
Gradient evaluations: 30
array([ 0.99998968, 0.99997855])
An ill-conditionned quadratic
function.
These methods need the gradient of the function. They can compute it, but will perform better if you can pass
them the gradient:
An ill-conditionned
non-quadratic function.
An ill-conditionned very
non-quadratic function.
Note that the function has only been evaluated 30 times, compared to 120 without the gradient.
The more a function looks like a quadratic function (elliptic iso-curves), the easier it is to optimize.
The gradient descent algorithms above are toys not to be used on real problems.
As can be seen from the above experiments, one of the problems of the simple gradient descent algorithms, is
that it tends to oscillate across a valley, each time following the direction of the gradient, that makes it cross
253
Newton methods use a local quadratic approximation to compute the jump direction. For this purpose, they
rely on the 2 first derivative of the function: the gradient and the Hessian.
254
Note that compared to a conjugate gradient (above), Newtons method has required less function evaluations,
but more gradient evaluations, as it uses it to approximate the Hessian. Lets compute the Hessian and pass it
to the algorithm:
>>> def hessian(x): # Computed with sympy
...
return np.array(((1 - 4*x[1] + 12*x[0]**2, -4*x[0]), (-4*x[0], 2)))
>>> optimize.fmin_ncg(f, [2, 2], fprime=fprime, fhess=hessian)
Optimization terminated successfully.
Current function value: 0.000000
Iterations: 9
Function evaluations: 11
Gradient evaluations: 19
Hessian evaluations: 9
array([ 1., 1.])
L-BFGS: Limited-memory BFGS Sits between BFGS and conjugate gradient: in very high dimensions (> 250)
the Hessian matrix is too costly to compute and invert. L-BFGS keeps a low-rank version. In addition, the scipy
version, scipy.optimize.fmin_l_bfgs_b(), includes box bounds:
>>> def f(x):
# The rosenbrock function
...
return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
>>> def fprime(x):
...
return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] - x[0]**2)))
>>> optimize.fmin_l_bfgs_b(f, [2, 2], fprime=fprime)
(array([ 1.00000005, 1.00000009]), 1.4417677473011859e-15, {...})
If you do not specify the gradient to the L-BFGS solver, you need to add approx_grad=1
At very high-dimension, the inversion of the Hessian can be costly and unstable (large scale > 250).
Newton optimizers should not to be confused with Newtons root finding method, based on the same principles, scipy.optimize.newton().
255
256
An ill-conditionned
non-quadratic function:
An ill-conditionned very
non-quadratic function:
257
Hessian,
prefer
the
Newton
method
258
or
Powell
Consider the function exp(-1/(.1*x**2 + y**2). This function admits a minimum in (0, 0). Starting
from an initialization at (1, 1), try to get within 1e-8 of this minimum point.
You can use scipy.optimize.check_grad() to check that your gradient is correct. It returns the norm of the
different between the gradient given, and a gradient computed numerically:
>>> optimize.check_grad(f, fprime, [2, 2])
2.384185791015625e-07
This took 67 function evaluations (check it with full_output=1). What if we compute the norm ourselves and
use a good generic optimizer (BFGS):
>>> def g(x):
...
return np.sum(f(x)**2)
>>> optimize.fmin_bfgs(g, x0)
Optimization terminated successfully.
Current function value: 0.000000
Iterations: 11
Function evaluations: 144
Gradient evaluations: 12
array([ -7.4...-09,
1.1...e-01,
2.2...e-01,
3.3...e-01,
4.4...e-01,
5.5...e-01,
6.6...e-01,
7.7...e-01,
8.8...e-01,
1.0...e+00])
BFGS needs more function calls, and gives a less precise result.
Time your approach. Find the fastest approach. Why is BFGS not working well?
leastsq is interesting compared to BFGS only if the dimensionality of the output vector is large, and larger
than the number of parameters to optimize.
B If the function is linear, this is a linear-algebra problem, and should be solved with scipy.linalg.lstsq().
259
260
Least square problems occur often when fitting a nonlinear to data. While it is possible to construct our optimization problem ourselves, scipy provides a helper
function for this purpose: scipy.optimize.curve_fit():
>>> def f(t, omega, phi):
...
return np.cos(omega * t + phi)
>>> x = np.linspace(0, 3, 50)
>>> y = f(x, 1.5, 1) + .1*np.random.normal(size=50)
straints:
>>> def f(x):
...
return np.sqrt((x[0] - 3)**2 + (x[1] - 2)**2)
>>> optimize.curve_fit(f, x, y)
(array([ 1.51854577, 0.92665541]), array([[ 0.00037994, -0.00056796],
[-0.00056796, 0.00123978]]))
Exercise
Do the same with omega = 3. What is the difficulty?
instance in scikit-learn). In general do not use generic solvers when specific ones exist.
Lagrange multipliers
If you are ready to do a bit of math, many constrained optimization problems can be converted to nonconstrained optimization problems using a mathematical trick known as Lagrange multipliers.
261
262
14
Interfacing with C
Each technology is demonstrated by wrapping the cos function from math.h. While this is a mostly a trivial
example, it should serve us well to demonstrate the basics of the wrapping solution. Since each technique
also includes some form of Numpy support, this is also demonstrated using an example where the cosine is
computed on some kind of array.
Last but not least, two small warnings:
All of these techniques may crash (segmentation fault) the Python interpreter, which is (usually) due to
bugs in the C code.
14.2 Python-C-Api
The Python-C-API is the backbone of the standard Python interpreter (a.k.a CPython). Using this API it is
possible to write Python extension module in C and C++. Obviously, these extension modules can, by virtue of
language compatibility, call any function written in C or C++.
Chapters contents
All the examples have been done on Linux, they should be possible on other operating systems.
Introduction
Python-C-Api
Ctypes
SWIG
Cython
Summary
Further Reading and References
Exercises
When using the Python-C-API, one usually writes much boilerplate code, first to parse the arguments that were
given to a function, and later to construct the return type.
Advantages
Requires no additional libraries
Lots of low-level control
Entirely usable from C++
14.1 Introduction
Disadvantages
May require a substantial amount of effort
Python-C-Api
Must be compiled
Ctypes
Cython
Reference count bugs are easy to create and very hard to track down.
These four techniques are perhaps the most well known ones, of which Cython is probably the most advanced
one and the one you should consider using first. The others are also important, if you want to understand the
wrapping problem from different angles. Having said that, there are other alternatives out there, but having
understood the basics of the ones above, you will be in a position to evaluate the technique of your choice to
see if it fits your needs.
The following criteria may be useful when evaluating a technology:
Are additional libraries required?
The Python-C-Api example here serves mainly for didactic reasons. Many of the other techniques actually
depend on this, so it is good to have a high-level understanding of how it works. In 99% of the use-cases you
will be better off, using an alternative technique.
Since refernce counting bugs are easy to create and hard to track down, anyone really needing to use the
Python C-API should read the section about objects, types and reference counts from the official python documentation. Additionally, there is a tool by the name of cpychecker which can help discover common errors
with reference counting.
263
14.2. Python-C-Api
264
14.2.1 Example
cos_module.c
The following C-extension module, make the cos function from the standard math library available to Python:
/*
# include <Python.h>
# include <math.h>
/* wrapped cosine function */
static PyObject* cos_func(PyObject* self, PyObject* args)
{
double value;
double answer;
cos_module.c
cos_module.so
setup.py
In [3]: dir(cos_module)
Out[3]: ['__doc__', '__file__', '__name__', '__package__', 'cos_func']
In [4]: cos_module.cos_func(1.0)
Out[4]: 0.5403023058681398
In [5]: cos_module.cos_func(0.0)
Out[5]: 1.0
In [6]: cos_module.cos_func(3.14159265359)
Out[7]: -1.0
/* module initialization */
PyMODINIT_FUNC
initcos_module(void)
{
(void) Py_InitModule("cos_module", CosMethods);
}
As you can see, there is much boilerplate, both to massage the arguments and return types into place and for
the module initialisation. Although some of this is amortised, as the extension grows, the boilerplate required
for each function(s) remains.
The standard python build system distutils supports compiling C-extensions from a setup.py, which is
rather convenient:
from distutils.core import setup, Extension
In [10]: cos_module.cos_func('foo')
--------------------------------------------------------------------------TypeError
Traceback (most recent call last)
<ipython-input-10-11bee483665d> in <module>()
----> 1 cos_module.cos_func('foo')
TypeError: a float is required
If you do ever need to use the Numpy C-API refer to the documentation about Arrays and Iterators.
The following example shows how to pass Numpy arrays as arguments to functions and how to iterate over
Numpy arrays using the (old) Numpy-C-API. It simply takes an array as argument applies the cosine function
from the math.h and returns a resulting new array.
/*
$ ls
14.2. Python-C-Api
setup.py
265
Example of wrapping the cos function from math.h using the Numpy-C-API. */
14.2. Python-C-Api
266
# include <Python.h>
# include <numpy / arrayobject.h>
# include <math.h>
/* module initialization */
PyMODINIT_FUNC
initcos_module_np(void)
{
(void) Py_InitModule("cos_module_np", CosMethods);
/* IMPORTANT: this must be called */
import_array();
}
To compile this we can use distutils again. However we need to be sure to include the Numpy headers by using
:func:numpy.get_include.
To convince ourselves if this does actually works, we run the following test script:
import cos_module_np
import numpy as np
import pylab
x = np.arange(0, 2 * np.pi, 0.1)
y = cos_module_np.cos_func_np(x)
pylab.plot(x, y)
pylab.show()
14.3 Ctypes
Ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions
in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.
Advantages
14.2. Python-C-Api
267
14.3. Ctypes
268
Disadvantages
Requires code to be wrapped to be available as a shared library (roughly speaking *.dll in Windows
*.so in Linux and *.dylib in Mac OSX.)
No good support for C++
In [6]: cos_module.cos_func(3.14159265359)
Out[6]: -1.0
As with the previous example, this code is somewhat robust, although the error message is not quite as helpful,
since it does not tell us what the type should be.
In [7]: cos_module.cos_func('foo')
--------------------------------------------------------------------------ArgumentError
Traceback (most recent call last)
<ipython-input-7-11bee483665d> in <module>()
----> 1 cos_module.cos_func('foo')
14.3.1 Example
As advertised, the wrapper code is in pure Python.
""" Example of wrapping cos function from math.h using ctypes. """
/home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/ctypes/cos_module.py in cos_func(arg)
12 def cos_func(arg):
13
''' Wrapper for cos from math.h '''
---> 14
return libm.cos(arg)
import ctypes
from ctypes.util import find_library
# find and load the library
libm = ctypes.cdll.LoadLibrary(find_library('m'))
# set the argument type
libm.cos.argtypes = [ctypes.c_double]
# set the return type
libm.cos.restype = ctypes.c_double
def cos_func(arg):
''' Wrapper for cos from math.h '''
return libm.cos(arg)
Finding and loading the library may vary depending on your operating system, check the documentation
for details
This may be somewhat deceptive, since the math library exists in compiled form on the system already.
If you were to wrap a in-house library, you would have to compile it first, which may or may not require
some additional effort.
For more information, consult the corresponding section in the Numpy Cookbook and the API documentation
for numpy.ndarray.ctypes and numpy.ctypeslib.
For the following example, lets consider a C function in a library that takes an input and an output array,
computes the cosine of the input array and stores the result in the output array.
The library consists of the following header file (although this is not strictly needed for this example, we list it
for completeness):
void cos_doubles(double * in_array, double * out_array, int size);
In [2]: cos_module?
Type:
module
String Form:<module 'cos_module' from 'cos_module.py'>
File:
/home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/ctypes/cos_module.py
Docstring: <no docstring>
In [3]: dir(cos_module)
Out[3]:
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'cos_func',
'ctypes',
'find_library',
'libm']
# include <math.h>
/* Compute the cosine of each element in in_array, storing the result in
* out_array. */
void cos_doubles(double * in_array, double * out_array, int size){
int i;
for(i=0;i<size;i++){
out_array[i] = cos(in_array[i]);
}
}
And since the library is pure C, we cant use distutils to compile it, but must use a combination of make and
gcc:
m.PHONY : clean
libcos_doubles.so : cos_doubles.o
gcc -shared -Wl,-soname,libcos_doubles.so -o libcos_doubles.so cos_doubles.o
In [4]: cos_module.cos_func(1.0)
Out[4]: 0.5403023058681398
cos_doubles.o : cos_doubles.c
gcc -c -fPIC cos_doubles.c -o cos_doubles.o
In [5]: cos_module.cos_func(0.0)
Out[5]: 1.0
14.3. Ctypes
clean :
269
14.3. Ctypes
270
We can then compile this (on Linux) into the shared library libcos_doubles.so:
14.4 SWIG
$ ls
cos_doubles.c cos_doubles.h cos_doubles.py makefile test_cos_doubles.py
$ make
gcc -c -fPIC cos_doubles.c -o cos_doubles.o
gcc -shared -Wl,-soname,libcos_doubles.so -o libcos_doubles.so cos_doubles.o
$ ls
cos_doubles.c cos_doubles.o
libcos_doubles.so* test_cos_doubles.py
cos_doubles.h cos_doubles.py makefile
SWIG, the Simplified Wrapper Interface Generator, is a software development tool that connects programs
written in C and C++ with a variety of high-level programming languages, including Python. The important
thing with SWIG is, that it can autogenerate the wrapper code for you. While this is an advantage in terms of
development time, it can also be a burden. The generated file tend to be quite large and may not be too human
readable and the multiple levels of indirection which are a result of the wrapping process, may be a bit tricky
to understand.
Now we can proceed to wrap this library via ctypes with direct support for (certain kinds of) Numpy arrays:
""" Example of wrapping a C library function that accepts a C double array as
input using the numpy.ctypeslib. """
import numpy as np
import numpy.ctypeslib as npct
from ctypes import c_int
Disadvantages
Autogenerates enormous files
14.4.1 Example
Lets imagine that our cos function lives in a cos_module which has been written in c and consists of the
source file cos_module.c:
# include <math.h>
Note the inherent limitation of contiguous single dimensional Numpy arrays, since the C functions requires this kind of buffer.
Also note that the output array must be preallocated, for example with numpy.zeros() and the function
will write into its buffer.
Although the original signature of the cos_doubles function is ARRAY, ARRAY, int the final
cos_doubles_func takes only two Numpy arrays as arguments.
And, as before, we convince ourselves that it worked:
And our goal is to expose the cos_func to Python. To achieve this with SWIG, we must write an interface file
which contains the instructions for SWIG.
/*
%module cos_module
%{
/* the resulting C file should be built as a python extension */
# define SWIG_FILE_WITH_INIT
/* Includes the header in the wrapper code */
# include "cos_module.h"
%}
/* Parse the header file to generate wrappers */
%include "cos_module.h"
import numpy as np
import pylab
import cos_doubles
x = np.arange(0, 2 * np.pi, 0.1)
y = np.empty_like(x)
cos_doubles.cos_doubles_func(x, y)
pylab.plot(x, y)
pylab.show()
As you can see, not too much code is needed here. For this simple example it is enough to simply include
the header file in the interface file, to expose the function to Python. However, SWIG does allow for more fine
grained inclusion/exclusion of functions found in header files, check the documentation for details.
Generating the compiled wrappers is a two stage process:
1. Run the swig executable on the interface file to generate the files cos_module_wrap.c, which is the
source file for the autogenerated Python C-extension and cos_module.py, which is the autogenerated
pure python module.
14.3. Ctypes
271
14.4. SWIG
272
2. Compile the cos_module_wrap.c into the _cos_module.so. Luckily, distutils knows how to handle
SWIG interface files, so that our setup.py is simply:
setup(ext_modules=[Extension("_cos_module",
sources=["cos_module.c", "cos_module.i"])])
In [7]: cos_module.cos_func('foo')
--------------------------------------------------------------------------TypeError
Traceback (most recent call last)
<ipython-input-7-11bee483665d> in <module>()
----> 1 cos_module.cos_func('foo')
$ cd advanced/interfacing_with_c/swig
$ ls
cos_module.c
cos_module.h
cos_module.i
setup.py
cos_module.c
cos_module.h
cos_module.i
cos_module.py
_cos_module.so*
cos_module_wrap.c
We can now load and execute the cos_module as we have done in the previous examples:
In [1]: import cos_module
In [2]: cos_module?
Type:
module
String Form:<module 'cos_module' from 'cos_module.py'>
File:
/home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/swig/cos_module.py
Docstring: <no docstring>
In [3]: dir(cos_module)
Out[3]:
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'_cos_module',
'_newclass',
'_object',
'_swig_getattr',
'_swig_property',
'_swig_repr',
'_swig_setattr',
'_swig_setattr_nondynamic',
'cos_func']
setup.py
%module cos_doubles
%{
/* the resulting C file should be built as a python extension */
# define SWIG_FILE_WITH_INIT
/* Includes the header in the wrapper code */
# include "cos_doubles.h"
%}
/* include the numpy typemaps */
%include "numpy.i"
/* need this for correct module initialization */
%init %{
import_array();
%}
/* typemaps for the two arrays, the second will be modified in-place */
%apply (double* IN_ARRAY1, int DIM1) {(double * in_array, int size_in)}
%apply (double* INPLACE_ARRAY1, int DIM1) {(double * out_array, int size_out)}
In [4]: cos_module.cos_func(1.0)
Out[4]: 0.5403023058681398
In [5]: cos_module.cos_func(0.0)
Out[5]: 1.0
In [6]: cos_module.cos_func(3.14159265359)
Out[6]: -1.0
Again we test for robustness, and we see that we get a better error message (although, strictly speaking in
14.4. SWIG
273
14.4. SWIG
274
%}
14.5 Cython
Cython is both a Python-like language for writing C-extensions and an advanced compiler for this language.
The Cython language is a superset of Python, which comes with additional constructs that allow you call C
functions and annotate variables and class attributes with c types. In this sense one could also call it a Python
with types.
setup(ext_modules=[Extension("_cos_doubles",
sources=["cos_doubles.c", "cos_doubles.i"],
include_dirs=[numpy.get_include()])])
In addition to the basic use case of wrapping native code, Cython supports an additional use-case, namely
interactive optimization. Basically, one starts out with a pure-Python script and incrementally adds Cython
types to the bottleneck code to optimize only those code paths that really matter.
In this sense it is quite similar to SWIG, since the code can be autogenerated but in a sense it also quite similar
to ctypes since the wrapping code can (almost) be written in Python.
$ ls
While others solutions that autogenerate code can be quite difficult to debug (for example SWIG) Cython
cos_doubles.c cos_doubles.h cos_doubles.i numpy.i setup.py test_cos_doubles.py
comes with an extension to the GNU debugger that helps debug Python, Cython and C code.
$ python setup.py build_ext -i
running build_ext
The autogenerated C code uses the Python-C-Api.
building '_cos_doubles' extension
Advantages
swigging cos_doubles.i to cos_doubles_wrap.c
swig -python -o cos_doubles_wrap.c cos_doubles.i
Python like language for writing C-extensions
cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found.
cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found.
Autogenerated code
cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found.
Supports incremental optimization
creating build
creating build/temp.linux-x86_64-2.7
Includes a GNU debugger extension
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/anaconda/include/python2.7 -c cos_doubles.c -o build/temp.lin
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include
Support for C++ (Since version 0.13) -I/home/esc/anaconda/include/python2.7 -c cos_doubles_wrap.c -o build/tem
In file included from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1722,
Disadvantages
from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:17,
from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/arrayobject.h:15,
Must be compiled
from cos_doubles_wrap.c:2706:
Requires
additional
only at build
time, at this problemNPY_1_7_API_VERSION"
can be overcome by shipping the
/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/npy_deprecated_api.h:11:2: warning: #warning "Using deprecated
NumPyan
API,
disablelibrary
it by( but
#defining
NPY_NO_DEPRECATED_API
gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_doubles.o build/temp.linux-x86_64-2.7/cos_doubles_wrap.o -L/home/esc/anaconda/lib
-lpython2.7
generated
C files)-o /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/swig_numpy/_cos_do
$ ls
build/
cos_doubles.h cos_doubles.py
cos_doubles_wrap.c setup.py
cos_doubles.c cos_doubles.i _cos_doubles.so* numpy.i
test_cos_doubles.py
14.5.1 Example
The main Cython code for our cos_module is contained in the file cos_module.pyx:
import numpy as np
import pylab
import cos_doubles
""" Example of wrapping cos function from math.h using Cython. """
cdef extern from "math.h":
double cos(double arg)
def cos_func(arg):
return cos(arg)
cos_doubles.cos_doubles_func(x, y)
pylab.plot(x, y)
pylab.show()
14.4. SWIG
Note the additional keywords such as cdef and extern. Also the cos_func is then pure Python.
Again we can use the standard distutils module, but this time we need some additional pieces from the
Cython.Distutils:
275
14.5. Cython
276
Additionally, it is worth noting that Cython ships with complete declarations for the C math library, which
simplifies the code above to become:
""" Simpler example of wrapping cos function from math.h using Cython. """
setup(
cmdclass={'build_ext': build_ext},
ext_modules=[Extension("cos_module", ["cos_module.pyx"])]
)
Compiling this:
In this case the cimport statement is used to import the cos function.
$ cd advanced/interfacing_with_c/cython
$ ls
cos_module.pyx setup.py
$ python setup.py build_ext --inplace
14.5.2 Numpy Support
running build_ext
cythoning cos_module.pyx to cos_module.c
Cython has support for Numpy via the numpy.pyx file which allows you to add the Numpy array type to your
building 'cos_module' extension
Cython code. I.e. like specifying that variable i is of type int, you can specify that variable a is of type
creating build
numpy.ndarray with a given dtype. Also, certain optimizations such as bounds checking are supported. Look
creating build/temp.linux-x86_64-2.7
at the corresponding section in the Cython documentation. In case you want to pass Numpy arrays as C arrays
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/temp.linux-x86_64-2.7/cos_module.o
to your Cython wrapped C functions, there is a section about this in the Cython wiki.
gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/cython/cos_module.so
$ ls
In the following example, we will show how to wrap the familiar cos_doubles function using Cython.
build/ cos_module.c cos_module.pyx cos_module.so* setup.py
void cos_doubles(double * in_array, double * out_array, int size);
And running it:
# include <math.h>
In [1]: import cos_module
In [2]: cos_module?
Type:
module
String Form:<module 'cos_module' from 'cos_module.so'>
File:
/home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/cython/cos_module.so
Docstring: <no docstring>
In [3]: dir(cos_module)
Out[3]:
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'__test__',
'cos_func']
In [4]: cos_module.cos_func(1.0)
Out[4]: 0.5403023058681398
In [5]: cos_module.cos_func(0.0)
Out[5]: 1.0
In [6]: cos_module.cos_func(3.14159265359)
Out[6]: -1.0
And, testing a little for robustness, we can see that we get good error messages:
In [7]: cos_module.cos_func('foo')
--------------------------------------------------------------------------TypeError
Traceback (most recent call last)
<ipython-input-7-11bee483665d> in <module>()
----> 1 cos_module.cos_func('foo')
14.5. Cython
277
14.5. Cython
278
Of all three presented techniques, Cython is the most modern and advanced. In particular, the ability to optimize code incrementally by adding types to your Python code is unique.
setup(
cmdclass={'build_ext': build_ext},
ext_modules=[Extension("cos_doubles",
sources=["_cos_doubles.pyx", "cos_doubles.c"],
include_dirs=[numpy.get_include()])],
)
As with the previous compiled Numpy examples, we need the include_dirs option.
$ ls
cos_doubles.c cos_doubles.h _cos_doubles.pyx setup.py test_cos_doubles.py
$ python setup.py build_ext -i
running build_ext
14.8 Exercises
cythoning _cos_doubles.pyx to _cos_doubles.c
building 'cos_doubles' extension
creating build
Since this is a brand new section, the exercises are considered more as pointers as to what to look at next, so
creating build/temp.linux-x86_64-2.7
pick the ones that you find more interesting. If you have good ideas for exercises, please let us know!
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/anaconda/include/python2.7 -c _cos_doubles.c -o build/temp.li
1. Download the source code for each example and compile and run them on your machine.
In file included from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1722,
from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:17,
2. Make trivial changes to each example and convince yourself that this works. ( E.g. change cos for sin.)
from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/arrayobject.h:15,
from _cos_doubles.c:253:
3. Most of the examples, especially the ones involving Numpy may still be fragile and respond badly to
/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/npy_deprecated_api.h:11:2: warning: #warning "Using deprecated
NumPy
API,
disable
it by
#defining
NPY_NO_DEPRECATED_API
input
errors.
Look
for ways
to crash
the examples,
figure what the NPY_1_7_API_VERSION"
problem is and devise a potential
/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/__ufunc_api.h:236: warning: _import_umath defined but not solution.
used
Here are some ideas:
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/anaconda/include/python2.7 -c cos_doubles.c -o build/temp.lin
gcc -pthread -shared build/temp.linux-x86_64-2.7/_cos_doubles.o build/temp.linux-x86_64-2.7/cos_doubles.o -L/home/esc/anaconda/lib -lpython2.7
-o /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/cython_numpy/cos_doubl
(a) Numerical
overflow.
$ ls
(b) Input and output arrays that have different lengths.
build/ _cos_doubles.c cos_doubles.c cos_doubles.h _cos_doubles.pyx cos_doubles.so* setup.py test_cos_doubles.py
import numpy as np
import pylab
import cos_doubles
14.8.1 Python-C-API
cos_doubles.cos_doubles_func(x, y)
pylab.plot(x, y)
pylab.show()
1. Modify the Numpy example such that the function takes two input arguments, where the second is the
preallocated output array, making it similar to the other Numpy examples.
2. Modify the example such that the function only takes a single input array and modifies this in place.
3. Try to fix the example to use the new Numpy iterator protocol. If you manage to obtain a working solution, please submit a pull-request on github.
4. You may have noticed, that the Numpy-C-API example is the only Numpy example that does not wrap
cos_doubles but instead applies the cos function directly to the elements of the Numpy array. Does
this have any advantages over the other techniques.
5. Can you wrap cos_doubles using only the Numpy-C-API. You may need to ensure that the arrays have
the correct type, are one dimensional and contiguous in memory.
14.6 Summary
In this section four different techniques for interfacing with native code have been presented. The table below
roughly summarizes some of the aspects of the techniques.
x
Python-C-API
Ctypes
Swig
Cython
14.6. Summary
Part of CPython
True
True
False
False
Compiled
True
False
True
True
Autogenerated
False
False
True
True
Numpy Support
True
True
True
True
14.8.2 Ctypes
1. Modify the Numpy example such that cos_doubles_func handles the preallocation for you, thus making it more like the Numpy-C-API example.
279
280
14.8.3 SWIG
1. Look at the code that SWIG autogenerates, how much of it do you understand?
2. Modify the Numpy example such that cos_doubles_func handles the preallocation for you, thus making it more like the Numpy-C-API example.
3. Modify the cos_doubles C function so that it returns an allocated array. Can you wrap this using SWIG
typemaps? If not, why not? Is there a workaround for this specific situation? (Hint: you know the size of
the output array, so it may be possible to construct a Numpy array from the returned double *.)
14.8.4 Cython
1. Look at the code that Cython autogenerates. Take a closer look at some of the comments that Cython
inserts. What do you see?
2. Look at the section Working with Numpy from the Cython documentation to learn how to incrementally
optimize a pure python script that uses Numpy.
3. Modify the Numpy example such that cos_doubles_func handles the preallocation for you, thus making it more like the Numpy-C-API example.
Part III
14.8. Exercises
281
282
This part of the Scipy lecture notes is dedicated to various scientific packages useful for extended needs.
15
Statistics in Python
283
284
Reading from a CSV file: Using the above CSV file that gives observations of brain size and weight and IQ
(Willerman et al. 1991), the data are a mixture of numerical and categorical values:
Contents
B Missing values
The weight of the second individual is missing in the CSV file. If we dont specify the missing value (NA = not
available) marker, we will not be able to do statistical analysis.
In this document, the Python inputs are represented with the sign >>>.
Creating from arrays: A pandas.DataFrame can also be seen as a dictionary of 1D series, eg arrays or lists. If
we have 3 numpy arrays:
>>>
>>>
>>>
>>>
import numpy as np
t = np.linspace(-6, 6, 20)
sin_t = np.sin(t)
cos_t = np.cos(t)
Other inputs: pandas can input data from SQL, excel files, or other formats. See the pandas documentation.
Manipulating data
data is a pandas.DataFrame, that resembles Rs dataframe:
Separator
>>> data.shape
(40, 8)
285
286
Exercise
What is the mean value for VIQ for the full population?
How many males/females were included in this study?
Hint use tab completion to find out the methods that can be called, instead of mean in the above
example.
What is the average value of MRI counts expressed in log units, for males and females?
For a quick view on a large dataframe, use its describe method: pandas.DataFrame.describe().
Plotting data
Pandas comes with some plotting tools (pandas.tools.plotting, using matplotlib behind the scene) to display statistics of the data in dataframes:
Scatter matrices:
groupby_gender is a powerful object that exposes many operations on the resulting group of dataframes:
>>> groupby_gender.mean()
Unnamed: 0
FSIQ
Gender
Female
19.65 111.9
Male
21.35 115.0
VIQ
PIQ
Weight
Height
MRI_Count
109.45
115.25
110.45
111.60
137.200000
166.444444
65.765000
71.431579
862654.6
954855.4
Use tab-completion on groupby_gender to find more. Other common grouping functions are median, count
(useful for checking to see the amount of missing values in different subsets) or sum. Groupby evaluation is
lazy, no work is done until an aggregation function is applied.
Two populations
The IQ metrics are bimodal, as if there are 2 sub-populations.
287
288
Exercise
Plot the scatter matrix for males only, and for females only. Do you think that the 2 sub-populations
correspond to gender?
scipy.stats.ttest_1samp() tests if the population mean of data is likely to be equal to a given value (technically if observations are drawn from a Gaussian distributions of given population mean). It returns the T
statistic, and the p-value (see the functions help):
>>> stats.ttest_1samp(data['VIQ'], 0)
(...30.088099970..., 1.32891964...e-28)
With a p-value of 10^-28 we can claim that the population mean for the IQ (VIQ measure) is not 0.
For simple statistical tests, we will use the scipy.stats sub-module of scipy:
>>> from scipy import stats
See also:
We have seen above that the mean VIQ in the male and female populations were different. To test if this is
significant, we do a 2-sample t-test with scipy.stats.ttest_ind():
Scipy is a vast library. For a quick summary to the whole library, see the scipy chapter.
289
290
PIQ, VIQ, and FSIQ give 3 measures of IQ. Let us test if FISQ
and PIQ are significantly different. We can use a 2 sample test:
>>> stats.ttest_ind(data['FSIQ'], data['PIQ'])
(...0.46563759638..., 0.64277250...)
The problem with this approach is that it forgets that there are links between observations: FSIQ and PIQ are
measured on the same individuals. Thus the variance due to inter-subject variability is confounding, and can
be removed, using a paired test, or repeated measures test:
>>> stats.ttest_rel(data['FSIQ'], data['PIQ'])
(...1.784201940..., 0.082172638183...)
T-tests assume Gaussian errors. We can use a Wilcoxon signed-rank test, that relaxes this assumption:
>>> stats.wilcoxon(data['FSIQ'], data['PIQ'])
(274.5, 0.106594927...)
import numpy as np
x = np.linspace(-5, 5, 20)
np.random.seed(1)
# normal distributed noise
y = -5 + 3*x + 4 * np.random.normal(size=x.shape)
# Create a data frame containing all the relevant variables
data = pandas.DataFrame({'x': x, 'y': y})
The corresponding test in the non paired case is the MannWhitney U test, scipy.stats.mannwhitneyu().
Exercice
Test the difference between weights in males and females.
Use non parametric statistics to test the difference between VIQ in males and females.
Conclusion: we find that the data does not support the hypothesis that males and females have different
VIQ.
291
292
Date:
...
Prob (F-statistic):
0.445
Time:
...
Log-Likelihood:
-182.42
No. Observations:
40
AIC:
368.8
Df Residuals:
38
BIC:
372.2
Df Model:
1
==========================...
coef
std err
t
P>|t|
[95.0% Conf. Int.]
-----------------------------------------------------------------------...
Intercept
109.4500
5.308
20.619
0.000
98.704
120.196
Gender[T.Male]
5.8000
7.507
0.773
0.445
-9.397
20.997
==========================...
Omnibus:
26.188
Durbin-Watson:
1.709
Prob(Omnibus):
0.000
Jarque-Bera (JB):
3.703
Skew:
0.010
Prob(JB):
0.157
Kurtosis:
1.510
Cond. No.
2.62
==========================...
Terminology:
Statsmodel uses a statistical terminology: the y variable in statsmodel is called endogenous while the x
variable is called exogenous. This is discussed in more detail here.
To simplify, y (endogenous) is the value you are trying to predict, while x (exogenous) represents the
features you are using to make the prediction.
Intercept: We can remove the intercept using - 1 in the formula, or force the use of an intercept using +
1.
By default, statsmodel treats a categorical variable with K possible values as K-1 dummy boolean
variables (the last level being absorbed into the intercept term). This is almost always a good
default choice - however, it is possible to specify different encodings for categorical variables
(http://statsmodels.sourceforge.net/devel/contrasts.html).
Exercise
Retrieve the estimated parameters from the model above. Hint: use tab-completion to find the relevent
attribute.
We can write a comparison between IQ of male and female using a linear model:
>>> model = ols("VIQ ~ Gender + 1", data).fit()
>>> print(model.summary())
OLS Regression Results
==========================...
Dep. Variable:
VIQ
R-squared:
Model:
OLS
Adj. R-squared:
Method:
Least Squares
F-statistic:
0.015
-0.010
0.5969
293
294
120.781
7.943
We can see that we retrieve the same values for t-test and corresponding p-values for the effect of the
type of iq than the previous t-test:
>>> stats.ttest_ind(data['FSIQ'], data['PIQ'])
(...0.46563759638..., 0.64277250...)
Consider a linear model explaining a variable z (the dependent variable) with 2 variables x and y:
z = x c1 + y c2 + i + e
295
296
Exercice
Going back to the brain size + IQ data, test if the VIQ of male and female are different after removing the
effect of brain size, height and weight.
SOUTH
0
0
0
0
SEX
1
1
0
0
EXPERIENCE
21
42
1
4
UNION
0
0
0
0
WAGE
0.707570
0.694605
0.824126
0.602060
AGE
35
57
19
22
RACE
2
3
3
3
To switch back to seaborn settings, or understand better styling in seaborn, see the relevent section of
the seaborn documentation.
297
298
The plot above is made of two different fits. We need to formulate a single model that tests for a variance of
slope across the to population. This is done via an interaction.
A regression capturing the relation between one variable and another, eg wage and eduction, can be plotted
using seaborn.lmplot():
>>> seaborn.lmplot(y='WAGE', x='EDUCATION', data=data)
Robust regression
Hypothesis testing and p-value give you the significance of an effect / difference
Formulas (with categorical variables) enable you to express rich links in your data
Visualizing your data and simple model fits matters!
Conditionning (adding factors that can explain all or part of the variation) is important modeling
aspect that changes the interpretation.
Given that, in the above plot, there seems to be a couple of data points that are outside of the main cloud
to the right, they might be outliers, not representative of the population, but driving the regression.
To compute a regression that is less sentive to outliers, one must use a robust model. This is done in
seaborn using robust=True in the plotting functions, or in statsmodels by replacing the use of the OLS
by a Robust Linear Model, statsmodels.formula.api.rlm().
299
300
16
The Rational class represents a rational number as a pair of two Integers: the numerator and the denominator,
so Rational(1,2) represents 1/2, Rational(5,2) 5/2 and so on:
>>> from sympy import *
>>> a = Rational(1,2)
>>> a
1/2
>>> a*2
1
What is SymPy? SymPy is a Python library for symbolic mathematics. It aims to be an alternative to systems
such as Mathematica or Maple while keeping the code as simple as possible and easily extensible. SymPy is
written entirely in Python and does not require any external libraries.
Sympy documentation and packages for installation can be found on http://www.sympy.org/
SymPy uses mpmath in the background, which makes it possible to perform computations using arbitraryprecision arithmetic. That way, some special constants, like e, pi, oo (Infinity), are treated as symbols and can
be evaluated with arbitrary precision:
>>> pi**2
2
pi
>>> pi.evalf()
3.14159265358979
>>> (pi + exp(1)).evalf()
5.85987448204884
Chapters contents
16.1.2 Exercises
1. Calculate
p
2 with 100 decimals.
16.1.3 Symbols
In contrast to other Computer Algebra Systems, in SymPy you have to declare symbolic variables explicitly:
>>> from sympy import *
>>> x = Symbol('x')
>>> y = Symbol('y')
301
302
16.3 Calculus
2
(x + y)
Symbols can now be manipulated using some of python operators: +, -, *, ** (arithmetic), &, |, ~ , >>, <<
(boolean).
Printing
16.3.1 Limits
Limits are easy to use in SymPy, they follow the syntax limit(function, variable, point), so to compute the limit
of f (x) as x 0, you would issue limit(f, x, 0):
>>> limit(sin(x)/x, x, 0)
1
SymPy is capable of performing powerful algebraic manipulations. Well take a look into some of the most
frequently used: expand and simplify.
16.2.1 Expand
>>> limit(x**x, x, 0)
1
16.3.2 Differentiation
Use this to expand an algebraic expression. It will try to denest powers and multiplications:
You can differentiate any SymPy expression using diff(func, var). Examples:
>>> diff(sin(x), x)
cos(x)
>>> diff(sin(2*x), x)
2*cos(2*x)
>>> diff(tan(x), x)
2
tan (x) + 1
16.2.2 Simplify
>>> diff(sin(2*x), x, 2)
-4*sin(2*x)
Use simplify if you would like to transform an expression into a simpler form:
>>> diff(sin(2*x), x, 3)
-8*cos(2*x)
Simplification is a somewhat vague term, and more precises alternatives to simplify exists: powsimp (simplification of exponents), trigsimp (for trigonometric expressions) , logcombine, radsimp, together.
Exercises
>>> series(cos(x), x)
2
4
x
x
/ 6\
1 - -- + -- + O\x /
2
24
303
16.3. Calculus
304
>>> series(1/cos(x), x)
2
4
x
5*x
/ 6\
1 + -- + ---- + O\x /
2
24
In [7]: solve(x**4 - 1, x)
Out[7]: [I, 1, -1, -I]
As you can see it takes as first argument an expression that is supposed to be equaled to 0. It is able to solve a
large part of polynomial equations, and is also capable of solving multiple equations with respect to multiple
variables giving a tuple as second argument:
In [8]: solve([x + 5*y - 2, -3*x + 6*y - 15], [x, y])
Out[8]: {y: 1, x: -3}
Exercises
1. Calculate limx0 sin(x)/x
2. Calculate the derivative of l og (x) for x.
16.3.4 Integration
SymPy has support for indefinite and definite integration of transcendental elementary and special functions
via integrate() facility, which uses powerful extended Risch-Norman algorithm and some heuristics and
pattern matching. You can integrate elementary functions:
>>> integrate(6*x**5, x)
6
x
>>> integrate(sin(x), x)
-cos(x)
>>> integrate(log(x), x)
x*log(x) - x
>>> integrate(2*x + sinh(x), x)
2
x + cosh(x)
Another alternative in the case of polynomial equations is factor. factor returns the polynomial factorized
into irreducible terms, and is capable of computing the factorization over various domains:
In [10]: f = x**4 - 3*x**2 + 1
In [11]: factor(f)
Out[11]: (1 + x - x**2)*(1 - x - x**2)
In [12]: factor(f, modulus=5)
Out[12]: (2 + x)**2*(2 - x)**2
SymPy is also able to solve boolean equations, that is, to decide if a certain boolean expression is satisfiable or
not. For this, we use the function satisfiable:
In [13]: satisfiable(x & y)
Out[13]: {x: True, y: True}
This tells us that (x & y) is True whenever x and y are both True. If an expression cannot be true, i.e. no values
of its arguments can make the expression True, it will return False:
16.4.1 Exercises
2. Are there boolean values x, y that make (~x | y) & (~y | x) true?
16.5.1 Matrices
16.3.5 Exercises
>>> x = Symbol('x')
>>> y = Symbol('y')
>>> A = Matrix([[1,x], [y,1]])
305
306
>>> A
[1 x]
[
]
[y 1]
>>> A**2
[x*y + 1
[
[ 2*y
]
]
x*y + 1]
17
2*x
f and g are now undefined functions. We can call f(x), and it will represent an unknown function:
>>> f(x)
f(x)
See also:
For basic image manipulation, such as image cropping or simple filtering, a large number of simple operations
can be realized with NumPy and SciPy only. See Image manipulation and processing using Numpy and Scipy.
Note that you should be familiar with the content of the previous chapter before reading the current one, as
basic operations such as masking and labeling are a prerequisite.
Chapters contents
Keyword arguments can be given to this function in order to help if find the best possible resolution system.
For example, if you know that it is a separable equations, you can use keyword hint=separable to force dsolve
to resolve it as a separable equation:
>>> dsolve(sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x), f(x), hint='separable')
/
_____________\
/
_____________\
|
/
C1
|
|
/
C1
|
[f(x) = - asin|
/ ------- + 1 | + pi, f(x) = asin|
/ ------- + 1 | + pi,
| /
2
|
| /
2
|
\\/
cos (x)
/
\\/
cos (x)
/
/
_____________\
/
_____________\
|
/
C1
|
|
/
C1
|
f(x) = -asin|
/ ------- + 1 |, f(x) = asin|
/ ------- + 1 |]
| /
2
|
| /
2
|
\\/
cos (x)
/
\\/
cos (x)
/
Exercises
1. Solve the Bernoulli differential equation
image np.ndarray
pixels array values: a[2, 3]
307
308
import numpy as np
check = np.zeros((9, 9))
check[::2, 1::2] = 1
check[1::2, ::2] = 1
import matplotlib.pyplot as plt
plt.imshow(check, cmap='gray', interpolation='nearest')
(but they are less Pythonic and NumPy friendly, to a variable extent).
matplotlib
or
scikit-learn):
http://scikit-
Different kinds of functions, from boilerplate utility functions to high-level recent algorithms.
Filters: functions transforming images into other images.
NumPy machinery
Common filtering algorithms
Data reduction functions: computation of image histogram, position of local maxima, of corners, etc.
Other actions: I/O, visualization, etc.
Other Python packages are available for image processing and work with NumPy arrays:
scipy.ndimage : for nd-arrays. Basic filtering, mathematical morphology, regions properties
Mahotas
Saving to files:
309
310
Routines converting between different colorspaces (RGB, HSV, LAB etc.) are available in skimage.color :
color.rgb2hsv, color.lab2rgb, etc. Check the docstring for the expected dtype (and data range) of input
images.
3D images
Most functions of skimage can take 3D images as input arguments. Check the docstring to know if a
function can be used on 3D images (for example MRI or CT images).
Exercise
Open a color image on your disk as a NumPy array.
Find a skimage function computing the histogram of an image and plot the histogram of
each color channel
Convert the image to grayscale and plot its histogram.
Different integer sizes are possible: 8-, 16- or 32-bytes, signed or unsigned.
B An important (if questionable) skimage convention: float images are supposed to lie in [-1, 1] (in order to have
Local filters replace the value of pixels by a function of the values of neighboring pixels. The function can be
linear or non-linear.
Neighbourhood: square (choose size), disk, or more complicated structuring element.
Some image processing routines need to work with float arrays, and may hence output an array with a different
type and the data range from the input array
>>> try:
...
from skimage import filters
... except ImportError:
...
from skimage import filter as filters
>>> camera_sobel = filters.sobel(camera)
>>> camera_sobel.max()
0.591502...
B In the example above, we use the filters submodule of scikit-image, that has been renamed from filter to
filters between versions 0.10 and 0.11, in order to avoid a collision with Pythons built-in name filter.
Utility functions are provided in skimage to convert both the dtype and the data range, following skimages
conventions: util.img_as_float, util.img_as_ubyte, etc.
See the user guide for more details.
2
0
-2
1
0
-1
17.2.2 Colorspaces
Color images are of shape (N, M, 3) or (N, M, 4) (when an alpha channel encodes transparency)
>>> face = scipy.misc.face()
>>> face.shape
(768, 1024, 3)
311
312
Non-local filters use a large region of the image (or all the image) to transform the value of one pixel:
>>> from skimage import exposure
>>> camera = data.camera()
>>> camera_equalized = exposure.equalize_hist(camera)
Erosion = minimum filter. Replace the value of a pixel by the minimal value covered by the structuring element.:
>>> a = np.zeros((7,7), dtype=np.int)
>>> a[1:6, 2:5] = 1
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])
313
314
n = 20
l = 256
im = np.zeros((l, l))
points = l * np.random.random((2, n ** 2))
im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
im = filters.gaussian_filter(im, sigma=l / (4. * n))
blobs = im > im.mean()
See also:
315
316
Watershed segmentation
The Watershed (skimage.morphology.watershed()) is a region-growing approach that fills basins in the
image
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
Exercise
Load the coins image from the data submodule.
Separate the coins from the background by testing several segmentation methods: Otsu thresholding, adaptive thresholding, and watershed or random walker segmentation.
If necessary, use a postprocessing function to improve the coins / background segmentation.
Example: compute the size and perimeter of the two segmented regions:
>>> properties = measure.regionprops(labels_rw)
>>> [prop.area for prop in properties]
[770.0, 1168.0]
>>> [prop.perimeter for prop in properties]
[100.91..., 126.81...]
See also:
for some properties, functions are available as well in scipy.ndimage.measurements with a different API (a
list is returned).
Exercise (continued)
Use the binary image of the coins and background from the previous exercise.
Compute an image of labels for the different coins.
Compute the size and eccentricity of all coins.
skimage provides several utility functions that can be used on label images (ie images where
different discrete values identify different regions). Functions names are often self-explaining:
skimage.segmentation.clear_border(),
skimage.segmentation.relabel_from_one(),
skimage.morphology.remove_small_objects(), etc.
>>> plt.figure()
<matplotlib.figure.Figure object at 0x...>
>>> plt.imshow(clean_border, cmap='gray')
<matplotlib.image.AxesImage object at 0x...>
Visualize contour
>>> plt.figure()
<matplotlib.figure.Figure object at 0x...>
>>> plt.imshow(coins, cmap='gray')
<matplotlib.image.AxesImage object at 0x...>
>>> plt.contour(clean_border, [0.5])
<matplotlib.contour.QuadContourSet ...>
317
318
new_viewer = viewer.ImageViewer(coins)
from skimage.viewer.plugins import lineprofile
new_viewer += lineprofile.LineProfile()
new_viewer.show()
319
320
18
Requirements
Tutorial content
(this example is taken from the plot_corner example in scikit-image)
Points of interest such as corners can then be used to match objects in different images, as described in the
plot_matching example of scikit-image.
321
Introduction
Example
What are Traits
Initialisation
Validation
Documentation
Visualization: opening a dialog
Deferral
Notification
Some more advanced traits
322
18.1 Introduction
The Enthought Tool Suite enable the construction of sophisticated application frameworks for data analysis,
2D plotting and 3D visualization. These powerful, reusable components are released under liberal BSD-style
licenses.
Initialization
Validation
Kiva - 2D primitives supporting path based rendering, affine transforms, alpha blending and more.
Deferral
Notification
Visualization
Documentation
Envisage - application plugin framework for building scriptable and extensible applications
A class can freely mix trait-based attributes with normal Python attributes, or can opt to allow the use of only
a fixed or open set of trait attributes within the class. Trait attributes defined by a class are automatically
inherited by any subclass derived from the class.
18.2 Example
The common way of creating a traits class is by extending from the HasTraits base class and defining class
traits :
Throughout this tutorial, we will use an example based on a water resource management simple case. We will
try to model a dam and reservoir system. The reservoir and the dams do have a set of parameters :
Name
18.1. Introduction
323
324
If using Traits 3.x, you need to adapt the namespace of the traits packages:
traits.api should be enthought.traits.api
traitsui.api should be enthought.traits.ui.api
Using a traits class like that is as simple as any other Python class. Note that the trait value are passed using
keyword arguments:
TraitError: The 'max_storage' trait of a Reservoir instance must be a float, but a value of '23' <type 'str'> wa
18.3.1 Initialisation
18.3.3 Documentation
All the traits do have a default value that initialise the variables. For example, the basic python types do have
the following trait equivalents:
By essence, all the traits do provide documentation about the model itself. The declarative approach to the
creation of classes makes it self-descriptive:
Trait
Python Type
Bool
Complex
Float
Int
Long
Str
Unicode
Boolean
Complex number
Floating point number
Plain integer
Long integer
String
Unicode
False
0+0j
0.0
0
0L
class Reservoir(HasTraits):
name = Str
max_storage = Float(100)
The desc metadata of the traits can be used to provide a more descriptive information about the trait :
from traits.api import HasTraits, Str, Float
A number of other predefined trait type do exist : Array, Enum, Range, Event, Dict, List, Color, Set, Expression,
Code, Callable, Type, Tuple, etc.
class Reservoir(HasTraits):
name = Str
max_storage = Float(100, desc='Maximal storage [hm3]')
class Reservoir(HasTraits):
name = Str
max_storage = Float(100)
class Reservoir(HasTraits):
name = Str
max_storage = Float(1e6, desc='Maximal storage [hm3]')
max_release = Float(10, desc='Maximal release [m3/s]')
head = Float(10, desc='Hydraulic head [m]')
efficiency = Range(0, 1.)
Complex initialisation
When a complex initialisation is required for a trait, a _XXX_default magic method can be implemented.
It will be lazily called when trying to access the XXX trait. For example:
def _name_default(self):
""" Complex initialisation of the reservoir name. """
return 'Undefined'
if __name__ == '__main__':
reservoir = Reservoir(
name = 'Project A',
max_storage = 30,
max_release = 100.0,
head = 60,
efficiency = 0.8
)
18.3.2 Validation
Every trait does validation when the user tries to set its content:
reservoir = Reservoir(name='Lac de Vouglans', max_storage=605)
reservoir.max_storage = '230'
--------------------------------------------------------------------------TraitError
Traceback (most recent call last)
.../scipy-lecture-notes/advanced/traits/<ipython-input-7-979bdff9974a> in <module>()
----> 1 reservoir.max_storage = '230'
release = 80
print 'Releasing {} m3/s produces {} kWh'.format(
release, reservoir.energy_production(release)
)
325
326
reservoir.configure_traits()
The Traits library is also aware of user interfaces and can pop up a default view for the Reservoir class:
reservoir1 = Reservoir()
reservoir1.edit_traits()
18.3.5 Deferral
Being able to defer the definition of a trait and its value to another object is a powerful feature of Traits.
from traits.api import HasTraits, Instance, DelegatesTo, Float, Range
from reservoir import Reservoir
TraitsUI simplifies the way user interfaces are created. Every trait on a HasTraits class has a default editor that
will manage the way the trait is rendered to the screen (e.g. the Range trait is displayed as a slider, etc.).
In the very same vein as the Traits declarative way of creating classes, TraitsUI provides a declarative interface
to build user interfaces code:
from traits.api import HasTraits, Str, Float, Range
from traitsui.api import View
class Reservoir(HasTraits):
name = Str
max_storage = Float(1e6, desc='Maximal storage [hm3]')
max_release = Float(10, desc='Maximal release [m3/s]')
head = Float(10, desc='Hydraulic head [m]')
efficiency = Range(0, 1.)
# state attributes
storage = Range(low='min_storage', high='max_storage')
# control attributes
inflows = Float(desc='Inflows [hm3]')
release = Range(low='min_release', high='max_release')
spillage = Float(desc='Spillage [hm3]')
traits_view = View(
'name', 'max_storage', 'max_release', 'head', 'efficiency',
title = 'Reservoir',
resizable = True,
)
def print_state(self):
print 'Storage\tRelease\tInflows\tSpillage'
str_format = '\t'.join(['{:7.2f}'for i in range(4)])
print str_format.format(self.storage, self.release, self.inflows,
self.spillage)
print '-' * 79
if __name__ == '__main__':
projectA = Reservoir(
name = 'Project A',
max_storage = 30,
max_release = 100.0,
hydraulic_head = 60,
efficiency = 0.8
)
if __name__ == '__main__':
reservoir = Reservoir(
name = 'Project A',
max_storage = 30,
max_release = 100.0,
head = 60,
efficiency = 0.8
)
class ReservoirState(HasTraits):
"""Keeps track of the reservoir state given the initial storage.
"""
reservoir = Instance(Reservoir, ())
min_storage = Float
max_storage = DelegatesTo('reservoir')
min_release = Float
max_release = DelegatesTo('reservoir')
327
328
state.update_storage = True
state.print_state()
A special trait allows to manage events and trigger function calls using the magic _xxxx_fired method:
Dependency between objects can be made automatic using the trait Property. The depends_on attribute
expresses the dependency between the property and other traits. When the other traits gets changed, the
property is invalidated. Again, Traits uses magic method names for the property :
class ReservoirState(HasTraits):
"""Keeps track of the reservoir state given the initial storage.
# state attributes
storage = Range(low='min_storage', high='max_storage')
# control attributes
inflows = Float(desc='Inflows [hm3]')
release = Range(low='min_release', high='max_release')
spillage = Float(desc='Spillage [hm3]')
# state attributes
storage = Property(depends_on='inflows, release')
# control attributes
inflows = Float(desc='Inflows [hm3]')
release = Range(low='min_release', high='max_release')
spillage = Property(
desc='Spillage [hm3]', depends_on=['storage', 'inflows', 'release']
)
def _update_storage_fired(self):
# update storage state
new_storage = self.storage - self.release + self.inflows
self.storage = min(new_storage, self.max_storage)
overflow = new_storage - self.max_storage
self.spillage = max(overflow, 0)
def print_state(self):
print 'Storage\tRelease\tInflows\tSpillage'
str_format = '\t'.join(['{:7.2f}'for i in range(4)])
print str_format.format(self.storage, self.release, self.inflows,
self.spillage)
print '-' * 79
if __name__ == '__main__':
projectA = Reservoir(
name = 'Project A',
max_storage = 30,
max_release = 5.0,
hydraulic_head = 60,
efficiency = 0.8
)
def _get_spillage(self):
new_storage = self._storage - self.release
overflow = new_storage - self.max_storage
return max(overflow, 0)
+ self.inflows
def print_state(self):
print 'Storage\tRelease\tInflows\tSpillage'
str_format = '\t'.join(['{:7.2f}'for i in range(4)])
print str_format.format(self.storage, self.release, self.inflows,
self.spillage)
print '-' * 79
if __name__ == '__main__':
projectA = Reservoir(
name = 'Project A',
max_storage = 30,
329
330
max_release = 5,
hydraulic_head = 60,
efficiency = 0.8
Caching property
Heavy computation or long running computation might be a problem when accessing a property where the
inputs have not changed. The @cached_property decorator can be used to cache the value and only recompute
them once invalidated.
Lets extend the TraitsUI introduction with the ReservoirState example:
from traits.api import HasTraits, Instance, DelegatesTo, Float, Range, Property
from traitsui.api import View, Item, Group, VGroup
from reservoir import Reservoir
class ReservoirState(HasTraits):
"""Keeps track of the reservoir state given the initial storage.
+ self.inflows
def print_state(self):
print 'Storage\tRelease\tInflows\tSpillage'
str_format = '\t'.join(['{:7.2f}'for i in range(4)])
print str_format.format(self.storage, self.release, self.inflows,
self.spillage)
print '-' * 79
if __name__ == '__main__':
projectA = Reservoir(
name = 'Project A',
max_storage = 30,
max_release = 5,
hydraulic_head = 60,
efficiency = 0.8
)
state = ReservoirState(reservoir=projectA, storage=25)
state.release = 4
state.inflows = 0
state.print_state()
state.configure_traits()
# state attributes
storage = Property(depends_on='inflows, release')
# control attributes
inflows = Float(desc='Inflows [hm3]')
release = Range(low='min_release', high='max_release')
spillage = Property(
desc='Spillage [hm3]', depends_on=['storage', 'inflows', 'release']
)
### Traits view
traits_view = View(
Group(
VGroup(Item('name'), Item('storage'), Item('spillage'),
label = 'State', style = 'readonly'
),
VGroup(Item('inflows'), Item('release'), label='Control'),
)
)
Some use cases need the delegation mechanism to be broken by the user when setting the value of the trait.
The PrototypeFrom trait implements this behaviour.
from traits.api import HasTraits, Str, Float, Range, PrototypedFrom, Instance
class Turbine(HasTraits):
turbine_type = Str
power = Float(1.0, desc='Maximal power delivered by the turbine [Mw]')
class Reservoir(HasTraits):
name = Str
max_storage = Float(1e6, desc='Maximal storage [hm3]')
331
332
def print_state(self):
print 'Storage\tRelease\tInflows\tSpillage'
str_format = '\t'.join(['{:7.2f}'for i in range(4)])
print str_format.format(self.storage, self.release, self.inflows,
self.spillage)
print '-' * 79
turbine = Instance(Turbine)
installed_capacity = PrototypedFrom('turbine', 'power')
if __name__ == '__main__':
turbine = Turbine(turbine_type='type1', power=5.0)
reservoir = Reservoir(
name = 'Project A',
max_storage = 30,
max_release = 100.0,
head = 60,
efficiency = 0.8,
turbine = turbine,
)
if new > 0:
print 'Warning, we are releasing {} hm3 of water'.format(new)
if __name__ == '__main__':
projectA = Reservoir(
name = 'Project A',
max_storage = 30,
max_release = 100.0,
hydraulic_head = 60,
efficiency = 0.8
)
print '-' * 15
print 'setting the installed capacity breaks the link between turbine.power'
print 'and the installed_capacity trait'
reservoir.installed_capacity = 8
print turbine.power, reservoir.installed_capacity
18.3.6 Notification
Traits implements a Listener pattern. For each trait a list of static and dynamic listeners can be fed with callbacks. When the trait does change, all the listeners are called.
To listen to all the changes on a HasTraits class, the magic _any_trait_changed method can be implemented.
In many situations, you do not know in advance what type of listeners need to be activated. Traits offers the
ability to register listeners on the fly with the dynamic listeners
class ReservoirState(HasTraits):
"""Keeps track of the reservoir state given the initial storage.
"""
reservoir = Instance(Reservoir, ())
min_storage = Float
max_storage = DelegatesTo('reservoir')
min_release = Float
max_release = DelegatesTo('reservoir')
# state attributes
storage = Range(low='min_storage', high='max_storage')
# control attributes
inflows = Float(desc='Inflows [hm3]')
release = Range(low='min_release', high='max_release')
spillage = Float(desc='Spillage [hm3]')
333
334
_storage = Float
state.release = 90
state.inflows = 0
state.print_state()
def _get_spillage(self):
new_storage = self._storage - self.release
overflow = new_storage - self.max_storage
return max(overflow, 0)
+ self.inflows
@on_trait_change('storage')
def print_state(self):
print 'Storage\tRelease\tInflows\tSpillage'
str_format = '\t'.join(['{:7.2f}'for i in range(4)])
print str_format.format(self.storage, self.release, self.inflows,
self.spillage)
print '-' * 79
The dynamic trait notification signatures are not the same as the static ones :
def wake_up_watchman(): pass
def wake_up_watchman(new): pass
def wake_up_watchman(name, new): pass
if __name__ == '__main__':
projectA = Reservoir(
name = 'Project A',
max_storage = 30,
max_release = 5,
hydraulic_head = 60,
efficiency = 0.8
)
The patterns supported by the on_trait_change method and decorator are powerful. The reader should look at
the docstring of HasTraits.on_trait_change for the details.
class ReservoirState(HasTraits):
"""Keeps track of the reservoir state given the initial storage.
The following example demonstrate the usage of the Enum and List traits :
# state attributes
storage = Property(depends_on='inflows, release')
class Reservoir(HasTraits):
name = Str
max_storage = Float(1e6, desc='Maximal storage [hm3]')
max_release = Float(10, desc='Maximal release [m3/s]')
head = Float(10, desc='Hydraulic head [m]')
efficiency = Range(0, 1.)
irrigated_areas = List(IrrigationArea)
# control attributes
inflows = Float(desc='Inflows [hm3]')
release = Range(low='min_release', high='max_release')
spillage = Property(
desc='Spillage [hm3]', depends_on=['storage', 'inflows', 'release']
)
335
336
'''
power = 1000 * 9.81 * self.head * release * self.efficiency
return power * 3600
traits_view = View(
Item('name'),
Item('max_storage'),
Item('max_release'),
Item('head'),
Item('efficiency'),
Item('irrigated_areas'),
Item('total_crop_surface'),
resizable = True
)
traits_view = View(
Item('name'),
Item('max_storage'),
Item('max_release'),
Item('head'),
Item('efficiency'),
Item('irrigated_areas'),
resizable = True
)
if __name__ == '__main__':
upper_block = IrrigationArea(name='Section C', surface=2000, crop='Wheat')
if __name__ == '__main__':
upper_block = IrrigationArea(name='Section C', surface=2000, crop='Wheat')
reservoir = Reservoir(
name='Project A',
max_storage=30,
max_release=100.0,
head=60,
efficiency=0.8,
irrigated_areas=[upper_block],
)
reservoir = Reservoir(
name='Project A',
max_storage=30,
max_release=100.0,
head=60,
efficiency=0.8,
irrigated_areas=[upper_block]
)
release = 80
print 'Releasing {} m3/s produces {} kWh'.format(
release, reservoir.energy_production(release)
)
release = 80
print 'Releasing {} m3/s produces {} kWh'.format(
release, reservoir.energy_production(release)
)
The next example shows how the Array trait can be used to feed a specialised TraitsUI Item, the ChacoPlotItem:
Trait listeners can be used to listen to changes in the content of the list to e.g. keep track of the total crop
surface on linked to a given reservoir.
from traits.api import HasTraits, Str, Float, Range, Enum, List, Property
from traitsui.api import View, Item
class IrrigationArea(HasTraits):
name = Str
surface = Float(desc='Surface [ha]')
crop = Enum('Alfalfa', 'Wheat', 'Cotton')
import numpy as np
from
from
from
from
class Reservoir(HasTraits):
name = Str
max_storage = Float(1e6, desc='Maximal storage [hm3]')
max_release = Float(10, desc='Maximal release [m3/s]')
head = Float(10, desc='Hydraulic head [m]')
efficiency = Range(0, 1.)
name = DelegatesTo('reservoir')
inflows = Array(dtype=np.float64, shape=(None))
releass = Array(dtype=np.float64, shape=(None))
initial_stock = Float
stock = Property(depends_on='inflows, releases, initial_stock')
irrigated_areas = List(IrrigationArea)
month = Property(depends_on='stock')
total_crop_surface = Property(depends_on='irrigated_areas.surface')
def _get_total_crop_surface(self):
return sum([iarea.surface for iarea in self.irrigated_areas])
def energy_production(self, release):
''' Returns the energy production [Wh] for the given release [m3/s]
'''
power = 1000 * 9.81 * self.head * release * self.efficiency
return power * 3600
337
338
initial_stock = 10.
inflows_ts = np.array([6., 6, 4, 4, 1, 2, 0, 0, 3, 1, 5, 3])
releases_ts = np.array([4., 5, 3, 5, 3, 5, 5, 3, 2, 1, 3, 3])
view = ReservoirEvolution(
view.configure_traits()
19
Chapters contents
Mlab: the scripting interface
3D plotting functions
* Points
* Lines
* Elevation surface
* Arbitrary regular mesh
* Volumetric data
Figures and decorations
* Figure management
* Changing plot properties
* Decorations
Interactive work
The pipeline dialog
The script recording button
Slicing and dicing data: sources, modules and filters
An example: inspecting magnetic fields
Different views on data: sources and modules
* Different sources: scatters and fields
* Transforming data: filters
* mlab.pipeline: the scripting layer
Animating the data
Making interactive dialogs
A simple dialog
Making it interactive
Putting it together
reservoir = reservoir,
inflows = inflows_ts,
releases = releases_ts
See also:
References
ETS repositories
Traits manual
The mayavi.mlab module provides simple plotting functions to apply to numpy arrays, similar to matplotlib
or matlabs plotting interface. Try using them in IPython, by starting IPython with the switch --gui=wx.
Traits UI manual
Mailing list : enthought-dev@enthought.com
339
340
mlab.clf()
x, y = np.mgrid[-10:10:100j, -10:10:100j]
r = np.sqrt(x**2 + y**2)
z = np.sin(r)/r
mlab.surf(z, warp_scale='auto')
Points
Points in 3D, represented with markers (or glyphs) and optionaly different sizes.
x, y, z, value = np.random.random((4, 40))
mlab.points3d(x, y, z, value)
Lines
mlab.clf()
phi, theta = np.mgrid[0:np.pi:11j, 0:2*np.pi:11j]
x = np.sin(phi) * np.cos(theta)
y = np.sin(phi) * np.sin(theta)
z = np.cos(phi)
mlab.mesh(x, y, z)
mlab.mesh(x, y, z, representation='wireframe', color=(0, 0, 0))
Volumetric data
Elevation surface
If your data is dense in 3D, it is more difficult to display. One option is to take iso-contours of the data.
mlab.clf()
x, y, z = np.mgrid[-5:5:64j, -5:5:64j, -5:5:64j]
values = x*x*0.5 + y*y + z*z*2.0
mlab.contour3d(values)
341
342
This function works with a regular orthogonal grid: the value array is a 3D array that gives the shape of the
grid.
mlab.gcf()
mlab.clf()
mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0.5, 0.5, 0.5)
mlab.savefig(foo.png, size=(300, 300))
mlab.view(azimuth=45, elevation=54, distance=1.)
343
x, y, z are 2D arrays, all of the same shape, giving the positions of the vertices of the surface. The connectivity between these points is implied by the connectivity on the arrays.
For simple structures (such as orthogonal grids) prefer the surf function, as it will create more efficient
data structures.
Keyword arguments:
color the color of the vtk object. Overides the colormap, if any, when specified.
This is specified as a triplet of float ranging from 0 to 1, eg (1, 1, 1) for white.
colormap type of colormap to use.
extent [xmin, xmax, ymin, ymax, zmin, zmax] Default is the x, y, z arrays extents.
Use this to change the extent of the object created.
figure Figure to populate.
line_width The with of the lines, if any used. Must be a float. Default: 2.0
mask boolean mask array to suppress some data points.
mask_points If supplied, only one out of mask_points data point is displayed.
This option is usefull to reduce the number of points displayed on large
datasets Must be an integer or None.
mode the mode of the glyphs. Must be 2darrow or 2dcircle or 2dcross
or 2ddash or 2ddiamond or 2dhooked_arrow or 2dsquare or
2dthick_arrow or 2dthick_cross or 2dtriangle or 2dvertex or arrow
or cone or cube or cylinder or point or sphere. Default: sphere
name the name of the vtk object created.
representation the representation type used for the surface. Must be surface or
wireframe or points or mesh or fancymesh. Default: surface
resolution The resolution of the glyph created. For spheres, for instance, this is
the number of divisions along theta and phi. Must be an integer. Default: 8
scalars optional scalar data.
scale_factor scale factor of the glyphs used to represent the vertices, in
fancy_mesh mode. Must be a float. Default: 0.05
scale_mode the scaling mode for the glyphs (vector, scalar, or none).
transparent make the opacity of the actor depend on the scalar.
tube_radius radius of the tubes used to represent the lines, in mesh mode. If
None, simple lines are used.
tube_sides number of sides of the tubes used to represent the lines. Must be an
integer. Default: 6
vmax vmax is used to scale the colormap If None, the max of the data will be used
vmin vmin is used to scale the colormap If None, the min of the data will be used
344
Example:
fault.
In [3]: x = r * np.cos(theta)
In [4]: y = r * np.sin(theta)
The quickest way to create beautiful visualization with Mayavi is probably to interactively tweak the various
settings.
In [5]: z = np.sin(r)/r
In [6]: from mayavi import mlab
Click on the Mayavi button in the scene, and you can control properties of objects with dialogs.
Decorations
Different items can be added to the figure to carry extra information, such as a colorbar or a title.
In [9]: mlab.colorbar(Out[7], orientation='vertical')
Out[9]: <tvtk_classes.scalar_bar_actor.ScalarBarActor object at 0xd897f8c>
In [10]: mlab.title('polar mesh')
Out[10]: <enthought.mayavi.modules.text.Text object at 0xd8ed38c>
In [11]: mlab.outline(Out[7])
Out[11]: <enthought.mayavi.modules.outline.Outline object at 0xdd21b6c>
In [12]: mlab.axes(Out[7])
Out[12]: <enthought.mayavi.modules.axes.Axes object at 0xd2e4bcc>
345
346
This can be seen by looking at the pipeline view. By right-clicking on the nodes of the pipeline, you can add
new modules.
To find out what code can be used to program these changes, click on the red button as you modify those
properties, and it will generate the corresponding lines of code.
are
simulating
the
magnetic
field
generated
Quiz
Why is it not possible to add a VectorCutPlane to the vectors created by mayavi.mlab.quiver3d()?
Suppose
by
Helmholtz
coils.
The
examples/compute_field.py script does this computation and gives you a B array, that is (3 x n),
where the first axis is the direction of the field (Bx, By, Bz), and the second axis the index number of the point.
Arrays X, Y and Z give the positions of these data points.
Excercise
Visualize this field. Your goal is to make sure that the simulation code is correct.
Suggestions
If you compute the norm of the vector field, you can apply an isosurface to it.
using mayavi.mlab.quiver3d() you can plot vectors. You can also use the masking options (in
the GUI) to make the plot a bit less dense.
1. Create a contour (for instance of the magnetic field norm) by using one of those functions and
adding the right module by clicking on the GUI dialog.
2. Create the right source to apply a vector_cut_plane and reproduce the picture of the magnetic
field shown previously.
Note that one of the difficulties is providing the data in the right form (number of arrays, shape) to the
functions. This is often the case with real-life data.
See also:
Sources are described in details in the Mayavi manual.
If you create a vector field, you may want to visualize the iso-contours of its magnitude. But the isosurface
module can only be applied to scalar data, and not vector data. We can use a filter, ExtractVectorNorm to
add this scalar value to the vector field.
Filters apply a transformation to data, and can be added between sources and modules
347
348
See also:
Excercice
Using the GUI, add the ExtractVectorNorm filter to display iso-contours of the field magnitude.
Event loops
For the interaction with the user (for instance changing the view with the mouse), Mayavi needs some
time to process these events. The for loop above prevents this. The Mayavi documentation details a
workaround
mlab.pipeline.iso_surface(mlab.pipeline.extract_vector_norm(field),
contours=[0.1*Bmax, 0.4*Bmax],
opacity=0.5)
Excercice
Using the mlab.pipeline interface, generate a complete visualization, with iso-contours of the field magnitude, and a vector cut plane.
(click on the figure for a solution)
To make movies, or interactive application, you may want to change the data represented on a given visualization.
If you have built a visualization, using the mlab plotting functions, or the mlab.pipeline function, we can
update the data by assigning new values to the mlab_source attributes
x , y , z = np.ogrid[-5:5:100j ,-5:5:100j, -5:5:100j]
scalars = np.sin(x * y * z) / (x * y * z)
iso = mlab.contour3d(scalars, transparent=True, contours=[0.5])
for i in range(1, 20):
scalars = np.sin(i * x * y * z) /(x * y * z)
iso.mlab_source.scalars = scalars
def __init__(self):
HasTraits.__init__(self)
x, y, z = curve(n_turns=2)
# Populating our plot
self.plot = self.scene.mlab.plot3d(x, y, z)
349
350
Exercise
Using the code from the magnetic field simulation, create a dialog that enable to move the 2 coils: change
their parameters.
Hint: to define a dialog entry for a vector of dimension 3
direction = Array(float, value=(0, 0, 1), cols=3, shape=(3,))
351
352
20
Numpy, Scipy
IPython
matplotlib
scikit-learn (http://scikit-learn.org)
This data is stored in the .data member, which is a (n_samples, n_features) array.
>>> iris.data.shape
(150, 4)
The class of each observation is stored in the .target attribute of the dataset. This is an integer 1D array of
length n_samples:
Chapters contents
Loading an example dataset
Learning and Predicting
Classification
k-Nearest neighbors classifier
Support vector machines (SVMs) for classification
Clustering: grouping observations together
K-means clustering
Dimension Reduction with Principal Component Analysis
Putting it all together: face recognition
Linear model: from regression to sparsity
Sparse models
Model selection: choosing estimators and their parameters
Grid-search and cross-validated estimators
>>> iris.target.shape
(150,)
>>> import numpy as np
>>> np.unique(iris.target)
array([0, 1, 2])
353
354
The digits dataset consists of 1797 images, where each one is an 8x8 pixel image representing a handwritten digit:
>>> digits = datasets.load_digits()
>>> digits.images.shape
(1797, 8, 8)
>>> import pylab as pl
>>> pl.imshow(digits.images[0], cmap=pl.cm.gray_r)
<matplotlib.image.AxesImage object at ...>
The k-nearest neighbors classifier internally uses an algorithm based on ball trees to represent the samples it
is trained on.
KNN (k-nearest neighbors) classification example:
To use this dataset with the scikit, we transform each 8x8 image into a vector of length 64:
When experimenting with learning algorithms, it is important not to test the prediction of an estimator on the data used to fit the estimator. Indeed, with the kNN estimator, we would always get perfect
prediction on the training set.
Once we have learned from the data, we can use our model to predict the most likely outcome on unseen data:
>>> clf.predict([[ 5.0,
array([0])
3.6,
1.3,
0.25]])
We can access the parameters of the model via its attributes ending with an underscore:
>>> clf.coef_
array([[ 0...]])
20.2 Classification
20.2. Classification
355
SVMs try to construct a hyperplane maximizing the margin between the two classes. It selects a subset of the
input, called the support vectors, which are the observations closest to the separating hyperplane.
20.2. Classification
356
There are several support vector machine implementations in scikit-learn. The most commonly used ones
are svm.SVC, svm.NuSVC and svm.LinearSVC; SVC stands for Support Vector Classifier (there also exist
SVMs for regression, which are called SVR in scikit-learn).
Exercise
Train an svm.SVC on the digits dataset. Leave out the last 10%, and test prediction performance on these
observations.
Ground truth
K-means (3 clusters)
K-means (8 clusters)
Using kernels
Classes are not always separable by a hyperplane, so it would be desirable to have a decision function that is
not linear but that may be for instance polynomial or exponential:
Linear kernel
Polynomial kernel
Clustering can be seen as a way of choosing a small number of information from the observations (like
a projection on a smaller space). For instance, this can be used to posterize an image (conversion of a
continuous gradation of tone to several regions of fewer tones):
>>> from scipy import misc
>>> face = misc.face(gray=True).astype(np.float32)
>>> X = face.reshape((-1, 1)) # We need an (n_sample, n_feature) array
>>> K = k_means = cluster.KMeans(n_clusters=5) # 5 clusters
>>> k_means.fit(X)
KMeans(...)
>>> values = k_means.cluster_centers_.squeeze()
>>> labels = k_means.labels_
>>> face_compressed = np.choose(labels, values)
>>> face_compressed.shape = face.shape
Exercise
Raw image
Which of the kernels noted above has a better prediction performance on the digits dataset?
357
358
The cloud of points spanned by the observations above is very flat in one direction, so that one feature can
almost be exactly computed using the 2 other. PCA finds the directions in which the data is not flat and it can
reduce the dimensionality of the data by projecting on a subspace.
B Depending on your version of scikit-learn PCA will be in module decomposition or pca.
import numpy as np
import pylab as pl
from sklearn import cross_val, datasets, decomposition, svm
# ..
# .. load data ..
lfw_people = datasets.fetch_lfw_people(min_faces_per_person=70, resize=0.4)
perm = np.random.permutation(lfw_people.target.size)
lfw_people.data = lfw_people.data[perm]
lfw_people.target = lfw_people.target[perm]
faces = np.reshape(lfw_people.data, (lfw_people.target.shape[0], -1))
train, test = iter(cross_val.StratifiedKFold(lfw_people.target, k=4)).next()
X_train, X_test = faces[train], faces[test]
y_train, y_test = lfw_people.target[train], lfw_people.target[test]
# ..
# .. dimension reduction ..
pca = decomposition.RandomizedPCA(n_components=150, whiten=True)
pca.fit(X_train)
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
PCA is not just useful for visualization of high dimensional datasets. It can also be used as a preprocessing step
to help speed up supervised methods that are not efficient with high dimensions.
359
# ..
# .. classification ..
clf = svm.SVC(C=5., gamma=0.001)
clf.fit(X_train_pca, y_train)
360
# ..
# .. predict on new images ..
for i in range(10):
print(lfw_people.target_names[clf.predict(X_test_pca[i])[0]])
_ = pl.imshow(X_test[i].reshape(50, 37), cmap=pl.cm.gray)
_ = raw_input()
diabetes = datasets.load_diabetes()
diabetes_X_train = diabetes.data[:-20]
diabetes_X_test = diabetes.data[-20:]
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test = diabetes.target[-20:]
By default the GridSearchCV uses a 3-fold cross-validation. However, if it detects that a classifier is passed,
rather than a regressor, it uses a stratified 3-fold.
Cross-validated estimators
To improve the conditioning of the problem (uninformative variables, mitigate the curse of dimensionality, as
a feature selection preprocessing, etc.), it would be interesting to select only the informative features and set
non-informative ones to 0. This penalization approach, called Lasso, can set some coefficients to zero. Such
methods are called sparse method, and sparsity can be seen as an application of Occams razor: prefer simpler
models to complex ones.
Cross-validation to set a parameter can be done more efficiently on an algorithm-by-algorithm basis. This is
why, for certain estimators, the scikit-learn exposes CV estimators, that set their parameter automatically by
cross-validation:
199.17441034,
0.
,
These estimators are called similarly to their counterparts, with CV appended to their name.
Exercise
361
362
Index
D
diff, 304, 307
differentiation, 304
dsolve, 307
E
equations
algebraic, 305
differential, 307
I
integration, 305
M
Matrix, 306
P
Python Enhancement Proposals
PEP 255, 145
PEP 3118, 182
PEP 3129, 155
PEP 318, 147, 155
PEP 342, 145
PEP 343, 155
PEP 380, 147
PEP 380#id13, 147
PEP 8, 150
S
solve, 305
363