Pythonize Yourself
Pythonize Yourself
1/77
Pythonize Yourself
Pythonize Yourself
Michele Dei
[email protected]
1 Introduction:
Matlabholics Anonymous - How to redeem
2 Tools:
How to get things done: Tools, IDEs, Installation
3 Language:
Enjoy the Lego
R
4 Packages4Science:
Four Horsemen of the Apocalypse:
NumPy, SciPy, Matplotlib, Sympy
5 Examples:
Dirty work (but someone has to do it)
1 Introduction:
Matlabholics Anonymous - How to redeem
2 Tools:
How to get things done: Tools, IDEs, Installation
3 Language:
Enjoy the Lego
R
4 Packages4Science:
Four Horsemen of the Apocalypse:
NumPy, SciPy, Matplotlib, Sympy
5 Examples:
Dirty work (but someone has to do it)
Ethics!
I Expensive
I Influential establishment held by a pri-
vate company
”MATLAB
, R the language of technical computing, is a pro-
gramming environment for algorithm development, data anal-
ysis, visualization, and numeric computation.”
Function-name = file-name.
Ok for small code bases but discourages writing modular pro-
grams suitable for grown up projects, and at last the capability
of your code to be shared and be useful for the rest of the
community
http://www.mathworks.com/company/factsheet.pdf
http://www.mathworks.com/company/aboutus/index.html?s_tid=
gn_loc_drop
M, Dei, IMB-CNM(CSIC) ICAS Tutorials
Pythonize Yourself Intro Tools Language Packages4Science Examples 7/77
I Exercise #1
http://wiki.octave.org/FAQ
M, Dei, IMB-CNM(CSIC) ICAS Tutorials
Pythonize Yourself Intro Tools Language Packages4Science Examples 8/77
5
6 pp.xkcd()
7 pp.figure(figsize=(3.5,3.5))
8 pp.plot(x, np.sqrt(x),color=’m’,\
9 label=r"Skiing: $\sqrt{t}$")
10 pp.plot(x,x**2,color=’g’,\
11 label=r"Snowboarding: $tˆ2$")
12 pp.xlabel("Time $t$") ; pp.ylabel("Skill")
13 pp.legend(loc=’upper center’,fontsize=14,\
14 fancybox=True,framealpha=0.25)
15 pp.show()
learning curve.py
https://www.stat.washington.edu/˜hoytak/blog/whypython.html
M, Dei, IMB-CNM(CSIC) ICAS Tutorials
Pythonize Yourself Intro Tools Language Packages4Science Examples 9/77
I Cython: optimising static compiler for Python, allows calls back and forth from and to
C or C++ code natively at any point. easily tune readable Python code into plain C
performance by adding static type declarations
I Python can be integrated with other languages too (Fortran, Java, PHP ...):
https://wiki.python.org/moin/IntegratingPythonWithOtherLanguages
I What is Python used for? Google, Yahoo, Youtube, gaming...
https://wiki.python.org/moin/OrganizationsUsingPython
I Is used as extension language in Inkscape, Freecad, Klayout, Glade, Pymol:
https://en.wikipedia.org/wiki/List_of_Python_software#Embedded_as_a_scripting_language
Anyway we can take advantage of the interoperability of Scilab/Python and use the Xcos to
design dynamical systems models. https://www.scilab.org/scilab/features/
xcos
The last example in this presentation is focused on this issue.
1 Introduction:
Matlabholics Anonymous - How to redeem
2 Tools:
How to get things done: Tools, IDEs, Installation
3 Language:
Enjoy the Lego
R
4 Packages4Science:
Four Horsemen of the Apocalypse:
NumPy, SciPy, Matplotlib, Sympy
5 Examples:
Dirty work (but someone has to do it)
DIE HARD
Build Python (latest version) , config Vi(m) or Emacs
https://docs.python.org/2/using/unix.html
I Python on terminal
you may want to use it as command line
tool
I Python on terminal
you may want to use it as command line
tool
I IPython on terminal
Interactive with graphical capabilities,
shell syntax, tab completion, and history.
It has %magic commands
I Python on terminal
you may want to use it as command line
tool
I IPython on terminal
Interactive with graphical capabilities,
shell syntax, tab completion, and history.
It has %magic commands
I IDLE
Syntax highlighting, debugger
I Python on terminal
you may want to use it as command line
tool
I IPython on terminal
Interactive with graphical capabilities,
shell syntax, tab completion, and history.
It has %magic commands
I IDLE
Syntax highlighting, debugger
I Spyder
Syntax highlighting, debugger, intro-
spection for code completion, support
for multiple Python consoles (including
IPython), has the ability to explore and
edit variables from a GUI
1 Introduction:
Matlabholics Anonymous - How to redeem
2 Tools:
How to get things done: Tools, IDEs, Installation
3 Language:
Enjoy the Lego
R
4 Packages4Science:
Four Horsemen of the Apocalypse:
NumPy, SciPy, Matplotlib, Sympy
5 Examples:
Dirty work (but someone has to do it)
Calculator
>>> 17 / 3 # Comment: int / int -> int
5
>>> 17 / 3.0 # int / float -> float
5.666666666666667
>>> 17 // 3.0 # explicit floor division discards the fractional part
5.0
>>> 17 % 3 # the % operator returns the remainder of the division
2
>>> _ ** 3 # Exponentiation, the underscore is the last returned value
8
>>> (-1 + 3j)*2j # Complex numbers, natively supported
(-6-2j)
complex list
mutable sequence of
real and imaginary floats
objects
dict
maps one set of objects to
another
Playing around
>>> type(’float’) # String using single quotes
<type ’str’>
>>> type(8), type(8.1) # A sequence of inputs separated by a comma
(<type ’int’>, <type ’float’>)
>>> bool(-3), bool(0.0) # How much truth in a number?
(True, False)
>>> float(7), complex(3.1) # Conversion of numerical types
(7.0, (3.1+0j))
>>> a = complex(3, -4) # Assignment using complex() constructor
>>> abs(a) # Absolute function, consistent with the argument type
5.0
>>> int(a) # Will throw an exception ’TypeError’ since it is ambiguous
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can’t convert complex to int ’
>>> str(0.278), str(True), int(’23’) # Back and forth from str
(’0.278’, ’True’, 23)
3 http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/
EWD831.html
Strings
Dictionaries
Flow control4
if <condition1>: for <item> in <iterable>: while <condition>:
... ... ...
elif <condition2>:
... for <item> in <iterable>: while <condition1>:
... ... ...
elif <conditionN>: if <condition>: if <condition2>:
... continue continue
else: ... ...
...
for <item> in <iterable>: while <condition1>:
... ...
if <condition>: if <condition2>:
break break
... ...
Iterable: An object capable of returning its members one at a time. Examples: all Error handling
sequence types (list, str, and tuple) and some non-sequence types like dict Sometimes: ”it’s better to beg forgive-
and file. ness than ask permission”
XRange Type: The xrange type is an immutable sequence which is commonly used try:
for looping. The advantage of the xrange type over range is that the former will 1/0
always take the same amount of memory, no matter the size of the range it represents. except ZeroDivisionError:
range(100000), is list of 100000 elements! xrange(100000) not. print(’1/0!’)
>>> tuple(enumerate([6, 4, 5, 9])) assert(1 > 0)
((0, 6), (1, 4), (2, 5), (3, 9))
Enumerate: >>> for i, v in enumerate([6, 4, 5, 9]): assert for checking inputs or interme-
... print(i, v) diate results. If not asserted, raises an
AssertionError
4 https://docs.python.org/2/tutorial/controlflow.html
https://docs.python.org/2/tutorial/errors.html
Functions
Suppose you want a function that calculates the roots of ax2 + bx + c = 0.
1 def quadratic_formula(a, b, c): >>> quadratic_formula(1, -3, 2)
2 dis = (b**2 - 4*a*c)**0.5 (1.0, 2.0)
3 return (-dis-b)/(2*a), (dis-b)/(2*a)
quadratic0.py >>> quadratic_formula(1, 3, 3)
Traceback (most recent call last):
...
ValueError: negative number cannot be raised to
a fractional power
Functions ...
Optional arguments:
1 def quadratic_formula(a, b, c, real=False): >>> quadratic_formula(1, -3, 2)
2 dis = (b**2 - 4*a*c + 0j)**0.5 ((1-0j), (2+0j))
3 if real:
4 if dis.imag == 0: >>> quadratic_formula(1, -3, 2, real=True)
5 return (-dis.real-b)/(2*a), (1.0, 2.0)
6 (dis.real-b)/(2*a)
7 else: a, b, c are positional arguments
8 return (-dis-b)/(2*a), (dis-b)/(2*a) real is a keyword argument
quadratic2.py keyword arguments come always after positional arguments
I The variable name is already defined, and set to the value ’ main ’.
I This allows the programmer to control the behaviour of the script whether it is the main
program executed or not.
Script behaviours: !#
1 #! /usr/bin/env python
#!
2 def quadratic_formula(a, b, c, real=False): (shebang) directive:
3 """ instructs the loader which program to look for
4 Returns the roots of: a*x**2 + b*x + c = 0 executing the current script.
5 Only real solutions are returned if real is True
6 """ For Python scripts:
7 dis = (b**2 - 4*a*c + 0j)**0.5 #!/usr/bin/python
8 if real:
9 if dis.imag == 0: or, even bettera
10 return (-dis.real-b)/(2*a), (dis.real-b)/(2*a)
11 else: #!/usr/bin/env python
12 return (-dis-b)/(2*a), (dis-b)/(2*a)
13 The interpreter ignores it, as it is a comment
14 if __name__ == ’__main__’: a
https://mail.python.org/pipermail/
15 print(’This script contains the definition of a function’) tutor/2007-June/054816.html
16 else:
17 print(__name__)
quadratic3.py
Your script is now ready to be used in a shell, once you have changed its privileges to be
executable:
$ chmod a+x quadratic3.py
$ ./quadratic3.py
This script contains the definition of a function
$ _
>>> dir(quadratic3)
[’__builtins__’, ’__doc__’, ’__file__’, quadratic3 has its own attributes:
’__name__’, ’__package__’, ’quadratic_formula’] it has a name...
>>> quadratic3.__name__
’quadratic3’
>>> quadratic3.__file__
’quadratic3.py’
quadratic_formula(a, b, c, real=False)
Returns the roots of: a*x**2 + b*x + c = 0
Only real solutions are returned if real is True
Functions, classes, and more generally, objects, can be defined and reused im-
porting them. From now on cut+paste code from/to your scripts is capital crime!
import some_module
Best: [...]
some function visibility as part of some module namespace x = some_module.some_function(4)
I Suppose you want your script with quadratic formula() be accessible directly at
command line level. You may want to pass additional arguments to the interpreter.
$ python script_name.py argument(s) The script name and additional arguments thereafter are turned into a list
of strings and assigned to the argv variable in the sys module.
1 #! /usr/bin/env python
2 import sys $ python quadratic4.py 4 0 -100
3 import quadratic3 as q3 quadratic3
4 ((-5+0j), (5+0j))
5 if __name__ == ’__main__’:
6 arg = sys.argv $ python quadratic4.py 4 0 -100 True
7 try: quadratic3
8 assert(len(arg) >= 4) (-5.0, 5.0)
9 a,b,c = float(arg[1]),float(arg[2]),float(arg[3])
10 real = False $ python quadratic4.py 4 Z -100 True
11 if len(arg) > 4: quadratic3
12 real = True if arg[4] == ’True’ else ’False’ Invalid arguments
13 if a == 0:
14 try: $ python quadratic4.py
15 print(-c/b) Help on function quadratic_formula in
16 except ZeroDivisionError: module quadratic3:
17 print(’No unknown to solve for’)
18 else: quadratic_formula(a, b, c, real=False)
19 print(q3.quadratic_formula(a, b, c, real)) Returns the roots of: a*x**2 + b*x
20 except AssertionError: + c = 0
21 help(q3.quadratic_formula) Only real solutions are returned
22 except ValueError: if real is True
23 print(’Invalid arguments’) (END)
quadratic4.py
I Positional argument:
an argument that is not a keyword argument. Positional arguments can >>> complex(3, 5)
appear at the beginning of an argument list and/or be passed as elements
of an iterable preceded by *. >>> complex(*(3, 5))
For example, 3 and 5 are both positional arguments in the following calls:
Some remarks:
>>> def fun0(*args, **kwargs): >>> x, y = (1,2,3), (4,5,6)
... print(args) >>> z = zip(x,y); print(z)
... print(kwargs) [(1, 4), (2, 5), (3, 6)]
>>> xx, yy = zip(*z)
>>> fun0(1, 2, third=3, forth=4) >>> print(xx, yy)
(1, 2) ((1, 2, 3), (4, 5, 6))
{’forth’: 4, ’third’: 3}
zip()
Note nor args neither kwargs are known previously
from function side. args, kwargs are conventional
names.
Functional programming5
Classes
I What is a class? It’s about the definition of things. def: defines a function, class
defines a logical grouping of data and functions. We refer to them as attributes and
methods, respectively.
that’s because objects created from a class aim to mimic real world ”objects”.
https://xkcd.com/26/
You have a big database of signals:
I some of them are represented in the time domain, others in frequency domain.
Each of them comes with its time (∆t) or frequency resolution (∆f ), for simplicity uni-
formly spaced. You may wish to switch from one representation to another. Direct and
inverse fft()
I you may want to analyse them from a power spectral density (psd) point of view, and
associate to each signal its proper windowing function, or more advanced filtering to ex-
tract the signal from unwanted interference. psd(), window, averages number,
filt(), filt params = { ... }
I you may also want some specialized visualization tools for your data: psd plot, an his-
togram plotting the statistical distribution of amplitudes, etc. psd plot(), histo()
Classes ...
A skecth of your class would look like:
After defining your class you would use it simply like:
1 class Signal():
2 def __init__(self, x, domain, res): >>> x = Signal(raw_data, ’freq’, 1e2)
3 assert(domain in [’time’, ’freq’]) >>> x.filt(5e3, 50e3) # use a method!
4 TF = domain == ’time’ >>> x.histo()
5 self.xt = x if TF else self.fft(x, res, -1) ...
6 self.xf = self.fft(x, res) if TF else x
7
x is now an object with all its attributes (x.xt, x.xf
8 def fft(self, x, dx, direction = 1): ...) tidily bundled and organized.
9 pass # to be implemented! It has capabilities (methods) like histo(), psd(), etc.
10
that operates on it, and are specialized functions that op-
11 def psd(self, window): erate in a well defined environment.
12 self.window = window
13 pass # to be implemented! __init__()? Initialization method, needed to initialize
14 the instance.
15 def filt(self, **filt_params):
16 pass # to be implemented! self?
17 used to declare a method or an a attribute of the instance!
18 def psd_plot(self): Without it all would look like local variables and the code
19 pass # to be implemented! would be ambiguous
20
21 def histo(self):
22 pass # to be implemented!
1 Introduction:
Matlabholics Anonymous - How to redeem
2 Tools:
How to get things done: Tools, IDEs, Installation
3 Language:
Enjoy the Lego
R
4 Packages4Science:
Four Horsemen of the Apocalypse:
NumPy, SciPy, Matplotlib, Sympy
5 Examples:
Dirty work (but someone has to do it)
Stack/Ecosystem
Numpy
Create
>>> np.ones((2,3))
array([[ 1., 1., 1.], ones(shape, dtype=None, ...)
[ 1., 1., 1.]]) zeros(shape, dtype=None, ...)
>>> np.ones(4) ones_like(a, dtype=None, ...)
array([ 1., 1., 1., 1.]) zeros_like(a, dtype=None, ...)
>>> a = np.zeros(3)
>>> np.ones_like(a)
eye(N, M=None, k=0, dtype=<type ’float’>)
array([ 1., 1., 1.])
Return a 2-D array with ones on the diagonal and zeros
...
elsewhere. M columns, k index of diagonal.
>>> np.eye(3)
array([[ 1., 0., 0.],
[ 0., 1., 0.], k: -1 0 1
[ 0., 0., 1.]]) 11 12 13
>>> np.eye(3, k=-2) + np.eye(3, k=1)
array([[ 0., 1., 0.], 21 22 23
[ 0., 0., 1.], 31 32 33
[ 1., 0., 0.]])
Simple tests
>>> a = np.array([[1, 2], [3, 4]]) dtype
>>> type(a), a.dtype, len(a), np.shape(a), np.size(a) shape
(<type ’numpy.ndarray’>, dtype(’int64’), 2, (2, 2), 4) size
>>> np.unique(a)
unique
array([1, 2, 3, 4])
Extraction of unique elements
>>> a.diagonal() diagonal
array([1, 4])
Simple manipulation
>>> a.transpose() >>> a In multidimensional arrays you
array([[1, 3], transpose array([[1, 2],
both as method and function have the axis optional argu-
[2, 4]]) [3, 4]]) ment:
>>> np.transpose(a)
array([[1, 3], >>> a.sum()
[2, 4]]) 10
axis=0
>>> a.T >>> a.sum(axis=0)
array([[1, 3], array([4, 6])
2
[2, 4]]) >>> a.prod(axis=1)
=
is
array([ 2, 12])
ax
>>> a.reshape(4,1) reshape, flatten axis=1
array([[1], both as methods and functions >>> a.mean(axis=1)
sum, prod
[2], array([ 1.5, 3.5])
[3], mean, var, std, max, min
[4]]) >>> a.argmin(axis=1)
>>> a.flatten() array([0, 0]) argmax, argmin
array([1, 2, 3, 4]) >>> a.argmax(axis=0) array indices of the minimum
array([1, 1]) and maximum values
>>> a.clip(2,3) clip, fill
array([[2, 2], >>> b = a copy
[3, 3]]) >>> b.fill(0); a
>>> a.fill(9); a array([[0, 0],
array([[9, 9], [0, 0]])
[9, 9]])
>>> a = np.copy(b)
>>> a = np.eye(2); b
array([[0, 0],
[0, 0]])
11 12 13 1 1 1 12 13 14
21 22 23 2 2 2 23 24 25
Exercises
Which is the result of:
31 32 33 3 3 3 34 35 36
I np.array([[1, 2, 3]]).T*np.array([1, 2, 3])?
11
1 1 1 1 2 3 2 3 4 I np.arange(1,10).reshape((3,3))**2?
2 2 2 1 2 3 3 4 5
3 3 3 1 2 3 4 5 6
>>> a[0]
0-based indexing
0
I Whereas slicings on lists and tuples create new objects, a slicing operation on an array
creates a view on the original array. So we get an another possibility to access the
array, or better a part of the array. From this follows that if we modify a view, the
original array will be modified as well.
Array selectors
I Selection by booleans I Selection by indexes
>>> a = np.array([[6, 4], [5, 9]], float) >>> a = np.array([2, 4, 6, 8], float)
>>> a >= 6 >>> b = np.array([0, 0, 1, 3, 2, 1], int)
array([[ True, False], >>> a[b]
[False, True]], dtype=bool) array([ 2., 2., 4., 8., 6., 4.])
>>> a[a >= 6]
array([ 6., 9.]) >>> a[np.where(a>5)]
>>> a[np.logical_and(a > 5, a < 9)] array([ 6., 8.])
>>> a[np.nonzero(a>5)]
array([ 6., 8.])
Structured arrays
>>> dtype = np.dtype([(’month’, ’S10’), (’day’, ’S10’), (’number’, ’i4’)])
Array algebra
>>> a, b = np.array([1, 2, 3]), np.array([0, 1, 1])
>>> np.dot(a,b) dot()
5 dot product
NumPy also comes with a number of built-in routines for linear algebra calculations. These
can be found in the sub-module linalg.
Polynomials
poly() Given a set of roots, returns the polynomial co-
>>> np.poly([-1, 1, 1, 10]) efficients
poly() Given a set of polynomial coefficients, returns
>>> np.roots([1, 4, -2, 3]) the roots
polyadd(), polysub(), polymul(), polydiv()
>>> np.polyint([1, 1, 1, 1]) Polynomial algebra
polyder(), polyint() Derivation, integration (con-
>>> np.polyder([1./4., 1./3., 1./2., 1., 0.]) stant of unknown term is 0)
polyval() Evaluates a polynomial at a particular point
... polyfit() fot data to polynomial (least-squares error)
Scipy?
Matplotlib Backends
Pylab?
from pylab import *
Matplotlib Pyplot
1 # -*- coding: utf-8 -*- 8 # Computation part: Van der Pol equation
2 from numpy import * 9 def vanderpol(u, t=0., mu=.5):
3 from scipy import * 10 x = u[0]
4 from scipy.integrate import odeint 11 v = u[1]
5 from matplotlib.pyplot import * 12 dx = v
6 matplotlib.rc(’axes’, edgecolor = ’black’) 13 dv = mu*(1. - x**2)*v - x
van der pol mod1.py 14 return dx, dv
15
With respect to the original codea here the computational
16 t = linspace(-5.5, 5.5, 300)
and the graphical parts are separated.
17 u0 = array([1. , 1.])
I numpy, scipy, matplotlib.pyplot imported di- 18 mu = [ .25, .5, 1., 1.5, 2.0]
rectly into the main namespace. 19 u = []
20 for m in mu:
I The odeint solve numerically systems of ordinary 21 u.append(odeint(vanderpol, u0, t, args=(m,)))
differential equation: 22
23 # Computational part: attractors
dx 24 x = linspace(-3, 3, 15)
= f (x, t0 , . . .)
dt 25 y = linspace(-4, 4, 15)
26 x, y = meshgrid(x, y)
I The Van der Pol equation is: 27 X, Y = vanderpol([x, y])
(
dx
28 M = (hypot(X, Y))
d2 x 2 dx dt
=v 29 M[M == 0] = 1.
−µ(1−x ) +x = 0 −→ dv
dt2 dt dt
= µ(1 − x2 )v − x 30 X, Y = X/M, Y/M
https://commons.wikimedia.org/wiki/
a van der pol mod1.py
File:Van_der_pols_equation_phase_portrait.
svg
I legend() http://matplotlib.org/users/legend_
guide.html
45 # Legend
46 ax.legend(loc = ’upper left’)
47 setp(ax.get_legend().get_texts(), fontsize = 14)
48 fig.savefig("van_der_pol_equation_phase_portrait_1_p3.svg",
49 bbox_inches="tight", pad_inches=.15)
van der pol mod1.py
50 # Grids
51 ax.grid(True)
52 ax.minorticks_on()
53
54 # Text on figure
55 txt_dic = {’fontsize’: 18, ’backgroundcolor’: ’w’}
56 text(0.0, -3.2, r’$\dot{x} = v$’, **txt_dic)
57 text(0.0, -3.7, r’$\dot{v} = \mu(1 - xˆ2)v - x$’, **txt_dic)
58 fig.savefig("van_der_pol_equation_phase_portrait_1_p4.svg",
59 bbox_inches="tight", pad_inches=.15)
van der pol mod1.py
Sympy8
I Sympy adds symbolic math for a Maple or
$ ipython notebook --profile=sympy
Mathematica alternative. In conjunction with
a IPython Notebook, it has similar functional- >>> from sympy import *
ity. However we will explore its features im-
porting it as a module.
I Regarding Sage9:
– Sage includes Sympy
– Sage is huge and glues together many mathematical open source packages (also
non-Python)
– Sympy is a lightweight normal Python module. No external dependencies.
Geometry Module
Linear Algebra Module
Numerics Module
I It has various submodules: Plotting Module
Concrete Mathematics Module
Polynomials Module
Statistics Module
Pretty Printing
8 Extensive documentation: http://sympy.googlecode.com/svn/api/sympy.html
9 https://github.com/sympy/sympy/wiki/SymPy-vs.-Sage
SymPy: Symbols
Built-in numeric types: Real for arbitrary-precision floating-point numbers, Rational
Represents integers and rational numbers p/q of any size
>>> Rational(3), Rational(1,2)
(3, 1/2)
>>> Rational("3/5"), Rational("1.23") # from a string
(3/5, 123/100)
>>> Rational("1.23").p, Rational("1.23").q # Access nominator and denominator as .p and .q
(123, 100)
Complex numbers
>>> exp(I*x).expand(complex=True)
I*exp(-im(x))*sin(re(x)) + exp(-im(x))*cos(re(x))
>>> x = Symbol("x", real=True)
>>> exp(I*x).expand(complex=True)
I*sin(x) + cos(x)
SymPy: Calculus
Limits Algebraic equations
>>> limit(sin(x)/x, x, 0) In [19]: solve(Eq(x**4, 1), x)
1 Out[19]: [1, -1, -I, I]
>>> limit(1/x, x, oo) # infinity symbol: oo
0 Integration
>>> integrate(log(x), x) # indefinite
Differentiation x*log(x) - x
>>> diff(tan(x), x) >>> integrate(sin(x), (x, 0, pi/2)) # definite
tan(x)**2 + 1 1
>>> limit((tan(x+y)-tan(x))/y, y, 0) >>> integrate(exp(-x), (x, 0, oo)) # improper
tan(x)**2 + 1 1
# Higher derivatives diff(func, var, n):
>>> diff(sin(2*x), x, 2) Series expansion
-4*sin(2*x)
>>> cos(x).series(x, 0, 10)
1 - x**2/2 + x**4/24 - x**6/720 + x**8/40320 +
+ O(x**10)
Differential equations
In [2]: Eq(f(x).diff(x, x) + f(x), 0)
Out[2]:
2
d
-----(f(x)) + f(x) = 0
dx dx
SymPy
Linear Algebra: Matrix
>>> from sympy.matrices import Matrix
>>> A = Matrix([[1,x], [y,1]])
>>> A
[1, x]
[y, 1]
>>> A**2
[x*y + 1, 2*x]
[ 2*y, x*y + 1]
Printing
Python build-in way to print an expression is simply through the use of str(expression)
or repr(expression). More readable printing is available through the Pretty print-
ing submodule:
SymPy
Simplifications
Simplify: uses heuristics to determine the ”simplest” result. Combinations of expand(),
factor(), collect(), cancel() may return the desired result10.
>>> simplify(sin(x)**2 + cos(x)**2)
1
Partial fractions
>>> f = 1/(x**2*(x**2 + 1))
>>> f
1
2 2
x (x + 1)
>>> apart(f)
1 1
− 2 + 2
x +1 x
>>> together(_)
1
2 2
x (x + 1)
Evaluations:
evalf evaluates a sympy expression numerically with arbitrary number of digits. lamb-
dify transform sympy expressions to lambda functions which can be used to calculate
numerical values very fast. Example:
>>> pi.evalf(n=30)
3.14159265358979323846264338328
10 http://docs.sympy.org/latest/tutorial/simplification.html#simplify
SymPy, Plot
The plotting module allows you to make 2-dimensional and 3-dimensional plots. Plots are
rendered using matplotlib as a backend. The following functions are available:
I plot: Plots 2D line plots.
I plot parametric: Plots 2D para-
metric plots.
I plot implicit: Plots 2D implicit 15
and region plots.
10
I plot3d: Plots 3D plots of functions 5
in two variables.
0
I plot3d parametric line: Plots 5
3D line plots, defined by a parame-
10
ter.
15
I plot3d parametric surface: 10
Plots 3D parametric surface plots. 5
10 0
Example: 5
0 5
5
>>> from sympy.plotting import plot3d
10 10
>>> x, y = symbols(’x y’)
>>> plot3d(cos(x*3)*cos(y*5)-y*cos(x))
1 Introduction:
Matlabholics Anonymous - How to redeem
2 Tools:
How to get things done: Tools, IDEs, Installation
3 Language:
Enjoy the Lego
R
4 Packages4Science:
Four Horsemen of the Apocalypse:
NumPy, SciPy, Matplotlib, Sympy
5 Examples:
Dirty work (but someone has to do it)
Suppose we are interested in the socio-economic inequality issue, we find some data on
the internet11 and we propose to analyse them.
We save our CSV file, with its predifined name DP LIVE 26042016225351582.csv lo-
cally into a data subfolder relative to our script path.
We want to be able to view the data by country (LOCATION), by year (TIME), and of course
by the value of the Gini coefficient (VALUE).
11 https://data.oecd.org/inequality/income-inequality.htm
6 csv_file = (
7 ’DP_LIVE_26042016225351582.csv’,
8 ’data’,
9 os.path.dirname(os.path.abspath(__file__))
10 )
11 data_struct = {
12 ’field’ : (’Country’, ’Year’, ’Value’),
13 ’dtype’ : (’S3’, np.int16, np.float16),
14 ’ncol’ : (0, 5, 6),
15 ’heads’ : 1
16 }
>>> print(data[1:8])
[(’AUT’, 2008, 0.281005859375) (’AUT’, 2009, 0.2890625)
(’AUT’, 2010, 0.280029296875) (’AUT’, 2011, 0.281982421875)
(’AUT’, 2012, 0.27587890625) (’BEL’, 2005, 0.280029296875)
(’BEL’, 2006, 0.27099609375)]
We want csv file, data struct, dtype, data to be accessible for all the methods
in the csv2data class, hence they are created at init as class attributes.
Now the class could be organized with the following functionalities (methods):
I fetch data in the given csv file, corresponding to the code between lines 22-26 of
gini coeff.py
I capability to filter by key, key value analogously to the function filter data()
I capability to extract data, as in extract data()
With respect to the gini coeff.py we added here a try/except construct to handle
input/output errors of the file (for example, file not found, etc.)
Finally we add a call method to let any instance of the csv2data class to be used
as they were functions:
50 def __call__(self, key, key_value):
51 if len(self.data)==0:
52 self.fetch_data()
53 return self.extract_data(key, key_value)
Gini coefficient
27 props = dict(width=0.3, alpha=0.5, linewidth=0)
28
29
30
for i, country in enumerate(countries):
g = gini(’Country’, country)
0.30
31 x = g[’Year’]
32 y = g[’Value’]
33 ax.bar(x+i*0.2, y, color=colors[i], label=country, **props) 0.25
34
35 plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=4, mode="expand", borderaxespad=0., fontsize=10)
36
37 ax.set_ylim([0.2,0.4]) 0.20
05
06
07
08
09
10
11
12
38 ax.set_ylabel(’Gini coefficient’)
20
20
20
20
20
20
20
20
39 xTickMarks = [str(i) for i in range(min(g[’Year’]),max(g[’Year’])+1)]
40 xtickNames = ax.set_xticklabels(xTickMarks)
41 plt.setp(xtickNames, rotation=45)
42 plt.subplots_adjust(right=0.5)
43 plt.tight_layout()
test csv2data.py
Multiprocessing: multiproc.py
This example is designed to show how:
I include a very basic multiprocessing capability in Python scripts
I Xcos, like Simulink provides a graphical programming environment for modelling, sim-
ulating and analysing multi-domain dynamic systems.
I You can script Xcos directly within the Scilab12 environment without Python. Anyway
Scilab and Python has a certain grade of interoperability
I From the Python-side, to interact with Scilab-Xcos, you need the scilab2py mod-
ule13. It is not present in the Anaconda bundle by default, but it is easy to install by
pip: $ pip install scilab2py
Useful links:
How to simulate a Xcos model from the scilab command window (batch mode):
https://help.scilab.org/docs/5.5.0/fr_FR/xcos_simulate.html
A (very short) documentation on how to use the scilab2py API can be found here:
http://blink1073.github.io/scilab2py/source/api.html
12 http://www.scilab.org/
13 https://pypi.python.org/pypi/scilab2py
1 importXcosDiagram(filename)
2 scs_m.props.context =
3 ["Ain=0.01" "fs=1" "fin=0.01"];
4 xcos_simulate(scs_m, 4);
PSD [V 2 /Hz]
20
21 # set Xcos parameters (context): 10-3
22 sci.eval(’scs_m.props.context = ’ +
23 ’["Ain=0.01" "fs=1" "fin=0.01" "nclocks = 10-4
2048"];’)
24 # simulate:
25 sci.eval(’xcos_simulate(scs_m, 4);’) 10-5
# retrieve DOUT from scilab workscape:
10-6
26
27 dout = sci.pull(’DOUT.values’)
28
29
# Close session:
sci.close()
10-7
10-8
0.0 0.1 0.2 0.3 0.4 0.5
frequency [Hz]
Resources
Web resources:
I http://stackoverflow.com/
I https://docs.python.org/2/
I https://wiki.python.org/moin/FrontPage
Bonus
World clouds in Python: https://github.com/amueller/word_cloud
1 # /usr/bin/env python
2 # -*- coding: utf-8 -*-
3 from os import path
4 from scipy.misc import imread
5 import matplotlib.pyplot as plt
6 import random
7 from wordcloud import WordCloud, STOPWORDS
8
9 # custom color function
10 def py_color_func(word, font_size, position, orientation, random_state=None, **kwargs):
11 return "hsl(0, 65%%, %d%%)" % random.randint(60, 80)
12
13 # current script path
14 d = path.dirname(__file__)
15
16 # python logo
17 mask = imread(path.join(d, "pythonlogo45.png"), flatten = True)
18
19 # from the tex source of the session 3 of this presentation
20 text = open("language.tex").read()
21
22 # stopwords: exclude set of latex syntax words
23 stopwords = STOPWORDS.copy()
24 with open(path.join(d, ’latex_syntax.txt’), ’r’) as f:
25 rm = set(f.read().split())
26 stopwords = stopwords | rm
27
28 # create the cloud
29 wc = WordCloud(max_words=1000,
30 mask=mask,
31 stopwords=stopwords,
32 margin=1,
33 random_state=3,
34 width=794*10,
35 height=595*10,
36 font_path=path.join(d,’cmuntt.ttf’),
37 background_color=’white’).generate(text)
38
39 # plot
40 plt.figure()
41 plt.imshow(wc.recolor(color_func=py_color_func, random_state=3))
42 wc.to_file(’pythonwordcloud.png’)
43 plt.axis("off")
44 print(’File output: ’+d+os.sep+’pythonwordcloud.png’)