Home

Python Scientific lecture notes

image

Contents

1. e Follow up copy all instructions of this exercise in a script called 1ena locket py then execute this script in IPython with run lena locket py Change the circle to an ellipsoid 3 2 Numerical operations on arrays 67 Python Scientific lecture notes Release 2013 1 Exercise Array manipulations 1 Form the 2 D array without typing it in explicitly 6 Ty 9 2 O il and generate a new array containing its 2nd and 4th rows Divide each column of the array gt gt gt a np arange 25 reshape 5 5 elementwise with the array b np array 1 5 10 15 20 Hint np newaxis 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 e 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 3 2 Numerical operations on arrays 68 Python Scientific lecture notes Release 2013 1 Exercise Data statistics The data in populations txt describes the populations of hares and lynxes and carrots in northern Canada during 20 years gt gt gt data np loadixi data populations txt gt gt gt year hares lynxes carrots data T trick columns to variables wo Ole axess 10 2 Odor 0 57 Uus lt matplotlib axes Axes object at gt
2. gt gt gt np matrix 1 0 0 1 np matrix 1 2 3 4 Maer ect iL 2 ised 8 5 Summary e Anatomy of the ndarray data dtype strides Universal functions elementwise operations how to make new ones e Ndarray subclasses e Various buffer interfaces for integration with other tools Recent additions PEP 3118 generalized ufuncs 8 6 Contributing to Numpy Scipy Get this tutorial http www euroscipy org talk 882 8 6 1 Why e There s a bug e I don t understand what this is supposed to do I have this fancy code Would you like to have it Td like to help What can I do 8 6 2 Reporting bugs Bug tracker prefer this http projects scipy org numpy http projects scipy org scipy Click the Register link to get an account e Mailing lists scipy org Mailing_ Lists If you re unsure 8 5 Summary 189 Python Scientific lecture notes Release 2013 1 Noreplies in a week or so Just file a bug ticket Good bug report Title numpy random permutations fails for non integer arguments I m trying to generate random permutations using numpy random permutations When calling numpy random permutation with non integer arguments zi falls with lg Cryptic error messages gt gt gt Np random permutacion 12 array Uem dob cl IU 2 ihe ty CER Se 2 OR Sil poo MO random permuceac wom 2 Meaceback most recent call ast File lt stdi
3. Python Scientific lecture notes Release 2013 1 head Float 10 desc Hydraulic head m efficiency Range 0 1 irrigated areas List IrrigationArea def energy_production self release Returns the energy production Wh for the given release m3 s power 1000 x 9 81 self head release x self efficiency return power x 3600 traits view View Item name Item max_storage Item max_release Item head Item efficiency Item irrigated areas cresiz aole True if name Z main upper block IrrigationArea name Section C surface 2000 crop Wheat ye 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 1 kWh format release reservoir energy production release 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 erop e Enum Alitalia Wheat Corton class Reservoir HasTraits name Str max storage Float le6 desc Maximal storage hm3 max release Float 10 desc Maximal release m3 s
4. head Float 10 desc Hydraulic head m efficiency Range 0 1 irrigated areas List IrrigationArea 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 Python Scientific lecture notes Release 2013 1 def energy_production self release Returns the energy production Wh for the given release m3 s power 1000 x 9 81 self head release x self efficiency return power x 3600 traits view View teem name Item max_storage Item max_release Item head Item efficiency Item irrigated areas reem total crop surtace y resizable True 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 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 import numpy as np from traits api import HasTraits Array Instance Float Property from traits api import DelegatesTo from traitsui api import View Item Group from chaco chaco plot editor import ChacoPlotItem from reservoir import Reservo
5. e 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 e a language very easy to interface with other languages in particular C and C e 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 http www python org about for more information about distinguishing features of Python Python Scientific lecture notes Release 2013 1 2 1 First steps Start the Ipython shell an enhanced interactive Python shell e by typing ipython from a Linux Mac terminal or from the Windows cmd shell or by starting the program from a menu e g in the Python x y or EPD men
6. gt gt gt rp hpef1 gt gt gt xr white black p greens blue red 2 2 Basic types 13 Python Scientific lecture notes Release 2013 1 gt gt gt r2 list L gt gt gt I red blue green black white gt gt gt r2 reverse in place gt gt gt r2 white black green blue red Concatenate and repeat lists gt gt gt xy dh whate black qroen blue red red blue green black white gt gt gt rx 2 white black ya green blue red white black green Dbiue red Sort gt gt gt sorted r new object black blue green red white gt gt gt r white p plack green blue red gt gt gt cos in place gt gt gt r black blue green red white Note Methods and Object Oriented Programming The notation r method r sort r append 3 L pop 1s 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 Note Discovering methods Reminder in Ipython tab completion press tab In 28 lt TAB gt E ved E Sede r setattr tae elass Lo imal r setitem Lao COnNtCaLlnNS 1 S r __setslice __ ro cdela
7. A number of other predefined trait type do exist Array Enum Range Event Dict List Color Set Expression Code Callable Type Tuple etc Custom default values can be defined in the code from traits api import HasTraits Str Float class Reservoir HasTraits name Str max storage Float 100 reservoir Reservoir name Lac de Vouglans Note 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 14 3 2 Validation Every trait does validation when the user tries to set its content reservoir Reservoir name Lac de Vouglans max_storage 605 reservotr max storage 2307 Dead eit ret Traceback most recent call last cu dipinte PONE Sele ecciesie theatres Ipyvenen impue 7 o Fedgnmn9 7 4a gt in mod Python Scientific lecture notes Release 2013 1 T reservoir max storage 230 Users eliam eom occ etis pacis Aia ci ipao handlers pyc in Curren sels object mame value 166 vu 167 raise TraitError object name self full_info object name value Weis value 18539 170 def arg error self method arg num object name value TraitError The max storage trait of a Reservoir instance must be a float but
8. Browse the tracker Documentation work API docs improvements to docstrings Know some Scipy module well User guide Needs to be done eventually Want to think Come up with a Table of Contents http scipy org Developer Zone UG Toc Ask on communication channels numpy discussion lit Scipy dev list 8 6 Contributing to Numpy Scipy 192 CHAPTER 9 Debugging code author Ga l Varoquaux This tutorial explores tool 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 Prerequisites e Numpy Python nosetests http readthedocs org docs nose en latest pyflakes http pypi python org pypi pyflakes gdb for the C debugging part Chapters contents Avoiding bugs page 193 Coding best practices to avoid getting in trouble page 193 pyflakes fast static analysis page 194 Running pyflakes on the current edited file page 194 A type as go spell checker like integration page 195 Debugging workflow page 196 Using the Python debugger page 196 Invoking the debugger page 197 x Postmortem page 197 Step by step execution page 198 Other ways of starting a debugger page 200 Debugger commands and interaction page 201 Getting help when in the debugger page 201 Debugging segmentation faults using gdb page 201 9 1 A
9. matplotlib figure Pigure object at i cos plitplos tnupoesqrhtimeauncscsdlistomce Gs be Nps ET fet smatplotiib lines Line2D object at i2 metplotiob lrnes hine2D object at s plIt xlabel r USsts mactplotlrb textoelText ODject at 2 gt gt gt Dilteylabelir Ss vegrty 15note delta x 2 Xrsngle e e mat pror babere ce rp qM Io o pui pra d J TOU 150 200 3 2 Numerical operations on arrays E 58 Python Scientific lecture notes Release 2013 1 The RMS distance grows as the square root of the time 3 2 3 Broadcasting Basic operations on numpy arrays addition etc are elementwise This works on arrays of the same size Nevertheless It s also possible to do operations on arrays of different sizes if Numpy can transform these arrays so that they all have the same size this conversion is called broadcasting The image below gives an example of broadcasting N s S s LM UC UNCTUS T Let s verify gt gt a np crtle inp earangetO 40 10 3 D T gt gt gt a Bu OF 89 MF 2 0 GOs qn 5205 20 Z0 L350 307 Sd gt gt gt b np array 0 1 21 gt gt gt a b array mO dr Aer oe SES EE S OP ae e d M PSO 9p C An useful trick gt gt gt a np arange 0 40 10 gt gt gt a shape 3 2 Numerical operations on arrays 59 Python Scientific lecture notes Release 2013 1 gt gt gt a a np newaxis adds a new axis
10. pyflakes mode t A type as go spell checker like integration n vim Use the pyflakes vim plugin 1 download the zip file from http www vim org scripts script php script_id 244 2 extract the files in vim ftplugin python 3 make sure your vimrc has filetype plugin indent on B self log emissionprob obs Alternatively use the syntastic plugin This can be configured to use 1ake8 too and also handles on the fly checking for many other languages ta load_data exercises data MIT Fi data data H debug file pu Ol at least two spaces before inline comment In emacs Use the flymake mode with pyflakes documented on http www plope com Members chrism flymake mode add the following to your emacs file 9 1 Avoiding bugs 195 Python Scientific lecture notes Release 2013 1 when load flymake t defun flymake pyflakes init letx temp file flymake init create temp buffer copy flymake create temp inplace local file file relative name temp file file name directory buffer file name List Over lakest cust docebit add to list flymake allowed file name masks UI OUN ov UE iude i elles esie 9 3 add hook tind tile hook tliymake rind rile hook 9 2 Debugging workflow I you do have a non trivial bug this is when debugging strategies kick in There is no silver bullet Yet strategies help Note For debugging a given problem the favora
11. gt gt gt a erre WII hee hus sos eun eae Deo dox Oum gt gt gt a T array Il Me Cay Or Note 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 page 106 Exercise Generate arrays 2 0 2 1 2 2 2 3 2xx4 anda j 3 2 2 Basic reductions Computing sums gt gt gt x NO carray il 2 27 41 gt gt gt TD Sum x 10 gt gt gt x Sum 10 axis O Sum by rows and by columns gt gt gt X Mp array Ill dg I2 219 gt gt gt X array be a 2o n gt gt gt x sum axis 0 columns first dimension array s 1 Ss sce rss Soles reset 3p 3 gt gt gt x sum axis 1 rows second dimension array 2 4 3 2 Numerical operations on arrays 55 Python Scientific lecture notes Release 2013 1 sas spo sumtus se usum Co Same idea in higher dimensions gt gt gt x To random rand 2 gt gt gt x sum axis 2 0 1 1 14764 soo D I s sum ERIS ETSI PET Other reductions works the same way and take axi s e Statistics gt gt gt X np array I gt gt gt y mpra aand gt gt gt x mean CATS gt gt gt np median x IS gt gt np medran y
12. gt gt gt plt plot year hares year lynxes year carrots p mat plot lib lines Line D bqeck b siop 44 4 gt gt gt plr legend Hare Lynx Carrer j locs 1 0397 0457 lt matplotlib legend Legend object at gt 80000 70000 60000 Hare 50000 Lynx Carrot 40000 30000 20000 10000 1500 1905 1910 1915 1920 Computes and print based on the data in populations txt 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 Hint argsort amp fancy indexing of npo ebravtltBHt gt 60513 4 Which years any of the populations is above 50000 Hint comparisons and np any 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 3 2 Numerical operations on arrays 69 Python Scientific lecture notes Release 2013 1 Exercise Crude integral approximations Write a function f a b c that returns a ranges 0 1 x 0 1 x 0 1 Approximate the 3 d integral c Form a 24x12x6 array containing its values in parameter i ow gd J a c da db dc 0 Jo Jo over this volume with the mean The exact result is In 2 i z 0 1931 what
13. np ones mask shape label_im mask labels 12 6 Measuring objects properties ndimage measurements Synthetic data gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt n 10 1 256 zm Mp Zeros ily Lx points Ianp random random 2 ns 2 iim pokes Ol Past Veo E MODs s hi sss VID eT 1l im ndimage gaussian_filter im sigma 1 4 n mask lt S T RORIS CHOIR Analysis of connected components Label connected components ndimage label 12 6 Measuring objects properties ndimage measurements 246 Python Scientific lecture notes Release 2013 1 gt gt gt label im nb labels ndimage label mask gt gt gt nb labels how many regions o gt gt gt plt imshow label im matplotlib image AxesImage object at gt Compute size mean value etc of each region gt gt gt sizes ndimage sum mask label im range nb labels 1 gt gt gt mean vals ndimage sum im label im range 1 nb labels 1 Clean up small connect components gt gt gt mask size sizes 1000 gt gt gt remove pixel mask size label im gt gt gt remove pixel shape o D gt gt gt label im remove pixel 0 gt gt gt plt imshow label im matplotlib image AxesImage object at gt Now reassign labels with np searchsorted gt gt gt labels np unique label im gt gt gt label im np searchsorted labels la
14. numexpr 1s designed to mitigate cache effects in array computing Example inplace operations caveat emptor e Sometimes gt gt gt a b is not the same as 8 1 Life of ndarray 173 Python Scientific lecture notes Release 2013 1 gt gt gt a Db Copy gt gt gt x np array l1 gt gt gt x x transpose gt gt gt X gt gt gt y np array 1l gt gt gt y y T copy gt gt gt y e x and x transpose share data e x x transpose modifies the data element by element e because x and x t ranspose have different striding modified data re appears on the RHS 8 1 5 Findings in dissection TAn n scalar e l es s ri ndarray e memory block may be shared base data data type descriptor structured data sub arrays byte order casting viewing astype view e strided indexing strides C F order slicing w integers as strided broadcasting stride tricks diag CPU cache coherence 8 2 Universal functions 8 2 1 What they are Ufunc performs and elementwise operation on all elements of an array Examples e Automatically support broadcasting casting The author of an ufunc only has to supply the elementwise operation Numpy takes care of the rest The elementwise operation needs to be implemented in C or e g Cython 8 2 Universal functions 174 Python Scientific lecture notes Release 2013 1 Part
15. values are corresponding non zero values efficient for constructing sparse matrices incrementally constructor accepts dense matrix array sparse matrix 11 2 Storage Schemes 218 Python Scientific lecture notes Release 2013 1 shape tuple create empty matrix efficient O 1 access to individual elements flexible slicing changing sparsity structure is efficient can be efficiently converted to a coo matrix once constructed slow arithmetics or loops with dict iteritems use when sparsity pattern is not known apriori or changes Examples create a DOK matrix element by element gt gt gt mtx sparse dok matrix 5 5 dtype np float64 gt gt gt mtx 5x5 sparse Matrix ot type tvpe numpy rloato4q with 0 stored elements in Dictionary Of Keys format gt gt gt for ir in range 5 for ic in range 5 mex lic xe e WO x ccu Je are gt gt gt mtx 5x5 Sperse Matrix ot type lt tyoe numpy tloatoZ2 with 20 stored elements in Dictionary Of Keys format gt gt gt mtx todense Mele ea 40 INL o dee E ee deca Dar AOL LA EE Mee benz Eee ugue tear a Lau euer Cake Oe TAL e ii il P 0 11 slicing and indexing soc oie ele L O20 xoc Mexi Leo lt 1x2 sparse matrix of type type numpy floato4 with 1 stored elements in Dictionary Of Keys format pos camxLT Ls3 2600densew macax uo dee Do poc mcs dq lpcelcodenmscet Tracebac
16. 2 3xx 6xy 15 Ix yl fuu Velie eyes a Eccc It also has limited support for trascendental equations im S isolve expisx sex GUESS SEA 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 rm 10 E er ee Zee ra LL racco E Ouel Lills GC TS ee ee In DES Facco i modulus 3 Quebec ee a ae 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 Tem SESS sies etc qae x38 oy Once sq 1x trus y rrue This tells us that x amp y is True whenever x and y are both True If an expression cannot be true 1 e no values of its arguments can make the expression True it will return False In 14 satisfiable x amp x Out 14 False 16 4 1 Exercises 1 Solve the system of equations x y 2 2 x y 0 2 Are there boolean values x y that make x y amp y x true 16 5 Linear Algebra 16 5 1 Matrices Matrices are created as instances from the Matrix class gt gt gt from sympy import Matrix sc Mabie EIE n To 1 0 0 1 unlike a NumPy array you can also put Symbols in it gt gt gt x Svmboli x gt gt gt y Symbol y oc Ace Matrix a aL gt gt gt A 1 x y BE gt gt gt Axx
17. D diff 297 300 differentiation 297 dsolve 300 equations algebraic 298 differential 300 integration 298 M Matrix 299 P Python Enhancement Proposals PEP 255 147 PEP 3118 183 PEP 3129 1537 PEP 318 150 157 PEP 342 147 PEP 343 157 PEP 380 149 PEP 380 id13 149 PEP 8 152 o solve 298 Index 331
18. Getting started 1D optimization page 255 Gradient based methods page 256 Some intuitions about gradient descent page 256 Conjugate gradient descent page 257 Newton and quasi newton methods page 258 Newton methods using the Hessian 2nd differential page 258 Quasi Newton methods approximating the Hessian on the fly page 260 Gradient less methods page 260 A shooting method the Powell algorithm page 260 Simplex method the Nelder Mead page 261 Global optimizers page 262 Brute force a grid search page 262 Simulated annealing page 262 Practical guide to optimization with scipy page 262 Choosing a method page 262 Making your optimizer faster page 263 Computing gradients page 263 Synthetic exercices page 264 Special case non linear least squares page 264 Minimizing the norm of a vector function page 264 Curve fitting page 265 e Optimization with constraints page 266 Box bounds page 266 General constraints page 266 13 1 Knowing your problem 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 13 1 Knowing your problem 253 Python Scientific lecture notes Release 2013 1 13 1 1 Convex versus
19. a Warning 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 DLL 2 5 4 main and module loading File demo2 py import sys def print a VER IMES d print a print sys argv 2 5 Reusing code scripts and modules 29 Python Scientific lecture notes Release 2013 1 if name aes Due rne 52 print al Importing it In 11 import demo2 b In 12 import demo2 Running it In 13 run demo2 b a 2 5 5 Scripts or modules How to organize your code Note Rule of thumb e Sets of instructions that are called several times should be written inside functions for better code reusability Functions or other bits of code that are called from several scripts should be written inside a module so that only the module is imported in the different scripts do not copy and paste your functions in the different scripts Note How to import a module from a remote directory Many solutions exist depending mainly on your operating system When the import mymodule statement is executed the module mymodule is searched in a given list of directories This list includes a list of installation dependent default path e g usr lib python as well as the list of directories specified by the environment variable PYTHONPATH The list of directories searched by Python is given by the sys path variabl
20. gt gt gt L 2 4 gray purple gt gt gt L yellow blue gray purple whace Note The elements of a list may have different types gt gt gt I 3 200 hello gt gt gt L l5 2007 hello SS oe aie G2 20 hello 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 Python offers a large panel of functions to modify lists or query them Here are a few examples for more details see http docs python org tutorial datastructures html more on lists Add and remove elements gt gt gt L red blue green black white gt gt gt L append pink gt gt gt L V red blue Green black white pink gt gt gt L pop removes and returns the last item pink gt gt gt L red blue green black white gt gt gt L extend pink purple extend L in place gt gt gt L red blue green black whrte pink purple gt gt gt TD oce gt gt gt L wed gt bue green Drack white Reverse
21. gt gt gt a 1 too cramped 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 2 5 Reusing code scripts and modules 32 EE ES eee Use meaningful object names 2 6 Input and Output 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 gt gt gt f open workfile w opens the workfile file gt gt gt type f type file gt gt gt f write This is a test nand another test gt gt gt f close To read from a file In 1 f open workfile r In 2 s f read In 3 print s This is a test and another test In 4 f close For more details http docs python org tutorial inputoutput html 2 6 1 Iterating over a file In 6 f open workfile r In LIT IS for line xm f print line Tais as a TESE and another test In ile E Closs File modes e Read only r e Write only w Note Create a new file or overwrite existing file e Append a file a e Read and Write r Binary mode b Note Use for binary files especially on Windows 26 Input and Output 8 Python Scientific lecture notes Rel
22. gt gt gt it g gt gt gt next it etar yielding 0 0 gt gt gt it Sendi CMH yield returned 11 Vielding I gt gt gt it throw IndexError yield raised IndexError cuv ie ldi ng 2 2 soe Le bosse Los ing Note 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 there s a proposed syntax extension to allow continue to take 7 1 Iterators generator expressions and generators 148 Python Scientific lecture notes Release 2013 1 an argument which will be passed to send of the loop s iterator If this extension is accepted it s 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 7 1 5 Chaining generators Note This is a preview of PEP 380 not yet implemented but accepted for Python 3 3 Let s say we are writing a generator and we want to yield a number of values generated by a second generator a subgenerator If yieldi
23. lt matploclib colorbar Colorbar Instance AC e gt gt gt plt show 3 1 The numpy array object 47 Python Scientific lecture notes Release 2013 1 See Also More in the matplotlib chapter 3D plotting For 3D visualization we can use another package Mayavi A quick example start by relaunching iPython with these options ipython pylab wx or ipython pylab wthread in Python lt 0 10 E 00x25 uL 0248 o4 D 14 Bs 0714 0457 In 58 from mayavi import mlab In 61 mlab surf image Out leI senthought meayavicsmodules surrace ourrace object St i In 62 mlab axes Out 62 enthought mayavi modules axes Axes object at gt The mayavi mlab window that opens is interactive by clicking on the left mouse button you can rotate the 3 1 The numpy array object 48 Python Scientific lecture notes Release 2013 1 image zoom with the mouse wheel etc For more information on Mayavi http github enthought com mayavi mayavi See Also More in the Mayavi chapter page 287 3 1 6 Indexing and slicing The items of an array can be accessed and assigned to the same way as other Python sequences e g lists gt gt gt a np arange 10 gt gt gt a array lOr d 2 Oo 4 57 Ge lt 1 Sy 91 scc Olly ale sla Oy 27 9 Warning Indices begin at 0 like other Python sequences and C C In contrast in Fortran or Matlab indices begin at 1 For multidimensional arrays inde
24. pass Removing a dynamic listener can be done by calling the remove trait listener method on the trait with the listener method as argument calling the on trait change method with listener method and the keyword remove True deleting the instance that holds the listener Listeners can also be added to classes using the on trait change decorator from traits api import HasTraits Instance DelegatesTo Float Range from traits api import Property on trait change from reservoir import Reservoir class ReservoirState HasTraits Keeps track of the reservoir state given the initial storage For the simplicity of the example the release is considered in hm3 timestep and noc in m3 s n m m reservoir Instance Reservoir 05 max storage DelegatesTo reservoir min_release Float max_release DelegatesTo reservoir state attributes storage Property depends_on inflows release Xx controd Bal ributes int lows Float desc Intlows Tams release Range low min_release high max_release 14 3 What are Traits 281 Python Scientific lecture notes Release 2013 1 spillage Property desc Spillage hm3 depends_on storage inflows release Private traits FFFFETEFEEEEEEEEEEE EERE EEE EEE ETE EE HH ET EEE _storage Float Traits property implementation Feeeeeeeeeeeeeeeeeaeteeee eee ttt def _get_storage self new storage
25. 11 def print sorted collection try collection sort except AttributeError pass print collection In l2 prine oorted ll 3 21 ge el In 13 prank sorred ser CL 2 set 2p ze in 14 print sortegd 1327 T32 2 8 3 Raising exceptions e Capturing and reraising an exception 2 8 Exception handling in Python 39 Python Scientific lecture notes Release 2013 1 15 def filter name name try name name encode ascii except UnicodeError e if name Ga8 amp l print OK Ga l else raise e return name In 16 filter _name Ga l OK Ga l Out 16 GaWMxc3Nxabl In 17 filter name St fan UnicodeDecodeError ascii codec can t decode byte Oxc3 in position 2 ordinal not in range Exceptions to pass messages between parts of the code In 17 def achilles arrow x 1f absz 1 e raise StopIteration le return x In 18 In 19 while True try X achilles arrow x except StopIteration break In 20 x Gu TID 0299702343715 Use exceptions to notify certain conditions are met e g StopIteration or not e g custom error raising 2 9 Object oriented programming OOP Python supports object oriented programming OOP The goals of OOP are to organize the code and to re use code in similar contexts Here is a small example we create a Student class which is an object gathering several custom functions
26. 16 5 Linear Algebra 299 Python Scientific lecture notes Release 2013 1 pu A Yy 2x Dos ce sese 16 5 2 Differential Equations SymPy is capable of solving some Ordinary Differential Equations sympy ode dsolve works like this Ts Poe Gx ss clie se ae er espe OEC ria 15 elsi as ME S 0LEE E A S r IE C PEE Out 5 Cl xsin x C2xcos x 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 In 6 dsolve sin x cos f x cos x sin f x f x diff x f x hint separable Out 6 log 1 sin f x 2 2 C1 log 1 sin x 2 2 16 5 3 Exercises 1 Solve the Bernoulli differential equation x f x diff x f x f x 2 Warning TODO correct this equation and convert to math directive 2 Solve the same equation using hint Bernoulli What do you observe 16 5 Linear Algebra 300 CHAPTER 17 scikit learn machine learning in Python author Fabian Pedregosa Gael Varoquaux machine learning in Python Prerequisites e Numpy Scipy Python e matplotlib e scikit learn http scikit learn org Chapters contents Loading an example dataset page 302 Learning and Predicting page 303 Classification page 303 k Nearest neighbors classifier page
27. 2nd differential 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 13 2 A review of the different optimizers 258 Python Scientific lecture notes Release 2013 1 An ill conditionned quadratic function DELLI Note that as the quadratic approximation is exact the Newton method is blazing fast An ill conditionned non quadratic function 1 LLL E Here we are optimizing a Gaussian which is always below its quadratic approximation As a result the Newton method overshoots and leads to oscillations An ill conditionned very non quadratic function In scipy the Newton method for optimization is implemented in scipy optimize fmin nocg cg here refers to that fact that an inner operation the inversion of the Hessian is performed by conjugate gradient scipy optimize fmin tnc can be use for constraint problems although it is less versatile gt gt gt def f x Ihe rosenbrock function P return 25 40 I oo e se Dur Sc Os Zee gt gt gt def fprime x return Nosarray 27 5 1 P9 42ex O0 gt Coll x0 ee2 25 eb 0 ese 2 e e gt gt gt optimize fmin ncg f 2 2 fprime fprime Optimization terminated successfully Current function value 0 000000 Iterations 10 Humctvon evaluar toms 12 Gradient evaluations 44 Hessian evalu
28. DNDEBUG og ivr y Os Wall Weerilet ererotypes fPIC goce peliread shared build temo lanux lt 36 764 2 1 7 cos doubles o build temp linu x26 64 2 7 cos_d ls bualel zos doubles cos doubles se cos doubles h cos doubles Pys cos doubles so setup py And as before we convince ourselves that it worked 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 by oue c y pylab show 18 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 PartofCPython Compiled Autogenerated Numpy Support Python C Api True Clypes Cython 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 18 7 Further Reading and References e Ga l Varoquaux s blog post about avoiding data copies provides some insight on how to handle memory management cleverly If you ever run into issues with large datasets this is a reference to come back to for some inspiration 18 6 Summary 328 Python Scientific lecture notes Release 2013 1 18 8 Exercises Since this is a brand new section the exercises are considered more a
29. Keeping track of enumeration number 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 gt gt gt words cool powerful readable gt gt gt for i in range 0 len words print 1 words i D cool 1 powerful 2 readable But Python provides enumerate keyword for this gt gt gt for index item in enumerate words print index item O cool 1 powerful 2 readable Looping over a dictionary Use iteritems pos gp uere ul wd Pe Say gt gt gt for key val in d iteritems print Key s has value s key val Key a has value 1 Key c has value 1j Key b bas values 1 2 2 3 6 List Comprehensions gt gt gt l 2 for i in range 4 coy ly 4 J 2 3 Control Flow 20 Python Scientific lecture notes Release 2013 1 Exercise Compute the decimals of Pi using the Wallis formula CO 4i r 2 4i 1 4 1 2 4 Defining functions 2 4 1 Function definition In 56 def test RUE print in test function In 57 test dm best Euher ven Warning Function blocks must be indented as other control flow blocks 2 4 2 Return statement Functions can optionally return values In 6 def disk_area radius return 3 14 x radius x radius In 8 disk area 1 5 Orwel 7206499999999599995 Note By default functions return None Note Note the
30. Take home message conditioning number and preconditioning If you know natural scaling for your variables prescale them so that they behave similarly This is related to preconditioning 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 iterations function calls DAE 0 20 40 60 80 100 120 140 A well conditionned quadratic function iterations function calls Error on f x 1 5 DAE O 200 400 600 800 100012001400 An ill conditionned quadratic function iterations function calls Error on f x 5 ers 200 400 600 800 1000 1200 An ill conditionned non quadratic function iterations function calls j 5 A ass 1 200 400 600 800 1000 1200 An ill conditionned very non quadratic function The more a function looks like a quadratic function elliptic iso curves the easier it is to optimize Conjugate gradient descent 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 the valley 13 2 A review of the different optimizers 257 Python Scientific lecture notes Release 2013 1 The co
31. The following C extension module make the cos function from the standard math library available to Python 18 2 Python C Api 313 Python Scientific lecture notes Release 2013 1 je Example Cf wrapping cos function From methn with che Python C ABT 4 7 include Python h wi OC mde lt mMATN a fe wrapped cosine function statio PyOb Jece Cos tune PyObyect sel PwvObJjectse args double value double answer parse the input from python float to c double if PyArg Parseluple args d amp value return NULL if the above function returns 1 an appropriate Python exception will have been set and the function simply returns NULL fe Call Cos from 1 ibm 7 answer cos value Ye SCONStrUCE Lhe GuEput Brom cos rom Cc doublo to Py non foe a7 return Py BuildValue f answer define functions in module static PyMethodDef CosMethods cos func cos func METH VARARGS evaluate the cosine NUCL MOLL 0O MULD by a module Afni btaliz7arion 7 PyMODINDT_ FUNC initcos module void i 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 extension
32. dimension reduction pca decomposition RandomizedPCA n_components 150 whiten True poss Ete xX eran x train ped e possem Oem x train X test pca pca transform X test wu gesbseesIdom Ton clf svm SVC C 5 gamma 0 001 Citi cd NOG SEXE me e oJ se wise 17 5 Putting it all together face recognition 309 Python Scientific lecture notes Release 2013 1 predict on new images for i in range 10 print lfw people target names clf predict X test pca i 01 1 _ pl imshow X test i reshape 50 37 cmap pl cm gray _ raw input 17 6 Linear model from regression to sparsity Diabetes dataset The diabetes dataset consists of 10 physiological variables age sex weight blood pressure measure on 442 patients and an indication of disease progression after one year gt gt gt diabetes datasets load diabetes gt gt gt diabetes X train diabetes data 20 gt gt gt diabetes X test diabetes data 20 gt gt gt diabetes y train diabetes target 20 gt gt gt diabetes y test diabetes target 20 The task at hand is to predict disease prediction from physiological variables 17 6 1 Sparse models 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 approa
33. docs scipy org doc The search button is quite useful inside the reference documentation of the two packages http docs scipy org doc numpy reference and http docs scipy org doc scipy reference Tutorials on various topics as well as the complete API with all docstrings are found on this website Numpy and Scipy Documentation SciPy v0 8 dev Reference Guide DRAFT next modules index Z SciPy Release 0 8 dev Date February 11 2010 SciPy pronounced Sigh Pie is open source software for mathematics science and engineering e SciPy Tutorial o Introduction o Basic functions in Numpy and top level scipy o Special functions scipy special Table Of Contents SciPy o Integration scipy integrate Reference o Optimization optimize o a i H Next topic Interpolation scipy interpolate 3 o Signal Processing signal cxi PUT Lu o Linear Algebra This Page o Statistics o Multi dimensional image processing ndimage o File IO scipy io Resources o Weave e Release Notes Show Source Scipy org website Edit page Reference Quick search e Clustering package scipy cluster e Constants scipy constants e Fourier transforms scipy fftpack Go e Integration and ODEs scipy integrate Enter search terms or a module e Interpolation scipy interpolate class or function name e Input and output scipy io e Linear algebra scipy linalg e Maximum entropy models scipy maxentrop
34. from the minima of the histogram 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 sumor np bincount to compute the grain sizes 8 Compute the mean size of bubbles Proposed solution gt gt gt import numpy as np gt gt gt import pylab as pl gt gt gt from scipy import ndimage 5 11 Summary exercises on scientific computing 134 Python Scientific lecture notes Release 2013 1 5 11 4 Example of solution for the image processing exercise unmolten grains in glass Det Spot Mag MV 15 05 2009 1280 C 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 gt gt gt dat plor mreead data MV HFV 012 Jpg 2 Crop the image to remove the lower panel with measure information gt gt gt dat dat 60 3 Slightly filter the image with a median filter in order to refine its histogram Check how the histogram changes gt gt gt filtdat ndimage median filter dat size 7 7 gt gt gt hi dat np histogram dat bins np arange 256 gt gt gt hi
35. gt gt gt COOUZ optimrize rtsolve f 2 5 gt gt gt root array 2 47948183 Curve fitting Suppose we have data sampled from f with some noise gt gt gt xdata np linspace 10 10 num 20 gt gt gt ydata f xdata np random randn xdata size 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 gt gt gt def fF2 x a D return axx 2 b np sin x Then we can use scipy optimize curve fit to find a and b gt gt gt guess 2 2 gt gt gt params params Covariance optimize curve_fit f2 xdata ydata guess gt gt gt params array T 0 99923477 tous Now we have found the minima and roots of and used curve fitting on it we put all those resuls together in a single plot 5 5 Optimization and fit scipy optimize 113 Python Scientific lecture notes Release 2013 1 120 f x 100 Curve fit result e e Minima 80 v v Roots 60 Gq 40 20 O 20 10 Note In Scipy gt 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 You can find algorithms with the same functionalities for
36. gt print mtx 07 0 1 du T 2 27 2 3 597 3 4 MEET 2 27 1 6 95 123 7 One 325 LI ec 12 gt gt gt mtx todense icu a e iil L Oe 1s mc c M o Uu doe S ug Ur 0p Fa pg explanation with a scheme offset row 2 9 1 10 0 1 11 11 2 Storage Schemes 216 Python Scientific lecture notes Release 2013 1 1 5 2 12 2 6 3 3 7 4 8 matrix vector multiplication gt gt gt vec np ones 4 gt gt gt vec array L IE I Lal gt gt gt mtx vec array L257 lap eur d 1 gt gt gt mtx toarray vec cana cto AMICI D Vn es On A s Pe Duo quse P 0s On ore Oy etr Oe pe 4 List of Lists Format LIL row based linked list each row is a Python list sorted of column indices of non zero elements rows stored in a NumPy array dt ype np object non zero values data stored analogously efficient for constructing sparse matrices incrementally constructor accepts dense matrix array sparse matrix shape tuple create empty matrix flexible slicing changing sparsity structure is efficient slow arithmetics slow column slicing due to being row based use when sparsity pattern is not known apriori or changes example reading a sparse matrix from a text file Examples create an empty LIL matrix gt gt gt mtx sparse lil matrix 4 75 prepare random data gt gt gt from numpy
37. home emma user defined modules if new path not in sys path SyS path append new path 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 http docs python org tutorial modules html for more information about modules 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 MIS cl ster Co README txt Susie 2S Contig py LATERO i C Sccu od SVN Version py BOC Odie cee o vic Pull ley setup pyc __svn_version__ pyc CONSU bs SE aree setupscons py THANKS txt Eft pack linsolve setupscons pyc COCHAN GR txt Psi E maxentropy signal version py Lane pyc mise sparse version pyc ENS PAG c Ca ndimage spatial weave integrate odr special interpolate optimize stats s 0d ndamage S ls doccer py fourier pye Interpolation e morro logy pyc Setup py doccer pyc INTO py interpolation pyc _nd_image so setupscons py fulrers ouv anfo pye measurements py COD SUpport py SeCLUpSCons pyc filters pyc __init__ py measurements pyc Mi S6 o19 096 5 pO IE ENSE S fourier po aide Soyo mie pp OS OG
38. vputeconuputcesevEesLel NPY CDOUBRLE elementwise funcs 0 lt void gt mandel_single_point Toop ctumcsj l1 B EImmucc EB Pmpuc coutpuce tvpes 5 NEY CEhORT Input oUt put types 4 NPY CFLOAT Jupe output evpesisl NECSOEBORT elementwise funcs 1 lt voidk mandel single point singleprec mandel PyUFunc_FromFuncAndData Loco ume elementwise funcs input SOS GIOI types 27 d MUMber Of Supported mou Cypre pe uc LU 2 ut number Of input args 1 number of output args O identity element never mind this 8 2 Universal functions 181 EE eee mandel function name mandellz C gt qomputes iterated Zaz set docet a TIG 0O unused 8 2 4 Generalized ufuncs ufunc output elementwise_function input Both output and input can be a single array element only generalized ufunc output and input can be arrays with a fixed number of dimensions For example matrix trace sum of diag elements input shape n n output shape l e scalar SON ML NL Matrix product input 1 shape m n tnput 2 shape n p output shape m p Qr Alr na P e n p e This is called the signature of the generalized ufunc e The dimensions on which the g ufunc acts are core dimensions Status in Numpy e g ufuncs are in Numpy already e new ones can be created with PyUFunc_FromFuncAndDataAndSignature e but we don t ship with public g ufuncs except for testing
39. 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 M sparse matrix dense matrix LinearOperator Preconditioner for A The preconditioner should ap proximate 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 common interface for performing matrix vector products useful abstraction that enables using dense and sparse matrices within the solvers as well as matrix free solutions e has shape and matvec some optional parameters example gt gt gt import numpy as np gt gt gt from scipy sparse linalg import LinearOperator gt gt gt def mv v return up array Ll2 v 10 3 v 1 gt gt gt A LinearOperator 2 2 matvec mv gt gt gt A 2x2 LinearOperator with unspecified dtype gt gt gt gt A matvec np ones 2 anna 2 4 Sealy gt gt gt A x np ones 2 Bursa 2p 32l 11 3 Linear System Solvers 228 Python Scientific lecture notes R
40. 2 Le reorder dimensions first to levell spinl level2 spin2 and then reshape gt correct matrix product 3 2 5 Sorting data Sorting along an axis soo a Mp array i 47 38 5 dev xb gt gt gt b np sort a axis 1 gt gt gt b array Lbs 4 51 Note Sorts each row separately In place sort gt gt gt a sort axis 1 gt gt gt a array Uber sd 0 Lgs alge x2 de Sorting with fancy indexing sso a mp rvarray 4 37 d 21 gt gt gt j np argsort a gt gt gt j dima M ES E 3 2 Numerical operations on arrays 65 gt gt gt a j dps d x d Python Scientific lecture notes Release 2013 1 Finding minima and maxima gt gt gt a np array 4 3 1 2 gt gt gt J max np argmax a 2x jJ min Np argmin a gt gt gt J max J m n O 2 3 2 6 Some exercises 3 2 Numerical operations on arrays 66 Python Scientific lecture notes Release 2013 1 Worked example Framing Lena Let s do some manipulations on numpy arrays by starting with the famous image of Lena http www cs cmu edu chuck lennapg scipy provides a 2D array of this image with the scipy lena function gt gt gt from scipy import misc gt gt gt lena misc lena Note In older versions of scipy you will find lena under scipy lena Here are a few images we will be able to obtain with our manipulations use different colormaps crop the image c
41. 2 The block of code underneath with is executed Just like with t ry clauses it can either execute success fully 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 X method is called If an exception was thrown the information about the 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 berethrown after exit is finished Let s say we want to make sure that a file is closed immediately after we are done writing to it gt gt gt class closing object def init__ self obj self obj obj def enter self return self obj def exit self xargs ee selt obj elose gt gt gt with closing open tmp file w as f fowrite thecconmtentsin 7 3 Context managers 157 Python Scientific lecture notes Release 2013 1 Here we have made sure that the 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 Ithas an___exit___ method which calls close and can be used as a context manager itself gt gt gt with open tmp file fa as f fawrieTek mor Con ent m The common use for try finally is releasing resources Various different cases are implemented similarly in the __enter__ phase the resource is acq
42. 2o NP iinfo np Uint o4 max od c 1 18446744073709551615L 18446744073709551615L Floating point numbers 22 gt Ap rinio np Tloat nepe posso gc en eo MP Ed OX OISIEISIEG Su dr epe 2227044004975 05191891 6 gt gt gt np float32 1e 8 np float32 1 1 True gt gt gt np float64 1e 8 np float64 1 1 Falce Complex floating point numbers complex64 two 32 bit floats complex128 two 64 bit floats complex192 two 96 bit floats platform dependent two 128 bit floats platform dependent Smaller data types If you don t know you need special data types then you probably don t Comparison on using float32 instead of float 64 Half the size in memory and on disk Half the memory bandwidth required may be a bit faster in some operations In 1 a np zeros 1e6 dtype np float64 in 2 b np zeros le6 dtype np float32 In 3 timeit axa TODO Looms best or 3S 1 76 ms per loop In 4 timeit bxb 1000 l 6 o0ps best or 3S 1 07 ms per Loop But bigger rounding errors sometimes in surprising places i e don t use them unless you really need them 3 3 2 Structured data types oat float 3 3 More elaborate arrays 74 Python Scientific lecture notes Release 2013 1 samples np zeros 6 dtype sensor code S4 position Eloac value boast samples ndim samples shape 6 gt gt gt samples dtype names sensor code po
43. 51 S2 Sn C dj41d 42 dn X itemsize 8j dido dj X itemsize Note Now we can understand the behavior of view gt gt gt y np array l t 3 12 4l dtype np uint9 transpose gt gt gt x y copy Transposition does not affect the memory layout of the data only strides gt gt gt x strides a gt gt gt y Strides ly 2 gt gt gt str x data EXO T DP US SAT 22x Ser Vodet s 701 pP S gia the results are different when interpreted as 2 of int16 e copy creates new arrays in the C order by default Slicing with integers e Everything can be represented by changing only shape strides and possibly adjusting the data pointer Never makes copies of the data gt gt gt x Movarray ly 27 37 Ee 5p 6l odtypeenpsgtmtS2 pose wo sese gt gt gt y array iG Su du x 2 di dtype int2 8 1 Life of ndarray 169 Python Scientific lecture notes Release 2013 1 gt gt gt y strides 4 gt gt gt y x 2 25 v rray interrace datasa l0 x array interftace data FIO 8 gt gt gt x unpizeros l0 10 10 dtyoe np float 2o xX Strides 8007 60 B pocos duc Ae oeri des 1600 7 240 32 e Similarly transposes never make copies it just swaps strides gt gt gt x Np zeros 10 10 10 dtype np tloat gt gt gt x strides S00 SO e poc xil ctrides ov 320 200 But not all reshaping operations can be re
44. ATM gt gt gt import numpy core umath_tests as ut ee Ul moque eeu e m n n p m p gt gt gt x np ones 10 2 4 gt gt gt y np ones 10 4 5 gt gt gt uUt matri x multiply x y shape O 1 e the last two dimensions became core dimensions and are modified as per the signature e otherwise the g ufunc operates elementwise e matrix multiplication this way could be useful for operating on many small matrices at once Generalized ufunc loop Matrix multiplication m n n p gt m p 8 2 Universal functions 182 Python Scientific lecture notes Release 2013 1 void gufunc loop void xargs int dimensions int xsteps void xdata char input 1 char args 0 these are as previously char input 2 char args 1 char output char args 2 int input l stride m steps 3 strides for the core dimensions 7 we ere cadded atter the noa core w int input 1 stride n steps 4 T o e int input_2_strides_n steps 5 6 T 8 int input_2_strides_p steps int output strides n steps int output strides p steps int m dimension 1 core dimensions are added after int n dimension 2 the main dimension order as in int p dimension l 74 signature 47 int i fort 1 0 uc damenscvenstOols bg marcm l ror s tua deco med ross inputs npe Output strides for each array input 1
45. BRE SEES Writing faster numerical code a wa shoe ioe Seb EGER Bow Ge eee POR EORR Xo xs Sparse Matrices in SciPy 11 1 11 2 l trod cton s sso sedesa ia eee E S eb ee ee E SOR GRIS A Ros dE Sm 6 Sne oe e C Ls o Ros bd Rm ESG 2d xh x ox db BESO Raf Wu d eg I Linear Systemi SOIVErS uuu uou S EC o EUM Ro E Ga Geage Uy b RON qox 444 OR oe 11 4 Other Interesting Packages 22644060445 FER 9 ORO 39 HEER OE oS 3o EE G6 e EEE d Image manipulation and processing using Numpy and Scipy 12 1 12 2 12 5 12 4 12 3 12 6 Opening and writing to image files 2 2a o aaa eee Ee ee ee ee Se a ee REGE Displaying WAGs Ge ewe ee a RUE EGROR BOE e R ee SIM HOP REG oe ee eS Basic manipulations 22s em omocp Rom RUE ede RO UE GR ROGR ee na we ene RO Pew eG Image GCOS x 5 43 32x 4 ee ERS ER ES Ree Be ee Feature extraction L2 ie tie 6S S646 EEE ED SHH GSES RO SRI Ro 44 44 439 EUG Measuring objects properties ndimage measurements Mathematical optimization finding minima of functions 13 1 13 2 13 3 13 4 53 Traits Knowing your problem 4222 xx om 24 Se X XOXOA RORORO x 3b EORR OROXOE x ROS 45 A review of the different optimizers 2s oso 9or 9 ow ow xo OR Row Ro REO CE POR o OR OR OR RO Practical guide to optimization with SCIDY 2 4 ooo 9 ono domom om O9 ROO OS xS Special case non linear least squares 4 24 9o RR RR OX RR X Roo y RR Optimization with constraints uu oos o9 9x eu beeen
46. Calculate the expanded form of x y 2 Simplify the trigonometric expression sin x cos x 16 3 Calculus 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 gt 0 you would issue limit f x 0 sc ine Ce ity xe r0 E you can also calculate the limit at infinity Doe xmas sep of OO OO gt gt gt limit 1 x 00 0 gt gt gt limit x x x 0 al 16 3 2 Differentiation You can differentiate any SymPy expression using diff func var Examples soc sii Six oe Coe x gt gt gt Gift sini 22x 2 x 2eCOS 2 x gt gt gt Giff tan x x 1 tan x 2 You can check that it is correct by gt gt gt limit tan xty tan x y y 0 a eam Higher derivatives can be calculated using the diff func var n method o gt E sme v s 1 2eCOs x s gt s diri Sin 23 Se 2 4xsin 2 gt x e SSINTIN 2 ce mes 25 163 Calculus ge Python Scientific lecture notes Release 2013 1 16 3 3 Series expansion SymPy also knows how to compute the Taylor series of an expression at a point Use series expr var gt gt gt Series cos x xX EEE eee A deua uie series 1 cos x x 1 x 2 2 5b x x x4 24 O xx x 6 16 3 4 Exercises 1 Calculate lim x gt 0 sin a x 2 Calulate the derivative of log x for x 16 3 5 Integration SymPy has su
47. Jaks TEY InP dimensions NPY 10L Steps Voldy void PyUPUnG d d char args npy_ inp dimensions movent pe steps vord Func Vorld PYUP UNG Eo Chark argo NEY Intp imens ions Ney INP Steps volds ume void PyUkunc g g Chars s args Npy in ips dimensions nP int ps Steps voids dune void PyUkunc F F AS D Dchar args mpyrcuantpe dimensions Apy Intp Seeps Oso void PyUkuUNC F F Char s args Npy intpp dimensions Moy intps Steps vold func void PYUPUNG D D chars args mpy 1ntps dimensions NOY Intp Steps voids func word PyYUPUNG G G char args Npy_intpx lt dimensions NPY Intp steps Vords Tune youd PURUN eee excl els aree eee S aE n pe damens lons y ne Steos vold func void PyUkunc fi Chat arge Moy Ite dimensions NPY 1InNCP S BOIS Voids FUNC void PyUku unc Jd obitum s bsp dimensions NPY intp sbepse voids TUNC vord PyUPUNne gg g chars argar npy intip dimensions Mpy Int Steps vold Tune VOL PyURUN EE EP CAS DD D chNnar s arge Dey inip dimensions Apy Intp Steps vold func void PyUFunc DD Dchar args Npy intp dimensions Npy intps Steps volds TUNC vord PyUPUncC_PRPIE cChar x arger Npy Intp dimensions Npy intpp steps volds une void E SIEG oae arge NPY Itp dimensions NPY 1nCpP Secps Voids TUNC Required module initialization 8 2 Universal functions 177 Python Scientific lecture notes Release 2013 1 import array import Urune The actual ufune cleclarcation cdef PyUFuncGene
48. SOM coe Sry OSes ly number of supported nput types TODO 4 Number of input args TODO number or output args 0 identity element never mind this mandel function name mandel z gt computes 2 2 k t F docstring O unused Reminder some pre made Ufunc loops 8 2 Universal functions 178 Python Scientific lecture notes Release 2013 1 PyUfunc f f float elementwise_func float input 1 PyUfunc ffj ffloat elementwise func float input 1 float input 2 PyUfunc d d double elementwise func double input 1 PyUfunc_dd Mouble elementwise func double input 1 double input 2 PyUfunc D D elementwise func complex double xinput complex doublex PyUfunc DD DBlementwise func complex double inl complex double xin2 mt emper doubler wt T Type codes N YABOOD NEYREY EE NEUE Ip psi pU BT SIE abro SU IE NEY LONG Ese E nS NEY IC RIS ORG ESO T NEY DOE EE NPY_LONGDOUBLE NPY_CFLOAT NPY_CDOUBLE NPY_CLONGDOUBLE NPY DATE e NEN MED EINA NERO BIET NEY SoIRING NE YAUN ICODE NEST AVOND 8 2 3 Solution building an ufunc from scratch The elementwise function cdef void mandel single point double complex xz in double complex c 1n double complex z out nogi The Mandelbrot iteration Some points of note Ita aNOT allowed to call amy Python functions here The Ufunc loop runs with the Python Global Interpreter Lock released Hence the nogil f And so al
49. Ve VA setup py From Ipython In 1 import scipy In 2 Seupy rile __ Out lolo ner lsb pstuon2z o dxstepackudges scrpy Init _ oyc In 3 import scipy version In 4 scipy version version OL ec Vu ODE In 5 import scipy ndimage morphology In 6 from scipy ndimage import morphology 2 5 Reusing code scripts and modules 31 Python Scientific lecture notes Release 2013 1 In LlIT7 morphology binary dilationf Type TASTE em Base Class suse S INO som gt edges Form lt fu unctCion binary dilation at O0x bedds4 gt Namespace Interactive File usr lib python2 6 dist packages scipy ndimage morphology py Definition morphology binary dilation input structure None iterations 1 mask None output None border value 0 origin 0 brute force False Docst ring Multi drimensional binary dilation with the given structure An output array can optionally be provided The origin parameter controls the placement of the filter If no structuring element is provided an element is generated with a squared connectivity equal to one The dilation operation is repeated iterations times If iterations is less than 1 the dilation is repeated until the result does not change anymore If a mask is given only those elements with a true value at the corresponding mask element are modified at each iteration 2 5 7 Good practices Note Good practices ndentation no choice Indenting is compulsory i
50. Versions 2 5 List of command line arguments passed to a Python script In 100 Sys artgv OUE TIO lt Users cours local biny toytnon sys path is a list of strings that specifies the search path for modules Initialized from PYTHONPATH In 1121 soys2pari Ome SEA e aor Users cburns locally bin yjUsers cbourns local lib povythonZ 5 site packages ogrim 1 l py2 5 e0q0 Users cburns local lib python4 5 site packages argparse U 8 0 py2Z 5 eqq Users courns local lib pyenon2 5 site packages Urwild 0 9 7 l py2 5 e00 Users courns local ilib pyenen2 5 site packages jvolk 0 4 1 py2 5 e00 s Users7 courns local lib pyehon2 5 site packages Virtualeny l 2 pyZ aed 2 7 Standard Library 37 Python Scientific lecture notes Release 2013 1 2 7 5 pickle easy persistence Useful to store arbitrary objects to a file Not safe or fast In 1 import pickle In I2 1 1 None Stan In 3 oi ckle dumo ly file rest hl 7a In 4 pickle load file test pkl Our 4 e 1 Nene stan Exercise Write a program to search your PYTHONPATH for the module site py path_site 2 8 Exception handling in Python It is highly unlikely that you haven t yet 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 Exception
51. a type definition that can be used for normal Python object attributes giving the attributes some additional characteristics Standardization Initialization Validation Deferral Notification e Visualization Documentation 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 The common way of creating a traits class is by extending from the HasTraits base class and defining class traits from traits api import HasTraits Str Float class Reservoir HasTraits name Str max_storage Float EE ES eee Warning For Traits 3 x users 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 reservoir Reservoir name Lac de Vouglans max storage 005 14 3 1 Initialisation All the traits do have a default value that initialise the variables For example the basic python types do have the following trait equivalents Python Type oolean omplex number Floating point number 000 OO Plain integer ong integer string u Unicode yu
52. an expression on the right hand side is evaluated the corresponding object is created obtained 2 aname on the left hand side is assigned or bound to the r h s object Things to note e a single object can have several names bound to it In LED S de 2 34 In 2 b a In 3 a ore hit dite ere aa In 4 b Ome ae que 94 In 5 a xs b Outils True In G6 2 ee Shae In LTIS a Dy qua eerte c3 to change a list in place use indexing slices in Il a ie 2524 794 In 3 a Dar Tow f fJ 32 5 In 4 a a b c Creates another object In 5 a SUG Ws ea oe Sar Tl In 6 id a Ome 6 459604106376 In 7 22 le Ze 291 4 Mocirres Object in place In 8 a Du oye ihe 2 oul in 9 id a Oue Pl 1396421676 3 Same ss un Cul lol yours will QilT r the key concept here is mutable vs immutable mutable objects can be changed in place immutable objects cannot be modified once created A very good and detailed explanation of the above issues can be found in David M Beazley s article Types and Objects in Python 2 3 Control Flow Controls the order in which the code is executed 2 3 1 if elif else gt gt gt if 2x 2 Pili Obwocoust Obvious Blocks are delimited by indentation 2 3 Control Flow 17 Python Scientific lecture notes Release 2013 1 Type the following lines in your Python interpreter and be careful to respect
53. an illustration a noisy input signal may look like gt gt gt time_step 0 02 gt gt gt period 5 gt gt gt time vec np arange 0 20 time step poo Sig mesa 2c m a 7 period aa tne ya a x 0 5 np random randn time vec size The observer doesn t 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 sym metric The scipy fftpack fftfreq function will generate the sampling frequencies and scipy fftpack fft will compute the fast Fourier transform gt gt gt from scipy import fftpack gt gt gt sample freq fftpack fftfreq sig size d time step 22 gt SUO OEIL Tipos birt E Because the resulting power is symmetric only the positive part of the spectrum needs to be used for finding the frequency gt gt gt pidxs np where sample freq gt 0 gt gt gt freqs sample freq pidxs gt gt gt power np abs sig_fft pidxs Peak frequency _ 0 050 100 150 200 250 300 350 400 45 Frequency Hz The signal frequency can be found by gt gt gt freq freqs power argmax cox Np ellelose rreq 15 pericd f check that correct freq is found gue Now the high frequency noise will be removed from the Fourier transformed signal 5 4 Fast Fourier transforms scipy fftpack 107 Python Scientific lecture notes Release 2013 1 gt gt gt sig fft np abs sample fr
54. areas gt 100 gt gt gt remove small sand mask sand labels ravel reshape sand labels shape 8 Compute the mean size of bubbles gt gt gt bubbles labels bubbles nb ndimage label void gt gt gt bubbles areas np bincount bubbles labels ravel 1 gt gt gt mean bubble size bubbles areas mean gt gt gt median bubble size np median bubbles areas gt gt gt mean bubble size median bubble size 5 11 Summary exercises on scientific computing 137 Python Scientific lecture notes Release 2013 1 boar oy VO 5 11 Summary exercises on scientific computing 138 CHAPTER 6 Getting help and finding documentation author Emmanuelle Gouillart Rather than knowing all functions in Numpy and Scipy it is important to find rapidly information throughout the documentation and the available help Here are some ways to get information In Ipython help function opens the docstring of the function Only type the beginning of the func tion s name and use tab completion to display the matching functions In 204 help np v np vander np vdot np version np voLd0 np vstack Mp Vad np vectorize np void Diy Sp late In 204 help np vander 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 e Numpy s and Scipy s documentations can be browsed online on http
55. 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 18 8 2 Ctypes 1 Modify the Numpy example such that cos doubles func handles the preallocation for you thus mak ing it more like the Numpy C API example 18 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 mak ing 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 x 18 8 Exercises 329 Python Scientific lecture notes Release 2013 1 18 8 4 Cython 1 Look at the code that Cython autogenartes 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 mak ing it more like the Numpy C API example 18 8 Exercises 330
56. choosing estimators and their parameters 17 7 1 Grid search and cross validated estimators Grid search The scikit learn provides an object that given data computes the score during the fit of an estimator on a parameter grid and chooses the parameters to maximize the cross validation score This object takes an estimator during the construction and exposes an estimator API gt gt gt from sklearn import svm grid_search ooo gammas no logspace 6 1 10 gt gt gt SVC Svm SVC gt gt gt clf grid search GridSearchCV estimator svc param grid dict gamma gammas n jobs 1 lose Clit parece ccc 1000 digits eerie er TESI GridSearchCVv cv None estimator SVC C 1 0 gt gt gt Cli best score ooo T SOOT Sd e gt gt gt clf best estimator gamma 0 00059948425031894088 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 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 gt gt gt from sklearn import linear_model datasets gt gt gt lasso linear_model LassoCV gt gt gt diabetes datasets load diabetes gt gt gt X diabetes diabetes data gt gt gt y
57. 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 Null Locator see below Tick Locators Tick locators control the positions of the ticks They are set as follows ax pl gca x xaxis set major locator eval locator NullLocator MultipleLocator 1 0 0 1 2 3 4 5 6 7 8 9 10 FixedLocator 0 2 8 9 10 eee ee ee ee ee ae ee re ae ae ee 0 2 8 9 10 IndexLocator 3 1 1 4 7 10 LinearLocator 5 0 2 5 5 0 7 5 10 LogLocator 2 1 0 1 2 4 8 AutoLocator There are several locators for different kind of requirements 2 4 6 10 All of these locators derive from the base class matplotlib ticker Locator You can make your own locator deriving from it Handling dates as ticks can be especially tricky Therefore matplotlib provides special locators in matplotlib dates 4 4 Other Types of Plots examples and exercises Regular Plot pl plot Plot lines and or markers 93 Bar Plot pl bar Contour Plot pl contour Make a bar plot with rectangles Draw contour lines and filled contours page 93 page 94 4 4 Other Types of Plots examples and exercises 91 Imshow pl imshow Display an image to current axe
58. contained in the file cos module pyx veu Example Or Wrapping Cos TUN CLOD From mas D Using Cy cion EEn cdef extern from math h double cos double arg def cos _tunci arg return cos arg 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 CVLEDnOnDIstutilLs from distutils core import setup Extension from Cython Distutils import build ext setup cmdclass build_ext build sexk ext modules Extension cos module cos module pyx Compiling this cd advanced interfacimg with e cvthon BS cos module pyx setup py B python Setup ey build ext inplace running build ext coc horndsmg Cos modulespyx to Cos module building cos module extension creating build Creating bui do tempo lanux x36 764 227 18 5 Cython 325 Python Scientific lecture notes Release 2013 1 CeCe Pe niead fNe striee ait aoing lt 4 O2 DI DEEUG Gq iwiae oS Weerice pr eeotypes fPIC gcc pthread shared build temp linux x86_64 2 7 cos_module o L home esc anaconda lib lpython2 cur de busdd cos_medule c cos module pyx cos_module sox setup py And running it In 1 import cos_module In 2 cos_modulel Type module String Form lt module cos module trom cos module so gt File home esc git working scipy lecture notes a
59. cos x 0 3xnp random rand 20 22 gt D NP POlLly Lan Poly age cp yr 53 0 gt gt gt t np linspace 0 1 200 poc Pler plot yn Gry cd toe uv lt matplot lip lines hbine2D Qbjece dbi wasgtplotirb lrnes bhrpne2zD object sb 2 34 Advanced operations 76 Python Scientific lecture notes Release 2013 1 1 3 1 2 1 1 1 0 0 9 0 8 0 7 0 6 2 30 0 2 0 4 0 6 0 8 1 0 See http docs scipy org doc numpy reference routines polynomials poly1d html for more More polynomials with more bases Numpy also has a more sophisticated polynomial interface which supports e g the Chebyshev basis 3r 2g 1 gt gt gt po mnpopolynomial Polynomral 1 2 391 4 coers in doirforent order gt gt gt p 0 Lo gt gt gt p roots Eu crude 1052333333321 gt gt gt p degree In general polynomials do not always expose order E Example using polynomials in Chebyshev basis for polynomials in range 1 1 gt gt gt x no linspace 1 1 2000 aoe y 1p cos x 7 O ornp random rand 2000 gt gt gt p no spolynomial Chebyshev ftit x y 90 55 gt t np linspace 1 1 2010 2o Plea plo a Sv ee 4 matplot trp lines Line2D ODJ s ass poc Plte Plott EEI fut Iwa l matplotlib lines Line2D cbijece xci ne 3 4 Advanced operations 77 Python Scientific lecture notes Release 2013 1 1 3 1 2 1 1 T 0 5 0 0 0 5 1 0 The Chebyshev polynom
60. del ul EIUS EAT In this tutorial we will focus on Traits 14 2 Example 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 e Name Minimal and maximal capacity of the reservoir hm3 Height and length of the dam m e Catchment area km2 Hydraulic head m 14 1 Introduction 269 Python Scientific lecture notes Release 2013 1 Power of the turbines MW e Minimal and maximal release m3 s e Efficiency of the turbines The reservoir has a known behaviour One part is related to the energy production based on the water released A simple formula for approximating electric power production at a hydroelectric plant is P phrgk where P is Power in watts e pis the density of water 1000 kg m3 e his height in meters e r is flow rate in cubic meters per second g is acceleration due to gravity of 9 8 m s2 e k is a coefficient of efficiency ranging from 0 to 1 Annual electric energy production depends on the available water supply In some installations the water flow rate can vary by a factor of 10 1 over the course of a year The second part of the behaviour is the state of the storage that depends on controlled and uncontrolled parameters storage 41 storage inflows release spillage irrigation 14 3 What are Traits A trait is
61. docs scipy org doc numpy reference ufuncs html casting rules Python Scientific lecture notes Release 2013 1 gt gt gt x np array 1 2 3 4 dtype np float gt gt gt X abibay Ia Dee oe EU gt gt gt y X aSLype Mp ints gt gt gt y arrey i 2 3 4ly dtype inte See v al array l2 3 4 S dtype inte ri e EE TUS array 1 2 3 4 dtype int8 gt gt gt y 250 70 ers Zeta 3295 Boos ooe po y F Mpwarray 256 dtype np 1int 2 dera oU SIDE IU cis d mE o2 Casting on setitem dtype of the array is not changed on item assignment roam gt UN IS gt gt gt y array 2 3 4 5 dbiype srnt9 Re interpretation viewing 8 1 Data block in memory 4 bytes 0x01 W 9x02 1 9x03 1 9x04 4 of uint8 OR 4 of int8 OR 2 of intl6 OR 1 of 1nt32 OR 1 of float32 OR How to switch from one to another Switch the dtype gt gt gt x np array i ZR dew dtype np uint8 gt gt gt sx drvpe lt 12 gt gt gt X array I 513 1027 dtype intlo gt gt O00201 02040 ose E 0x01 0x02 IW 0x03 0x04 Note little endian least significant byte is on the left in memory Create a new view gt gt gt y x view lt i4 gt gt gt y array 6 305935 sdtypesusme 32 0x040 0201 SE Jes 166 Life of ndarray Python Scientific lecture notes Release 2013 1 Note e view makes views does no
62. dxis 1 4 last axis array 207 SE po Xa Sid full population standard dev Ors OS ROS Extrema np array 1 3 min max webs Oman OL minimum argmax of maximum Logical operations gt gt gt Np al rrue True Ealse False gt gt gt np any True True False True Note Can be used for array comparisons a np zeros 100 100 gt gt gt np any a 0 False gt gt gt np all a Teure gt gt gt a gt gt gt b gt gt gt cC gt gt gt a True e and many more best to learn as you go 3 2 Numerical operations on arrays 56 Python Scientific lecture notes Release 2013 1 Example data statistics Data in populations txt describes the populations of hares and lynxes and carrots in northern Canada during 20 years We can first plot the data gt gt gt data np loadtxt data populations txt gt gt gt year hares lynxes carrots dota T trick columns to variables gt gt gt from matplotlib import pyplot as plt poo Olr axess 10 27 d ses oun matplotlib axes Axes object at gt cx Olt olor year nhares Year mixes year II OT matplot Ib ines line2D Object St i e gt gt gt Oli legend Hace lynx arro Joc 1 205 95595 lt matplotlib legend Legend object at gt 80000 70000 60000 Hare 50000 Lynx Carrot 40000 30000 20000 10000 1500 1905 1910 1915 1920 The
63. eos Ss 4 2 7 Moving spines Hint Documentation e Spines e Axis container e Transformations tutorial 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 We ll change that since we want to have them in the middle Since there are four of them top bottom left right we ll discard the top and right by setting their color to none and we ll move the bottom and left ones to coordinate 0 in data space coordinates Python Scientific lecture notes Release 2013 1 ax pl gca y gos stands for get Current axis ax spines rrghbt scset color none ax Spines top seu color none dococdoruSs sel ticks position boreom axe orl nes bDoteom Sser positron data 70 dstovaxus seb ticks pesmi ron left ax Spines etn seer position daca 05 4 2 8 Adding a legend Hint Documentation Legend guide legend command Legend API Let s add a legend in the upper left corner This only requires adding the keyword argument label that will be used in the legend box to the plot commands pl plot X C color blue linewidth 2 5 linestyle label cosine pil LOL Sy 00olorettreg linewidth 2 5 linestyle label sine plobtegend toc upper lert 4 2 9 Annotate some points cosine sine Hi
64. f2py to wrap this fortran code in Python f2py c m fortran module 2_a_fortran_module f90 import numpy as np import fortran_module def some_function input m Call a Fortran routine and preserve input shape W n input NO asabray input fortran_module some_function takes 1 D arrays output fortran module some Fumcuion input rave return output reshape input shape print Some _funceion np array ll 2 217 prine some ctumncttrononpesrrsv pil 2l T27 41 D EI Ba Ae ee pube Du 3 2 Numerical operations on arrays 64 Python Scientific lecture notes Release 2013 1 Case 2 b Block matrices and vectors and tensors Vector space quantum level amp spin P bed tal v ijo V1 Uil We wey In short for block matrices and vectors it can be useful to preserve the block structure In Numpy gt gt gt psi np zeros 2 2 dimensions level spin gt gt gt psu lO E 7 lt psl 41 downarrow Oa 0 Linear operators on such block vectors have similar block structure hi V HJ n e i gt gt gt H np zeros 2 2 2 2 7 dimensions levell Jevelz spini spinz gt gt gt M S ALO Oye ess gt gt gt V H O 1 Doing the matrix product get rid of the block structure do the 4x4 matrix product then put it back v v Hw gt gt gt def mdot operator psi return operator transpose 0 2 1 3 reshape 4 4 dot psi reshape 4 reshape 2
65. gains Running pyflakes on the current edited file You can bind a key to run pyflakes in the current buffer In kate Menu settings gt configure kate n plugins enable external tools n external Tools add pyflakes kdialog Lille ovrlalkes stutename mesdgbosc S pythakes siLilename n TextMate Menu TextMate gt Preferences gt Advanced Shell variables add a shell variable TM PYCHECKER Library Frameworks Python framework Versions Current bin pyflakes Then Ct rl Shift V is binded to a pyflakes report 9 1 Avoiding bugs 194 Python Scientific lecture notes Release 2013 1 e In vim In your vimrc binds F5 to pyf lakes autocmd FileType python let amp mp echo x running pyflakes autocmd Filetype tex mp rst python imap Esc i5 C 0 make M autocmd FileType tex mp rst python map lt Esc gt 15 make M autocmd FileType tex mp rst python set autowrite In emacs In your emacs binds F5 to pyflakes defun pyflakes thisfile interactive compile format pyflakes s buffer file name define minor mode pyflakes mode Toggle pyflakes mode With no argument this command toggles the mode Non null prefix argument turns on the mode Null prefix argument turns off the mode 2n The initial value miL ro The aindicaror Lor ehe mode dne EE deae 7 the minor mode bindrngs Su LES x pyr lakes thiar iler add hook python mode hook lambda
66. gt gt a shape CI gt gt gt len a 2 D 3 D F 2x So array 3 gt gt gt b ndim 2 gt gt gt b shape A o gt gt gt len b returns the size of the first dimension 2 gt gt gt c np array 1 gt gt gt C csse E KOP Hied ATR gt gt gt c shape O ME In practice we rarely enter items one by one e Evenly spaced gt gt gt import numpy as np gt gt gt a np arange 10 7 0O ax nai gt gt gt a arra lOr Lp 254 3 ep Ji gt gt gt b np arange l start end exlusive step gt gt gt b amranani 9 8S sh or by number of points gt gt gt c np linspace 0 start end num points gt gt gt cC atbiay On O22 pou Oey Ji 3 gt gt gt d np linspace 0 endpoint False gt gt gt d mra il Os z Common arrays 3 1 The numpy array object 44 Python Scientific lecture notes Release 2013 1 gt gt gt a np ones 3 3 reminder 3 3 is a tuple gt gt gt a arca Iii du ipee Hl calle ley vile elec set alles Ie Blige TUS gt gt gt b mnp zeros 2 2 gt gt gt b array AMI DNO Oly E Ong O0 pp gt gt gt c np eye 3 gt gt gt C array i ia rer Oly IP dE See O Ate des ales mood mpdiag Parray ik 25 9 AN gt gt gt d array IL y 0 0l I S e ROS Oy Se Whe Ors 2L OL AT 7 e np random random numbers Mersenne Twister PRNG gt gt gt a np random rand 4 a UD R
67. gt gt gt MEX Sparse csc matrix 3 4 dtype enp rnts9 gt gt gt mtx todense t merge q ccs OF NO XO DO xo cda TO LOS D 05 Olly deype ints create using data ij tuple 22 gt crow MP anran 10 0 1 2 2 uw gt gt gt COll mp array O 2 42 Oe ale Sq gt gt gt data np array ly 2 3 uw 3 61 gt gt gt mtx sparse csc_matrix data row col shape 3 3 gt gt gt mtx 3x3 sparse matrix of type type numpy into4 with 6 stored elements in Compressed Sparse Column format gt gt gt mtx todense Meese IlL SOG 2 LO zs 2 e S3 ay Ss 6 gt gt gt mtx data abbay l e 5x 24 37 6 gt gt gt mtx indices cuu O dedu cxcexdts pede SOR INEO Ide e dag 2 o Ol dtype aT 2 7 e create using data indices indptr tuple gt gt gt data np earray l 4 5 2 3 6 poc Indices mp gccavebye eg 0 iy 12 pom congu Mp array 0 2 3 61 gt gt gt mtx Sparse csce Matrix data Indices xndptr shape 3 3 gt gt gt mtx todense Matra Oily 390 2217 Gye CERES s 2 o UNI Block Compressed Row Format BSR basically a CSR with dense sub matrices of fixed shape instead of scalar items block size R C must evenly divide the shape of the matrix M N three NumPy arrays indices indptr data indices is array of column indices for each block data is array of corresponding nonzero values of shape nnz R C subclass of cs matr
68. gt gt lena range 400 range 400 12 3 1 Statistical information gt gt gt lena misc lena gt gt gt lena mean 124 04678344726502 gt gt gt lena max lena min 2457 25 np hrstogram 12 3 Basic manipulations 236 Python Scientific lecture notes Release 2013 1 Exercise 1 Open as an array the scikit image logo http scikit image org _static scikits_image_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 mat 1plot1ib 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 scikits image image processing in python 12 3 2 Geometrical transformations lena misc lena Ix ly lena shape f Cropping erop lenm molde I uei 7 4 jb up lt gt down SX flip ud lena np flipud lena rotation rotate lena ndimage rotate lena 45 rotate lena noreshape ndimage rotate lena 45 reshape False 12 3 Basic manipulations 237 Python Scientific lecture notes Release 2013 1 12 4 Image filtering Local filters replace the value of pixels
69. hood OQ ny AONO OBS aeos POSSE Xt t us End o PE TIDETUR SER SO pion ery Betis Doce SO UR ion mm ONU 9 05 orem Renton gees Sst hore etate OO Dao de dd ao DO 0 26 iQ ose Sous DEG deste eb OOA O00 ES ORIS DRUG D D00040 SEE nrn Y 3 24 2s gt In 1c Noise ier Transform the Fast Four ise using d to clean up the no 1S exercise We alm th 2 Load the e D lt z D e e c O 2 z D Ke N lt i9 Ban z en c c oN ne e c O oN e i D gt oF D Mem oO e X aa l lab imres image using py transform 1er image ing fftpack and plot the spectrum Four ion in scipy transform to see the result 1er Four Inverse frequency part of the spectrum so set some of those components to zero use array slicing 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 high 3 Find and use the 2 D FFT funct Apply the 5 imize opt scipy ion and fi imizat 5 5 Opt solution to a minimization or equality ing a numerica Optimization is the problem of find 1 scalar or mult minimization The scipy optimize module provides useful algorithms for functio
70. image AxesImage object at gt Other libraries gt gt gt from scipy misc import imsave gt gt gt cWsave l tinmy elephanb pug moLbrs 6 2 9 9 gt gt gt plt imshow plt imread tiny elephant png interpolation nearest lt matplotlib image AxesImage object at gt 34 Advancedoperations ag Python Scientific lecture notes Release 2013 1 10 20 30 40 Numpy s own format Numpy has its own binary format not portable but with efficient I O gt gt gt data np ones 3 3 gt gt gt np save pop npy data gt gt gt data3 npeload pop npv Well known amp more obscure file formats HDF5 h5py PyTables e NetCDF scipy io netcdf_file netcdf4 python e Matlab scipy io loadmat scipy io savemat e MatrixMarket scipy io mmread scipy io mmread If somebody uses it there s probably also a Python library for it Exercise Text data files Write a Python script that loads data from populations txt and drop the last column and the first 5 rows Save the smaller dataset to pop2 txt Numpy internals If you are interested in the Numpy internals there is a good discussion in Advanced Numpy page 160 34 Advanced operations 80 CHAPTER 4 Matplotlib plotting authors Nicolas Rougier Mike M ller Ga l Varoquaux Thanks Many thanks to Bill Wing and Christoph Deil for review and corrections 81 Python Scientific lecture notes Re
71. in a simple legible ways 2 Make it work reliably write automated test cases make really sure that your algorithm is right and that if you break it the tests will capture the breakage 204 Python Scientific lecture notes Release 2013 1 3 Optimize the code by profiling simple use cases to find the bottlenecks and speeding up these bottleneck finding a better algorithm or implementation Keep in mind that a trade off should be found between profiling on a realistic example and the simplicity and speed of execution of the code For efficient work it is best to work with profiling runs lasting around 10s 10 2 Profiling Python code No optimization without measuring Measure profiling timing You ll have surprises the fastest code is not always what you think 10 2 1 Timeit In IPython use timeit http docs python org library timeit html to time elementary operations In 1 import numpy as np In 2 a np arange 1000 In 3 stimeit a 2 100000 Xoops best wl 3 5 75 Us per loop In 4 2timeit a xx 2 1 1O00 loops best or 3 154 us per loop TARTS comer sr ive 100000 loops best ort 3 5 560 Us per loop Use this to guide your choice between strategies Note For long running calls using t ime instead of t imeit itis less precise but faster 10 2 2 Profiler Useful when you have a large program to profile for example the following file f For this example to run you also need the ica py
72. in the same directory as the test py file we can execute this 1n a console Popythom keota py Hello how are youR 2 5 Reusing code scripts and modules 26 Python Scientific lecture notes Release 2013 1 Standalone scripts may also take command line arguments Nota eye import sys print sys argv python file py test arguments file py y test aroumenuts Note Don t implement option parsing yourself Use modules such as optparse or argparse 2 5 2 Importing objects from modules In 1 import os in 2 os Our 2 module os from usz Lib python2 6 os pyel P In sls eS sta iin 4 Cue le PSOne ay 4 basic types rst oontcrolsrbowwrst Puta oS Sie a fao Neu language st CDS Sr cep Sb ete Ones 4 rexcepr tomes rSt 7 WOLKE ONTAS Ut Taek ret And also In 4 from os import listdir Importing shorthands In 5 import numpy as np Warning 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 a
73. is the closest to the his togram of the original noise free image 12 4 4 Mathematical morphology See http en wikipedia org wiki Mathematical_morphology Probe an image with a simple shape a structuring element and modify this image according to how the shape locally fits or misses the image Structuring element gt gt gt el ndimage generate_binary_structure 2 1 gt gt gt el array Palse True False True True True False True False dtype bool gt gt gt el astype np int arces o in Olly ll le All Oc cr O11 Erosion minimum filter Replace the value of a pixel by the minimal value covered by the structuring element gt gt gt a np zeros 7 7 dtype np int oso a ls6 2 9 1 12 4 Image filtering 240 gt gt gt a gu rss IIO 07 07 0 07 07 0l PO MD Mi Rr Ses MO ROT Doe Ts Se x Ser S0 MD te ED ie She hes e 10 pes Over ollie et s cedes FOL ROLE Or ig Sube She Ihe Ure ds DOr Or Wes De Or XO 20 iy gt gt gt ndimage binary_erosion a array 0 0 X Uu 0 Ol lies Oe lbs Oe OG 30 5 VO liv Ops Oi su cc Oh Ouen ues Oe UD hos Ore Xs nS ID cec rs SOLE luc VOR SO TE EOF BOG a0 S Oe Oe OE Oe ub AOR OG E05 10e UTI gt gt gt FErOSI ON gt gt gt ndimage binary_erosion a astype a dtype removes objects smaller than the structure Python Scientific lecture notes Release 2013 1 stru
74. like the Nelder Mead or gradient based methods many times with different starting points should often be preferred to heuristic methods such as simulated annealing 13 3 Practical guide to optimization with scipy 13 3 1 Choosing a method 10 10 3 2 107 o uio S E i 107 Ill conditioned Gaussian S Ill Conditioned quadratic AZ Rosenbrock l l IB Well conditioned Gaussian zb jh 2 ib ii e m Well conditioned quadratic So or 4 5 cdiGugate gradient Powell Nelder mead L BFGS BFGS Conjugate gradient BFGS L BFGS Newton wf wf wf w Hessian 13 3 Practical guide to optimization with scipy 262 Python Scientific lecture notes Release 2013 1 Without knowledge of the gradient e In general prefer BFGS scipy optimize fmin_bfgs or L BFGS scipy optimize fmin 1 bfgs b even if you have to approximate nu merically gradients On well conditioned problems Powell scipy optimize fmin powell and Nelder Mead scipy optimize fmin both gradient free methods work well in high dimension but they collapse for ill conditioned problems With knowledge of the gradient e BFGS scipy optimize fmin bfgs OT L BFGS scipy optimize fmin l bfgs b Computational overhead of BFGS is larger than that L BFGS itself larger than that of conjugate gradient On the other side BFGS usually needs less function evaluations than CG Thus conjugate gradient method is better than BFGS at optimizing computationally chea
75. mean populations over time oso populscctonms datal e gt gt gt populations mean axis 0 array I 940000952 99095 200 566566 01 600905x 24005 ie The sample standard deviations gt gt gt populations std axis 0 array 20997 90645209 16231 5915 69T Oro UR URS aa Which species has the highest population each year gt gt np argmax populations dou arron e 2 O O olen ea As AU ee ey ey WO Adr de aar vip xr wp 2 3 2 Numerical operations on arrays 57 EE ee eee Example diffusion simulation using a random walk algorithm AA 1 O 1 d t What is the typical distance from the origin of a random walker after t left or right jumps shuffled jumps Position cumulated jumps sum time time gt gt gt n stories 1000 number of walkers gt gt gt t_max 200 time during which we follow the walker We randomly choose all the steps 1 or 1 of the walk gt gt gt t np arange t_max Steps 2 s no random random integers 0 1 mostories tomax 1 gt gt gt Np unique steps Verification all steps are I or 1 amaray L 1p LI We build the walks by summing steps along the time gt gt gt positions np cumsum steps axis 1 axis 1 dimension of time gt gt gt Sq distance positions x2 We get the mean in the axis of the stories gt gt gt mean sq distance np mean sq_distance axis 0 Plot the results gt gt gt plt figure figsize 4 3
76. meth ods and variables attributes we will be able to use gt gt gt 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 2 9 Object oriented programming OOP 40 Python Scientific lecture notes Release 2013 1 gt gt gt anna Student anna gt gt gt anna set_age 21 gt gt gt anna Ssetma jor physics In the previous example the Student class has _ init__ set age and set major methods Its at tributes 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 won t copy the previous class but inherit from it gt gt gt class MasterStudent Student internship mandatory from March to June gt gt gt games Masterstudent james gt gt gt james internship Mandatory trom March tor Jane gt gt gt james set_age 23 gt gt gt james age Der 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 dif
77. more vp Eqs ease ls gt bs F color put noe oie umor meis Jr Lastly we would like to mention the tab completion feature whose description we cite directly from the IPython manual Tab completion especially for attributes is a convenient way to explore the structure of any object you re dealing with Simply type object name TAB to view the object s attributes Besides Python objects and keywords tab completion also works on file and directory names In 1 x 10 in I2 x TAB x bit length x conjugate x denominator x imag x numerator x real In 3 x real x real bit length x real denominator x real numerator x real conjugate x real imag x real real in A4 x real 1 3 The interactive workflow IPython and a text editor 8 CHAPTER 2 The Python language authors Chris Burns Christophe Combelles Emmanuelle Gouillart Ga l Varoquaux Python for scientific computing 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 http docs python org tutorial Dedicated books are also available such as http diveintopython org python Python is a programming language as are C Fortran BASIC PHP etc Some specific features of Python are as follows
78. morphology is a mathematical theory that stems from set theory It characterizes and transforms geometrical structures Binary black and white images in particular can be transformed using this theory the sets to be transformed are the sets of neighboring non zero valued pixels The theory was also extended to gray valued images Erosion Dilation Opening Closing al Dear Elementary mathematical morphology operations use a structuring element in order to modify other geometrical Structures Let us first generate a structuring element Iss ai ndimage generate_binary_structure 2 1 gt gt gt el array False True False True True True False True False dtype bool gt gt gt el astype np int array oO b 0l CE SS a Oro vip OE e Erosion gt gt gt a np zeros 7 7 dtype np int gt gt gt a 1 6 2 25 9 I gt gt gt a array ITO 0 0 0 05 0 Ul uir AO rs bos ike Mile dE AO rec Bee T Dr clas aie Duns On Oh E Sb S ds Calis PO O a e CROPS OE On O SES e alee rs NO dis o 05 O Oy De 207 Oy gt gt gt ndimage binary_erosion a astype a dtype array LPO De 0 U0 10 07 Oly Oy Oy OS Of O 207 Oly Oa Oh O ee ut Oc OI Oy uu We dbp ty cr O47 Or Du OF du Ue up Oly pra dS AD da UO UNES DUNS O07 0 p du 07 05 3 gt gt gt Erosion removes objects smaller than the structure 5 10 Image processing scipy ndimage 123 Pyt
79. object L Oe GM NT C2017 O02 Ell 0 021 Function base py 645 asarray_chkfinite 54 E AER DOO ORONG 0 000 Tnvumoy core cortblas dot 2 0 005 0 002 0 005 0 002 method any of numpy mdarray objects 6 9089 OUO ME 0 000 0 001 C2000 Beato hos Gor ime 6 0 001 9e 01910 O00 O00 tea py ON 14 O OO 0 000 o 0 000 numpy linalg lapack lite dsyevd je 02002 0000 9577 0 0 000 twodim base py 204 diag i BIS 0 001 0 008 0009 ica Py G9 cca 1 OT ORS 00T qu ux 14 551 execfile WON 0 000 8 0891 DOE 0 000 defmatri xs Py 229 array finalize 7 0 000 0 000 0 004 0 001 ca py 53 sym decorrelation y 0291 0 0 000 O200Z2 02000 Tinalg py e11 eigh 172 OSTIO 020010 02000 0 000 isinstance 1 0 000 DO us 55 14 551 demo py 1 lt module gt 29 0 000 0 000 0 000 0 000 mumeriuce py ts Casa ta 325 0000 02000 0 000 0 000 deftfmatrix py 193 new O2 02000 90810 SD DDIOD de fmatrix py 743 asmetri x Zr OS CHONG 0 000 0 002 0 000 defmatrix py 207 mul 41 0 000 0 000 0 000 0000 mumpy core multiarray zeros ZB 0 000 02000 0 000 0 000 method transpose of numpy ndarray objects i 0000 Qu 0 008 07009 e cp saca 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 10 2 3 Line profiler The profiler is great it tells us whi
80. power delivered by the turbine Mw class Reservoir HasTraits name Str max storage Float le6 desc Maximal storage hm3 max release Float 10 desc Maximal release m3 s head Float 10 desc Hydraulic head m efficiency Range 0 1 turbine Instance Turbine installed capacity PrototypedFrom turbine power if name main turbine Turbine turbine type typel power 5 0 reservoir Reservoir name Project A max_storage 30 max release 100 0 head 60 efficiency 0 8 turbine turbine print installed capacity is initialised with turbine power print reservoir installed_capacity prine CS 215 print updating the turbine power updates the installed capacity turbine power 10 print reservoir installed capacity print I5 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 14 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 Static listeners are defined using the XXX changed magic methods from traits api import HasTraits Instance DelegatesTo Float Range from reservoir import Reservoir class ReservoirState HasTraits Kee
81. pretty unreadable We could simplify this by using yield statements but then the user would have to explicitly call List find answers We can define a decorator which constructs the list for us def vectorized generator func def wrapper xargs x kwargs return list generator_func xargs xxkwargs return functools update_wrapper wrapper generator func Our function then becomes vectorized def find_answers while True ans look for next answer if ans is None break yield ans 7 2 7 A plugin registration system This is a class decorator which doesn t modify the class but just puts it in a global registry It falls into the category of decorators returning the original object class WordProcessor object PLUGINS def process self text for plugin in self PLUGINS text plugin cleanup text return text classmethod det pluginiclse plugin cls PLUGINS append plugin QWordProcessor plugin class CleanMdashesExtension object def cleanup self text return text replace amp mdash 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 unic
82. problem is key For instance an eigenvalue problem with a symmetric matrix is easier to solve than with a general matrix Also most often you can avoid inverting a matrix and use a less costly and more numerically stable operation Know your computational linear algebra When in doubt explore scipy linalg and use timeit to try out different alternatives on your data 10 4 Writing faster numerical code A complete discussion on advanced use of numpy is found in chapter Advanced Numpy page 160 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 Vectorizing for loops Find tricks to avoid for loops using numpy arrays For this masks and indices arrays can be useful Broadcasting Use broadcasting page 59 to do operations on arrays as small as possible before combining them n place operations 10 4 Writing faster numerical code 209 Python Scientific lecture notes Release 2013 1 In 1 a np zeros 1e 7 In 2 timeit global aj a Oxa L0 loops best or 3 Ill sms per Loop In 3 timeit global a a x 0 10 loops best of 3 48 4 ms per loop 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 Be easy on the memory use views and not copies Copying big arrays is as costly as making simple numerical oper
83. quality figures in many formats We are going to explore matplotlib in interactive mode covering most common cases 4 1 Introduction 82 Python Scientific lecture notes Release 2013 1 4 1 1 IPython and the pylab mode 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 When we start it with the command line argument pylab pylab since IPython version 0 12 it allows interactive matplotlib sessions that have Matlab Mathematica like functionality 4 1 2 pylab pylab provides a procedural interface to the matplotlib object oriented plotting library It is modeled closely after Matlab M Therefore the majority of plotting commands in pylab have Matlab analogs with similar arguments Important commands are explained with interactive examples 4 2 Simple plot In this section we want to draw the cosine and sine functions on the same plot Starting from the default settings we ll 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 X np linspace np pi np pi 256 endpoint True Cy specs x mosse X is now a numpy array with 256 values ranging from r to 7 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 pyl
84. random import rand gt gt gt data np round rand 2 3 gt gt gt data arbe ob Loy os dosis cue Ose CLE assign the data using fancy indexing 11 2 Storage Schemes 217 Python Scientific lecture notes Release 2013 1 Soe queo a bab 25 S rz ue gt gt gt mtx 4x5 sparse matrix of type type numpy float64 gt with 5 stored elements in Linked List format gt gt gt gt print mtx 0 E TO Os 22 IRO COTS WO CI IRO i 3 IRO gt gt gt mtx todense Mereiedse ii 0s LET LRF dS Only ORT y O e OnT gs De DN hu Sues EOT Ory Ue Uem rus gt gt gt mtx toarray rO O er lee der only MO Sep Ox eae s l 3055 5 Dec Oty Wiery Wess 0 Oey OF 0 Be em Lu 4 more slicing and indexing ooo me Searce pial me mam Oy e v Oy psy Xie SOUS Mle 205 Ob EUR gt gt gt MEX Lodense nsg cn she Or Su Oy Xe cgi siu 1090s re dE gt gt gt print mtx OG a Or lt 2 NO SES PRR WDhN PE 2y 3 gt gt gt Mex 2 2x4 sparse matrix of type type numpy into4 with 4 stored elements in LInked List format gt gt gt mex lez Alsetodenseq meca Os Ih 2 Ody 25 Oc le AO ile gt gt gt mex ee MTIR odense mac a koe a gt gt gt mtx todense Macrae E d 2 ID 34 o Ws uS Ub Ope WO L Dictionary of Keys Format DOK subclass of Python dict keys are row column index tuples no duplicate entries allowed
85. savefig foo png size 300 300 Change the view mlab view azimuth 45 elevation 54 distance 1 Changing plot properties In general many properties of the various objects on the figure can be changed If these visualization are created via mlab functions the easiest way to change them is to use the keyword arguments of these functions as described in the docstrings 15 1 Mlab the scripting interface 290 Python Scientific lecture notes Release 2013 1 Example docstring mlab mesh Plots a surface using grid spaced data supplied as 2D arrays Function signatures meos S Zr poa X y Zare 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 o
86. scipy org 0 54 0 53 0 52 0 51 e Matplotlib 2 D visualization publication ready plots http matplotlib sourceforge net e Mayavi 3 D visualization http code enthought com projects mayavi 1 2 Scientific Python building blocks 5 Python Scientific lecture notes Release 2013 1 1 3 The interactive workflow IPython and a text editor Interactive work to test and understand algorithms In this section we describe an interactive workflow with IPython that is handy to explore and understand algorithms 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 Note Reference document for this section IPython user manual http ipython org ipython doc dev index html 1 3 1 Command line interaction start ipython In 1 print Hello world Homo world Getting help by using the operator after an object En P213 print Type loud itum functiqoncor method Base Class tyvpe builtin function or _ method gt Supe Form built in DEO ime Namespace Python p Urltin Docs ring print value sep end n file sys stdout Prints the values to a stream or to Syssstdour by default Optional keyword arguments file a fil
87. self old new pass e def release changed self name old new pass Note Listening to all the changes 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 from reservoir import Reservoir from reservoir state property import ReservoirState def wake up watchman if spillage new value if new value gt 0 print Wake up watchman Spilling hm3 format new value if name m mariot Python Scientific lecture notes Release 2013 1 projectA Reservoir name Project A max_storage 30 max release 100 0 hydraulic head 600 efficiency 0 8 State ReservoirState reservoir projectA storage 10 register the dynamic listener state on_trait_change wake_up_watchman_if_spillage name spillage state release 90 Stare Nimi Vows 0 state print_state print Forcing spillage state inflows 100 state release O0 print Why do we have two executions of the callback 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 def wake up watchman object name new pass def wake up watchman object name old new
88. self storage self release self inflows return min new storage self max storage Set storage self storage value self storage storage value get spillage self new storage self storage self release self inflows overflow new storage self max storage return max overflow 0 Qon trait change storage def print state self print Storage tRelease tInflows tSpillage Str format e CNET join 4s T7 2f for zn raungec4 1 print str format format self storage self release self inflows self spillage print T s 79 if name e main t 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 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 14 3 7 Some more advanced traits The following example demonstrate the usage of the Enum and List traits from traits api import HasTraits Str Float Range Enum List from traitsui api import View Item class IrrigationArea HasTraits name Str surface Float desc Surface ha Crop Enum ALrslra wWwaedct Corton class Reservoir HasTraits name Str max storage Float le6 desc Maximal storage hm3 max release Float 10 desc Maximal release m3 s
89. solution 4 4 9 Multi Plots 4 4 Other Types of Plots examples and exercises 96 Python Scientific lecture notes Release 2013 1 Hint You can use several subplots with different partition Starting from the code below try to reproduce the graphic on the right pucsubplotu zn zc Ol seubp lon 2 2 3 pl jstlbploe 2 lt 2 o Click on figure for solution 4 4 10 Polar Axis Hint You only need to modify the axes line Starting from the code below try to reproduce the graphic on the right ol exes m 07 s xe N 20 theta nmp arange lO 2 c E 2 np pi N radii 10 2 np random tanid N width np pi 4 np random rand N bars pl bar theta radii width width bottom 0 0 for r bar an Zip radii Dars bare see facecolor cm youre NOS bar set_alpha 0 5 Click on figure for solution 4 4 11 3D Plots OL 25 N SOQ SIE A Hint You need to use contourf 4 4 Other Types of Plots examples and exercises 97 Python Scientific lecture notes Release 2013 1 Starting from the code below try to reproduce the graphic on the right from mpl toolkits mplot3d import Axes3D fig pl figure ax Axes3D fig X np arange 4 4 0 25 Y np arange 4 4 0 25 xX Y npowmeshorid x x MD SOrE XeeZ F Y 2 py Sn CR N w Il ax plot surface X Y 2 rstride 1 cstride 1 cmap hot Click on figure for
90. state release 90 state inflows state print state print How do we update the current storage A special trait allows to manage events and trigger function calls using the magic xxxx fired method from traits api import HasTraits Instance DelegatesTo Float Range Event from reservoir import Reservoir class ReservoirState HasTraits Keeps track of the reservoir state given the initial storage For the simplicity of the example the release is considered in hm3 timestep and not in m3 s n m 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 update storage Event desc Updates the storage to the next time step 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 Ye a foin 4 7e2f for in range 4 i print str_format format self storage self release self i
91. syntax to define a function the def keyword is followed by the function s name then e the arguments of the function are given between parentheses followed by a colon the function body and return object for optionally returning values 2 4 3 Parameters Mandatory parameters positional arguments 24 Defining functions et Python Scientific lecture notes Release 2013 1 In 81 def double_it x e return x gt 2 In 82 double it 3 Quis 6 In 83 double it Traceback most recent call last Price estdenm lune lj an lt module gt TypeError double_it takes exactly 1 argument 0 given Optional parameters keyword or named arguments In 84 def double_it x 2 ae return x gt 2 In 85 double_it Omi 25 A In 86 double_it 3 Our So 6 Keyword arguments allow you to specify default values Warning Default values are evaluated when the function is defined not when it is called This can be problematic when 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 In 124 bigx 10 In 125 def double it x bigx ae return x x 2 In 126 bigx 1e9 Now really big In 128 doubte che Out das 20 More involved example implementing python s slicing In 98 def slicer seq start None stop None step None NR he molement D
92. t y 2 p sin r er mlab surti z warp scale auto 10 10 100j 15 1 Mlab the scripting interface Python Scientific lecture notes Release 2013 1 points3 oe plot3ad surf 288 Python Scientific lecture notes Release 2013 1 Arbitrary regular mesh mesh P e Dit thera mpm des spp SE sce T Ey x Np sam pho xunpscosttheta y np sin phi messin theta Z np cos phi mlab mesh x y z mlab mesh x y Z representation wireframe colr PM Note A surface is defined by points connected to form triangles or polygones In mlab surf and mlab mesh the connectivity is implicity given by the layout of the arrays See also mlab triangular mesh Our data is often more than points and values it needs some connectivity information Volumetric data contour3d P P Xy SR A O mor Hoe 564 iy Doro soe Values xxx0 5 s yxy c ZxezeZ2 0 mlab contour3d values 15 1 Mlab the scripting interface 289 Python Scientific lecture notes Release 2013 1 This function works with a regular orthogonal grid the value array is a 3D array that gives the shape of the grid 15 1 2 Figures and decorations Figure management Here is a list of functions useful to control the current figure Get the current figure mlab gcf Clear the current figure mlab clf Set the current figure mlab figure 1 bgcolor 1 I 1 fgcolor 0 5 0 5 0 5 Save figure to image file mlab
93. the indentation depth The Ipython shell automatically increases the indentation depth after a column sign to decrease the indentation depth go four spaces to the left with the Backspace key Press the Enter key twice to leave the logical block In 1 a 10 In 2 1 a print 1 elif a print 2 else print A Tot A lot 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 Iterating with an index gt gt gt for i in range 4 print i te hy 5 3 c But most often it is more readable to iterate over values gt gt gt for word in cool powerful readable print Python 1s 38 S word Pychon ta cool Python is powerful Python is readable 2 3 3 While break continue Typical C style while loop Mandelbrot problem gt gt gt z 14 1j gt gt gt while abs z lt 100 Z z x2 1 gt gt gt Z eda More advanced features break out of enclosing for while loop gt gt gt z 14 1j gt gt gt while abs z lt 100 if z imag break Z zZ 2 1 continue the next iteration of a loop Dos qe Ud Oy Ze o gt gt gt for element in a 2 3 Control Flow 18 IS Ol amp 6 Python Scientific lecture notes Release 2013 1 if element continue print 1 element 2 3 4 Conditio
94. use a decorator class deprecated object WEN Print a deprecation warning once on I2rst use or Lhe runction gt gt gt deprecated doctest SKIP def f EE pass Se ary docbtestt SKIP f is deprecated def call self func self func func self count 0 return self _wrapper def _wrapper self xargs kwargs self count t 1 if self count print self func name is deprecated return self func xargs xxkwargs It can also be implemented as a function def deprecated func VEEP PLUG a deprecation warning ODCO On Tirst uso of ele funct10nD gt gt gt deprecated 7 doc ebli FoIP def f S pass ps E f doctest SKIP f is deprecated count 0 def wrapper xargs x xkwargs count 0 1 1f count 0 1 print func name is deprecated return func xargs xxkwargs return wrapper 7 2 Decorators 155 Python Scientific lecture notes Release 2013 1 7 2 6 A while loop removing decorator Let s say we have function which returns a lists of things and this list created by running a loop If we don t know how many objects will be needed the standard way to do this is something like def find answers answers while True ans look for next answer if ans is None break answers append ans return answers 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
95. was shown that they indeed solve real problems and that their use is as simple as possible Chapters contents terators generator expressions and generators page 145 Iterators page 145 Generator expressions page 146 Generators page 146 Bidirectional communication page 147 Chaining generators page 149 Decorators page 149 Replacing or tweaking the original object page 150 Decorators implemented as classes and as functions page 150 Copying the docstring and other attributes of the original function page 152 Examples in the standard library page 153 Deprecation of functions page 155 A while loop removing decorator page 156 A plugin registration system page 156 More examples and reading page 157 Context managers page 157 Catching exceptions page 158 Using generators to define context managers page 159 144 Python Scientific lecture notes Release 2013 1 7 1 lterators generator expressions and generators 7 1 1 lterators Simplicity Duplication of effort is wasteful and replacing the various home grown approaches with a standard feature usually ends up making things more readable and interoperable as well Guido van Rossum Adding Optional Static Typing to Python An iterator is an object adhering to the iterator protocol basically this means that it has a next method which when called returns the next item in the sequence and
96. we will call either scripts or modules Use your favorite text editor provided it offers syntax highlighting for Python or the editor that comes with the Scientific Python Suite you may be using e g Scite with Python x y 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 Let us now execute the script interactively that is inside the python interpreter This is maybe the most common use of scripts in scientific computing Note in Ipython the syntax to execute a scriptis run script py For example In Pl tun test py Hello how are you In 2 message Out zl Hello how are you The script has been executed Moreover the variables defined in the script such as message are now available inside the interpeter s 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
97. will allow us to see both the data and the labels for label in ax get xticklabels ax get yticklabels label set fontsize 160 label set_bbox dict facecolor white edgecolor None alpha 0 65 4 3 Figures Subplots Axes and Ticks So far we have used implicit figure and axes creation This is handy for fast plots We can have more control over the display using figure subplot and axes explicitly A figure in matplotlib means the whole window in the user interface Within this figure there can be subplots While subplot positions the plots in a regular grid axes allows free placement within the figure Both can be useful depending on your intention We ve already worked with figures and subplots without explicitly calling them When we call plot matplotlib calls gca to get the current 4 3 Figures Subplots Axes and Ticks 89 Python Scientific lecture notes Release 2013 1 axes and gca in turn calls gcf to get the current figure If there is none it calls figure to make one strictly speaking to make a subplot 111 Let s look at the details 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 api figure edgecolor color of edge around the drawing background draw figure frame o
98. 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 Note The autogenerated C code uses the Python C Api 18 4 SWIG 320 Python Scientific lecture notes Release 2013 1 Advantages Can automatically wrap entire libraries given the headers Works nicely with C Disadvantages Autogenerates enormous files Hard to debug if something goes wrong e Steep learning curve 18 4 1 Example Let s 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 l ACL UCE lt m n A double cos_func double arg return cos arg and the header file cos module h double cos func double arg 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 vm Example OL Wrapping COs Tno tion rom Math n Using SWIG u smodu le cos module A the resulting C file should be built as a python extension define SWIG FILE WITH INIT Includes the header in the wrapper code ii hue Cos module m Parse the header file to generate wrappers Slice Mde Cos module As you can see not too much code is needed here F
99. 02305 80e1396 In S12 cos module cos func 0 0 Ome s Sou in I5 cos meodulescos fine s 14059765559 Cie ts Sen Now let s see how robust this 1s In 10 cos module cos func foo Typekrror Traceback most recent call Mast ipython input 10 115bee483665d in lt module gt gt cos _ modulencoceitune roo TypeError a float is required 18 2 2 Numpy Support Analog to the Python C API Numpy which is itself implemented as a C extension comes with the Numpy C API This API can be used to create and manipulate Numpy arrays from C when writing a custom C extension See also ref advanced_numpy _ 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 s Example Gk wrapping the cos funceion From Mabn h Using the Numpy C Ari 27 inciude lt Python h gt include lt numpy arrayobject h gt a ACLS smachshe ju wrapped Cosine TUnCCION A7 18 2 Python C Api 315 Python Scientific lecture notes Release 2013 1 static PyObject cos func np PyObject self PyObject args PyArravyOb eck msgid PyObWJece kout array PyArraylterObject T0 iter PyArrayIterObject xout_iter parse single numpy array argument af lPyArguParseluplel args Ol G rPyArray Vyoe spec
100. 06 Python Scientific lecture notes Release 2013 1 Application to Image Compression Clustering can be seen as a way of choosing a small number of observations from the information For instance this can be used to posterize an image conversion of a continuous gradation of tone to several regions of fewer tones gt gt gt from scipy import misc gt gt gt lena misc lena astype np float32 gt gt gt X lena reshape 1 1 We need an n sample n feature array gt gt gt k means cluster KMeans n clusters 5 gt gt gt k means fit X KMeans gt gt gt values k means cluster centers squeeze gt gt gt labels k means labels gt gt gt lena compressed np choose labels values gt gt gt lena compressed shape lena shape A 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 gt gt gt from sklearn import decomposition gt gt gt pca decomposition PCA n components 2 17 4 Dimension Reduction with Principal Component Analysis 307 Python Scientific lecture notes Release 2013 1 oe pea TI rs data PCA copy True n_components 2 whiten False aoe X ped transtorm iris dara Now we can visualize the transformed iris dat
101. 0Ox33ef750 gt gt gt Remove axes and ticks Pos pIa ZLS om deos ed eos odisse n soe Sn Draw contour lines Dx Ole Ccontove Uu 2IL AMatplor lib contour C on oUr et instance gt Oxssise20 For fine inspection of intensity variations use interpolation nearest 2o pisumshowckEl2 909 220 09 7 270 map lE cm gray gt gt gt Diltsamshow 200 220 2001220 vomap plut comioray cnbeerpobtseron nearest Other packages sometimes use graphical toolkits for visualization GTK Qt 12 2 Displaying images 234 Python Scientific lecture notes Release 2013 1 100 200 300 400 12 2 Displaying images 235 Python Scientific lecture notes Release 2013 1 gt gt gt import skimage io gt gt gt skimage 10 se plugin ork mshow gt gt gt im io imshow 1 3 D visualization Mayavi See 3D plotting with Mayavi page 287 and mayavi voldata label mage plane widgets sosurfaces 12 3 Basic manipulations Images are arrays use the whole numpy machinery gt gt gt lena scipy misc lena gt gt gt lena 0 40 166 gt gt gt s SJdTOTDO gt gt gt JenallO 13 20225 abba Sg 156 1577 aie IRS Scc LL57 157 ao i gt gt gt Vena lloosiZ20 255 po gt gt gt lx ly lena shape gt gt gt K VY npogridios Iz Wea poc mask uu gcc usc I e gt gt gt Masks gt gt gt lena mask 0 gt gt gt Fancy indexing gt
102. 1 Box bounds Box bounds correspond to limiting each of the individual parameters of the optimization Note that some problems that are not originally written as box bounds can be rewritten as such be a change of variables 3 5 e scipy optimize fminbound for 1D optimization e scipy optimize fmin_l_bfgs_b aquasi Newton page 260 method with bound constraints gt gt gt def f x return np sqgrt Oocl0 3 2 4 XxX l 2 2 poc OCDeEIMize min l Oros bh Cr Mesarcray 0 ru opi oxegqitodsi pounds las dose io e emm ME Sq oq ees O0S4I eos mtd 0 wack SSNMORRGOHENCBSNORM OF PROJFE 13 5 2 General constraints Equality and inequality constraints specified as functions f x Oandg x 0 e scipy optimize fmin slsqp Sequential least square programming equality and inequality con straints gt gt gt def f x return ne sgr e O 3 2 4 x 1 2 2 gt gt gt def constraint x return np atleast_1d 1 5 no sum np abs x 13 5 Optimization with constraints 266 Python Scientific lecture notes Release 2013 1 gt gt gt dQpUcTImizecrnmmimssdtseptr moyarray 95 0l steqcons conctraimmt 1 Optimization terminated successfully Exit mode 0 Current function value 2474973735504 Iterations 5 Runctsxon evaluacronst 20 Gradient evaluations 5 array 1 25004696 0 424995304 e scipy optimize fmin_cobyla Constraints optimization by lin
103. 2 aD gt gt gt xol mp array qM 2 42 xs d gt gt gt data np array lly 22 3 4 3 9 gt gt gt mtx sparse bsr_matrix data row col shape 3 3 gt gt gt mtx 3x3 sparse matrix ot type lt type numpy Tnbpo4t with 6 stored elements blocksize 1x1 in Block Sparse Row format gt gt gt gt mtx todense Maree Ill x Z POTO 4 5 6 gt gt gt mtx data array NES 1 11 2 Storage Schemes 224 lees p gt gt gt mtx indices arra N Oea 12 eg oo Me E a5 1 arra DL 27 27 ol e create using data indices gt gt gt indptr np array 2 gt gt gt indices novarray G 2 gt gt gt data np array 1 2 3 gt gt gt mtx sparse bsr_matrix gt gt gt mtx todense Meira Sir OHO 2 pes Lg 15 0 Ar Za Oe Ole OP Oe 3o Sly Los OPES WO WO ee eis 4 4 Sn Sw 6 Gliz Mard mS uou qd gt gt gt data A a y Lie g LL s 25 T4 L3 45 99 cdd DES err 4 4 Lor ds y Sy 6 6 ov 61d for matrix mat vector F sparsetools S em bi Lid 11 2 Storage Schemes 2 dtype int32 LIME WES Sy Python Scientific lecture notes Release 2013 1 dtype int32 indptr tuple with 2 2 block size lbs 21 6 repeat 4 reshape 6 2 2 indptr shape 6 6 itera has data array specialized BN ee itera arithmetics via CSR ja oee itera O 1 item access incremental 7 ie consncion on itera ha
104. 303 Support vector machines SVMs for classification page 304 Clustering grouping observations together page 306 K means clustering page 306 Dimension Reduction with Principal Component Analysis page 307 Putting it all together face recognition page 308 Linear model from regression to sparsity page 310 Sparse models page 310 Model selection choosing estimators and their parameters page 311 Grid search and cross validated estimators page 311 301 Python Scientific lecture notes Release 2013 1 17 1 Loading an example dataset First we will load some data to play with The data we will use is a very simple flower database known as the Iris dataset We have 150 observations of the iris flower specifying some measurements sepal length sepal width petal length and petal width together with its subtype Iris setosa Iris versicolor Iris virginica To load the dataset into a Python object gt gt gt from sklearn import datasets gt gt gt iris datasets load_iris This data is stored in the dat a member which isa n samples n features array gt gt gt iris data shape T5055 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 gt gt gt iris target shape 150 gt gt gt import numpy as np gt gt gt Np unique iris target array ily ly 299 17 1 Loading an example data
105. 5 Click on figure for solution 4 4 5 Imshow Hint 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 Ex y Ppeturn lL 7 Oe M IO np linspace 3 3 4 np lvmnspece 34 3p45 3 MM np meshgrid x y pl imshow f X Y Click on the figure for the solution 4 4 6 Pie Charts L D Hint You need to modify Z Starting from the code below try to reproduce the graphic on the right taking care of colors and slices size A pranm uni rorm0 d 20 pl pie Z Click on the figure for the solution 4 4 Other Types of Plots examples and exercises 95 Python Scientific lecture notes Release 2013 1 4 4 7 Quiver Plots ww X h 4 4 A a wu w Ww h 4 d A uo wW D X wo amp wee gp py oy Yue eer YY f FY YY YN Hint You need to draw arrows twice Starting from the code above try to reproduce the graphic on the right taking care of colors and orientations n 8 Ne EC aoe amie nie Osa Oen pl guiver x Yn Click on figure for solution 4 4 8 Grids Starting from the code below try to reproduce the graphic on the right taking care of line styles axes pl gca axes set xlim 0 4 axes set ylim 0 3 axes set xticklabels axes set yticklabels l Click on figure for
106. 7 3 Clustering grouping observations together Given the iris dataset if we knew that there were 3 types of iris but did not have access to their labels we could try unsupervised learning we could cluster the observations into several groups by some criterion 17 3 1 K means clustering The simplest clustering algorithm is k means This divides a set into k clusters assigning each observation to a cluster so as to minimize the distance of that observation in n dimensional space to the cluster s mean the means are then recomputed This operation is run iteratively until the clusters converge for a maximum for max iter rounds An alternative implementation of k means is available in SciPy s cluster package The scikit learn implementation differs from that by offering an object API and several additional features including smart initial ization from sklearn import cluster datasets gt gt gt iris datasets load rris gt gt gt k_means cluster KMeans k 3 gt gt gt k_means fit iris data KMeans copy x True init k meanst k 3 gt gt gt print k_means labels_ 10 ale wake ale i Se ee E OOO O E ee EO NONI gt gt gt Prine ric tardet 10 Os O O DOSE SIE a ay ale T a A a e e ee o te der o Virginica ar Versicolour Petal length Petal length Petal length Ground truth K means 3 clusters K means 8 clusters 17 3 Clustering grouping observations together 3
107. CDOUBLE input output types 2 NPY_CDOUBLE elementwise funcs 0 void x mandel single point mandel PyUFunc_FromFuncAndData Teep Rue elementwise funcs input output types l F number of supported input types 2 n mber Of wnpub args LP n umber of oUbpuUt args QE identity element meyer mind Chis mandel function name mandellz lt 6 gt Compiles iterated Zaz C docet ag 0 unused import numpy as np import mandel x Np limspace 77 10 65 LOUD np linspace 124 1 4 1000 x None 1jx vy None N AK II mandel mandel c c import matplotlib pyplot as plt plitsyameshow obs z w 2 lt 1000 extent nh 7 0 6 ad X24 pute gray 8 2 Universal functions 180 Python Scientific lecture notes Release 2013 1 pce uo wA Note Most of the boilerplate could be automated by these Cython modules http wiki cython org MarkLodato CreatingUfuncs Several accepted input types E g supporting both single and double precision versions cdef void mandel single point double complex xz in double complex xc in double complex z2 out nogil cdef void mandel_single_point_singleprec float complex z_in float Complex xC 1n lose Complex z CUL Mogul cdef PyUFuncGenericFunction loop_funcs 2 edef char input output types 3 2 cdef void xelementwise funcs 1 x2 loop iunes 0 PyUFunc_DD_D Input ODE ut t yoes Ol NEY CDOURLE rapt output eva es NEY IDO UE
108. O 2p 2 Op lp 219 coc indptr Npsarray 0 99 gt gt gt mtx Sparse vcsr Matrix data Indices sndptre gt gt gt mtx todense macax i On n ere dese 47 55 6 Compressed Sparse Column Format CSC column oriented three NumPy arrays indices indptr data x x indices is array of row indices data is array of corresponding nonzero values shape 3 3 indptr points to column starts in indices and data length is n_col 1 last item number of values length of both indices and data nonzero values of the i th column are data indptr i indptr i 1 with row indices indices indptr i indptr itl item i Jj can be accessed as data indptr j k where k is position of i in indices andper 7 sandper gt 1 subclass of _cs_matrix common CSR CSC functionality subclass of data matrix sparse matrix classes with data attribute fast matrix vector products and other arithmetics sparsetools constructor accepts dense matrix array sparse matrix shape tuple create empty matrix data ij tuple data indices indptr tuple efficient column slicing column oriented operations slow row slicing expensive changes to the sparsity structure use actual computations most linear solvers support this format 11 2 Storage Schemes 222 Python Scientific lecture notes Release 2013 1 Examples create empty CSC matrix
109. OC 0452 56 7 d cis gt gt gt std 0987033158606090 s Exercise Probability distributions 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 gt gt gt np median a DUIS S2 PU Ode ar 5 6 Statistics and random numbers scipy stats 116 Python Scientific lecture notes Release 2013 1 It is also called the percentile 50 because 50 of the observation are below it gt gt gt stats scoreatpercentile a 50 iO similarly we can calculate the percentile 90 gt gt gt stats scoreatpercentile a 90 eccesso M The percentile is an estimator of the CDF cumulative distribution function 5 6 3 Statistical tests A statistical test is a decision indicator For instance if we have two sets of observations that we assume are gen erated from Gaussian processes we can use a T test to decide whether the two sets of observations are significantly different gt gt gt a np random normal 0 1 size 100 gt gt gt b np random normal 1 1 size 10 gt gt gt st
110. Om cm me ad gt gt gt a array PLC ONE penu Doe LO 7393 gt gt gt b np random randn 4 Gaussian gt gt gt b cua Wes 544600 du SE 1 796642115 gt gt gt np random seed 1234 Setting the random seed Exercise Array creation Create the following arrays with correct data types Par on course 3 statements for each Hint Individual array elements can be accessed similarly to a list e g a 1 ora 1 2 Hint Examine the docstring for diag Exercise Tiling for array creation Skim through the documentation for np tile and use this function to construct the array 4 4 eae 2 4 2 r IE r r qi 3 1 The numpy array object 45 Python Scientific lecture notes Release 2013 1 3 1 4 Basic data types 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 2 a Np array 1 2 3 gt gt gt a dtype diyoe umtod eer b np array ley ag wd gt gt gt b dtype dtype floato4 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 You can explicitly specify which data type you want gt gt gt c np array 1 2 3 dbype rloat gt gt gt c dt
111. PRES Eee X SOR ox SRE wx 3s 14 1 Introduction s s s s Roe xb REE esii riS oenn ESE ERE EERE HEHE RS Ia Example ce x Rom e x4 pse S IE Deo x eee IR ede es OO ERK See RES o o9 X 3 143 144 145 149 157 160 161 174 183 186 189 189 193 193 196 196 201 204 204 205 208 209 212 212 214 226 230 232 233 234 236 238 243 246 252 253 255 262 264 266 268 269 269 14 5 Whatare IPS 4 6 cee eee Rh eRe REE RET ESE SERRE EOS EERE 14 4 References uu 3 9x xx oz x9 ewe 3 XX ERR we OR Ow ww ew EES 15 3D plotting with Mayavi 15 1 Wilab th scripting interface 2244455 664486 e564 6448 ORO So X x c4 Wm we 15 2 Interactive VOI se ee hehe RO EUER Bb bGh GH AIR KERR EE Hw 9 4 5 RR P RE nS 16 Sympy Symbolic Mathematics in Python I5 l Pitst Steps WIULSVIMPUY du se sapaw Be SO eS Ee Se ee EE EURR Xx xs 15 2 vAlpebran TuanDEULdHOS uu 2o Eu Xov eg 8044 xe 3 P3gm ESE HAE Wb I0 3 OIG 2 ea ee ee he eee EEE EE 2e E P3 Wo RES EH eRe eee ee 16 4 Equation solving 6 lt 2 en bee de One REE KEE SESS EHS EO RSE EEK EEG i Linear COE e sas ee ee 3S 93 8 See BSI Eee 208 SU BOR POR P5 o9 17 scikit learn machine learning in Python 17 1 Loading anexample dataset 22 464 4 84 8b ho eERE REE EAGER YEE ok EO X Hs 72 Classification ee ee hae eee eee ee hee eho hee ee he eee eee ee ee 17 3 Clustering grouping observations together oaoa ee ee 17 4 Dimension Reduction with Principal Component Analy
112. Python Scientific lecture notes Release 2013 1 EuroScipy tutorial team Editors Valentin Haenel Emmanuelle Gouillart Ga l Varoquaux http scipy lectures github com February 10 2013 2013 1 2 9a33667 Getting started with Python for science Scientific computing with tools and workflow Scientific Python building blocks The interactive workflow Python and a text editor The Python language Defining functions Reusing code scripts and modules Input and Output Standard Library Exception handling in Python Object oriented programming OOP NumPy creating and manipulating numerical data The numpy array object Numerical operations on arrays More elaborate arrays Advanced operations Matplotlib plotting Figures Subplots Axes and Ticks Other Types of Plots examples and exercises Beyond this tutorial Quick references Scipy high level scientific computing File input output scipy io Special functions scipy special Linear algebra operations scipy linalg Fast Fourier transforms scipy fftpack Optimization and fit scipy optimize Statistics and random numbers scipy stats Contents II 10 11 12 13 14 Ta 5 8 5 9 5 10 5 11 Interpolation scipy interpolate aasa aaa deeb whom Fh EGRE 4o ok 3 Numerical integration scipy integrate aaaea e e e eevee ROW Xo 9X s Signal processing scipy Signal s s Pek Ceased aSERERE HESS BARES x BEES Image processus sScipy ndinage remser drda we
113. Release 2013 1 wee Ot Exaile Or Wrapping COS unc rom rom Markit using UU VEOSS import ctypes from ctypes util import find_library find and load the library inbm Ceyoes cd lil Loadiiorary find library m y set the argument type libm cos argtypes ctypes c double set the return type libm cos restype ctypes c double def cos runc arg Dd Wrapper FOr os rom msc F 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 We may now use this as before In 1 import cos module In 2 cos module Type module Sering Form module COs module from cos mocule py File home esc git working scipy lecture notes advanced interfacing with c ctypes cos modu Docstring modecstiuvnmg in 3 diri cos module Out ls s DAS eb nC ERR d Goce gt Fw Se name package n COS unic 7 ctypes pond library lt Liom In 4 cos_module cos_func 1 0 Cue la 0754032072305 e65 1393 in 5 cos module cos Fune 00 Orie e oes ooo In lale cos _module cos Tne 14159265359 Outro h20 As with the previous example this code is somewhat robust altho
114. S sremove Junk yexk PS BEES EET False 2n Oc ebedi os eur adika os path path manipulations os path provides common operations on pathnames In 70 In 71 In 72 In 73 CE pq In 74 Out ug 4 s In 78 Ct peus In 79 Out S In 80 Out D 1 In 84 Out 4 In 86 Oo reel In 87 cuc per 3 In 88 Our aes In 92 Duc Lp open gumnks bxt w fp close a s path abspath Junk txt a JUsers cours stc scipy20007 scioy 7009 tutorial source junk exc OS pach ecole a Users churiis src scipy2009 scipy 2009 tutorial source sunk txt OS path dirname a Usere courns src scipy20007 scioy 2 000 tutorial source os path basename a A PLU Shame mid os path splitext os path basename a Onk a E uo Cr es Poem est sie o um ECE True CS e a VS rile qure True CS Dee His eee oes esp tiae qo False OS pathvexpanduser 7 7local JUsers courme local OS Paths qgosru csset expanduser 5 os ban Users7 couric loced bana Running an external command In 8 basic types rst contro lM ION ESE demo2 py os system qe demo py FUNCIONS NIS C amp exceptions rst python language rst Pyehon logo png reusing_code rst Oe Sie Oop rst LirSt_Svueps rse Note Alternative toos system 2 7 Standard Library 35 Ens Ery rst Pyth
115. StrETOOG Ltrqcks ds sStrided smalt arrbray shape 2e6 2e6 strides 32 32 return big_array 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 Note For a list of Python specific commands defined in the gdbinit read the source of this file 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 9 4 Debugging segmentation faults using gdb 203 CHAPTER 10 Optimizing code Donald Knuth Premature optimization is the root of all evil author Ga l Varoquaux This chapter deals with strategies to make Python code go faster Prerequisites line_profiler e gprof2dot dot utility from Graphviz Chapters contents e Optimization workflow page 204 Profiling Python code page 205 Timeit page 205 Profiler page 205 Line profiler page 206 Running cProfile page 207 Using gprof2dot page 207 Making code go faster page 208 Algorithmic optimization page 208 Example of the SVD page 208 Writing faster numerical code page 209 Additional Links page 211 10 1 Optimization workflow 1 Make it work write the code
116. There is no Partial Differential Equations PDE solver in Scipy Some Python packages for solving PDE s are available such as fipy or SfePy 5 9 Signal processing scipy signal gt gt gt from scipy import signal e scipy signal detrend remove linear trend from signal t np lrmspacet t0 5 100 x t np random normal size 100 pl plot t x linewidth 3 pl plot t signal detrend x linewidth 3 5 9 Signal processing scipy signal 120 a ECS DOS e scipy signal resample resample a signal to n points using FFT t np linspace 0 5 100 x np sin t pl plot t x linewidth 3 leplet ule Signal resample v 90 v eo 1 5 1 0 0 5 0 0 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 e scipy signal has many window functions scipy signal hamming t0 scTpy signal bartlett solipy srgnal blackman t e scipy signal has filtering median filter scipy signal medfilt Wiener scipy signal wiener but we will discuss this in the image section 5 10 Image processing scipy ndimage The submodule dedicated to image processing in scipy is scipy ndimage 5 10 Image processing scipy ndimage 121 Python Scientific lecture notes Release 2013 1 Image processing routines may be sorted according to the category of processing they perform 5 10 1 Geometrical transformations on images Changing or
117. Traceback most recent call last ValueError expected square matrix The scipy linalg inv function computes the inverse of a square matrix gt gt gt arr e np diray lil 215 eR Le Sd ere Tarr qnas Jy Arr gt gt gt larr array EE JERS Tu S E O gt gt gt nMp allolose np dot arr larr momeye 2 True Finally computing the inverse of a singular matrix its determinant is zero will raise LinAlgError so arr np array lls 215 jos ion Tu gt gt gt donee inv ert Traceback most recent call last LonAcgEFESoOr Singular matrix More advanced operations are available for example singular value decomposition SVD poc arr Np arange 9 reshape 3 3 mpediag Ll 0 110 gt gt gt uari spec vharr linal svd arr The resulting array spectrum is gt gt gt spec array 14 88982544 0 45294236 O52 2654967 The original matrix can be re composed by matrix multiplication of the outputs of svd with np dot gt gt gt sarr np diag spec gt gt gt svd_mat uarr dot sarr dot vharr Linear algebra operations scipy linalg 106 ee eee mac Meo Eve h se see wast True 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 5 4 Fast Fourier transforms scipy fftpack The scipy fftpack module allows to compute fast Fourier transforms As
118. Ts XO lida o Or DES ROC 40 STIS 5 10 4 Measurements on images Let us first generate a nice synthetic binary image gt gt gt x y nNp 1indices 1007 100 gt gt gt SiG Mossi Z nP pA 20 ap Sann py 0a Tya gt gt gt mask sig gt 1 Now we look for various information about the objects in the image gt gt gt labels nb ndimage label mask gt gt gt nb 8 gt gt gt areas ndimage sum mask labels xrange 1 labels max 1 gt gt gt areas arcar oo ASe 4245 27836 459 7 190 7 52915 424 gt gt gt maxima ndimage maximum sig labels xrange 1 labels max 1 gt gt gt maxima array uo50299299 qe o OUS Seo 254 Oo 249611618 5 10 Image processing scipy ndimage 125 Python Scientific lecture notes Release 2013 1 Gx bod 3609 129023023807 Lori oad7 Zid 5519540791 gt gt gt ndimage find_objects labels 4 slice 30L 48L None slice 30L 48L None gt gt gt sl ndimage find_objects labels 4 gt gt gt import pylab as pl gt gt gt ploumshowtseo Sali lt matplotlib image AxesImage object at gt sig mask labels See the summary exercise on mage processing application counting bubbles and unmolten grains page 134 for a more advanced example 5 11 Summary exercises on scientific computing The summary exercises use mainly Numpy Scipy and Matplotlib They provide some real life examples of scientific computin
119. UR E TRUE Re eS eX Summary exercises on scientific computing uox wow RR xoxo EUR BAS ERE RE SEAS Getting help and finding documentation Advanced topics Advanced Python Constructs 7T T2 7 3 terators generator expressions and generators 24 6544 99 ooo kon t on o9 RO ee we IISCOLUDES x ass ee eu Boe S X EG SUR PURIS ee S WP XO WP Bee he SES x S CODE maces oa ww 3 944 ES X Ge Oe bow AE Wk wh Soe BEGET ASS Advanced Numpy 8 1 8 2 8 3 8 4 8 5 8 6 LHcOLIgdBd i baGeee bod doe be ed OSs boo ES Dude Ode der o eu BEES Universal UnCHONS sou kee RRR EE DEG eR Oe we Wow 3 33 Xo 3 xov 3 Interoperability features 4a be CBG eee BER EH Ew RoR o o9 X X 43 Array siblings chararray maskedarray matrix sns ETC Contributing to Numpy Scipy om Rey RR ROROROR EOR O3 446628 OHSS X 3G OR OR OR OR 3 Debugging code 9 9 9 3 9 4 Avoiding DUSS aa ck eS ow Xo Oe EES EORR 3b CER y ROO ETE OE wed EEE Debugging workflow c446 4668 he 6268 4a bo o R BOR OW ew O ee 9 OEC Re ES Using the Python dcbus cers son vox eom RR EERE O9 3o 9E ReEGROX 9 4 9 xXx EE Hee 39 Debugging segmentation faults using gdb 2222222 Optimizing code 10 1 10 2 10 3 10 4 Optimization workflow x ouo 62h meet eee o Xo 30x Roh OUR X X RE Ree RE x X REED Pronina Python code uoce ko ox oed ex Xo eSeE e RGRIE RO Re X 9 x ohe EERE Making code g fastef ios ak ok mom hU UR ROBUR RO b AUR EEK SUR bE OR
120. X Hd Fase 2507 Sco OF 24495 229507 T2 op SEDI 295 3 2 Numerical operations on arrays 60 Python Scientific lecture notes Release 2013 1 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 gt gt gt x y np arange 5 np arange 5 gt gt gt distance MP SI a ww yity Neynewaxas s gt gt gt distance ere S A s Des F Se 7 4 iby iy salle E edd d cu sd T Is exu Geist 5Gs ly 525 v eO ac qu Sd oT s Asus ga css p eboneg4705606n BaxC0S55l20 Wla24204060 S5 le 4 r o1231056035 d272195955 535 p o uoD695425 1 Or in color gt gt gt plt pcolor distance lt Mmeaup lou libs collections PolyCollection object GE sas Doo Dit colorbar lt matplotIlib colorbar olorbar instance au 4442 gt gt gt plt axis equal OVO 200 000 16 0 UI UJ NJ I Remark the numpy ogrid function allows to directly create vectors x and y of the previous example with two significant dimensions gt gt gt X y np ogrid 0 5 0 5 gt gt gt k y array OCOT s 2 ly euo ere CD e eec vp p 2a gt gt gt x shape y shape Cay cens ly a gt gt gt distance npo sqre x ww 2 y xe 2 3 2 Numerical operations on arrays 61 Python Scientific lecture notes Release 2013 1 So np ogridis very useful as soon as we have to han
121. _diabetes diabetes target gt gt gt lasso fit X diabetes y diabetes LassoCV alphas array 2 14804 EDS ese 0 0023 amp Q 002L5 copy X True cv None eps 0 001 fit intercept True max iter 1000 n alphas 100 normalize False precompute auto tol 0 0001 verbose False gt gt gt The estimator chose automatically its lambda gt gt gt lasso alpha ORONI oq These estimators are called similarly to their counterparts with CV appended to their name Exercise On the diabetes dataset find the optimal regularization parameter alpha 17 7 Model selection choosing estimators and their parameters 311 CHAPTER 18 Interfacing with C author Valentin Haenel This chapter contains an introduction to the many different routes for making your native code primarliy C C available from Python a process commonly referred to wrapping The goal of this chapter is to give you a flavour of what technologies exist and what their respective merits and shortcomings are so that you can select the appropriate one for your specific needs In any case once you do start wrapping you almost certainly will want to consult the respective documentation for your selected technique Chapters contents Introduction page 312 Python C Api page 313 Ctypes page 317 SWIG page 320 Cython page 324 Summary page 328 Further Reading and References page 328 Exercises page 329 18 1 Introduction This chap
122. _filtdat np h histogram filtdat bins np arange 256 5 11 Summary exercises on scientific computing 135 Python Scientific lecture notes Release 2013 1 140000 120000 100000 80000 60000 40000 20000 o 50 100 150 200 250 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 gt gt gt void filtdat lt 50 gt gt gt sand np logical and filtdat gt 30 filtdat ed gt gt gt glass filtdat gt 114 5 Display an image in which the three phases are colored with three different colors gt gt gt phases VOLO saSt ype Npainmt 2Zeoglass astype Np int 34sSaendsast ype Np and 5 11 Summary exercises on scientific computing 136 Python Scientific lecture notes Release 2013 1 6 Use mathematical morphology to clean the different phases gt gt gt sand_op ndimage binary_opening sand iterations 2 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 sumor np bincount to compute the grain sizes gt gt gt sand labels sand nb ndimage label sand op gt gt gt sand areas np array ndimage sum sand op sand labels np arange sand labels max 41 gt gt gt mask sand
123. a value of 23 14 3 3 Documentation By essence all the traits do provide documentation about the model itself The declarative approach to the creation of classes makes it self descriptive from traits api import HasTraits Str Float 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 class Reservoir HasTraits name Str max storage Float 100 desc Maximal storage hm3 Let s now define the complete reservoir class from traits api import HasTraits Str Float Range class Reservoir HasTraits name Str max storage Float le6 desc Maximal storage hm3 max release Float 10 desc Maximal release m3 s head Float 10 desc Hydraulic head m efficiency Range 0 1 def energy production self release Returns the energy production Wh for the given release m3 s FX power 1000 x 9 81 self head release x self efficiency return power x 3600 1f name maim reservoir Reservoir name Project A max_storage 30 max_release 100 0 head 60 efficiency 0 8 release 80 print Releasing m3 s produces kWh format Python Scientific lecture notes Release 2013 1 release reservoir energy_production release 14 3 4 Visualisation The Traits library is also aware o
124. ab This brings us to the IPython prompt IPython 0 15 An enhanced Interactive Python gt Iie roduceon o JXEPwibbon4s Teal ures smagi niforn ion caecum ESO Oe func ions helig gt Pyrchnon s own helpo system object gt Details about objecta Fob ject also works prints more Welcome to pylab a matplotlib based Python environment FOr more information type heltpipylab or you can download each of the examples and run it using regular python python exercice l py You can get source for each step by clicking on the corresponding figure Python Scientific lecture notes Release 2013 1 4 2 1 Using defaults Hint Documentation plot tutorial plot command 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 pylab as pl import numpy as np X np lunspace npaspui npvpr 256 endooint lrue Cy xS cmNEecost uu pss m x OL OLX Mol plot ae o pl show 4 2 2 Instantiating defaults Hint Documentation Customizing matplotlib In the script below we ve instantiated and commented all the figure settings that influence the appearance of the plot The settings have been explicitly set to their defaul
125. adable and well structured code we code what we think Many libraries for other tasks than scientific computing web server management serial port access etc Free and open source software widely spread with a vibrant community e Drawbacks less pleasant development environment than for example Matlab More geek oriented Not all the algorithms that can be found in more specialized software or toolboxes 1 1 Why Python 4 EE ES eee 1 2 Scientific Python building blocks 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 e Python a generic and modern computing language Python language data types st ring int flow control data collections lists dictionaries pat terns etc Modules of the standard library A large number of specialized modules or applications written in Python web protocols web frame work etc and scientific computing Development tools automatic testing documentation generation Bi Shell Konsole lt 2 gt gz IPython an advanced Python shell http ipython scipy org moin e Numpy provides powerful numerical arrays objects and routines to manipulate them http www numpy org e Scipy high level data processing routines Optimization regression interpolation etc http www
126. agers as special generator functions In fact the generator protocol was designed to support this use case Qcontextlib contextmanager def some generator arguments lt Set up try yield lt value gt finally lt cleanup gt The contextlib contextmanager helper takes a generator and turns it into a context manager The gen erator 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 con text 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 Let s rewrite the closing example as a generator contextlib contextmanager def closing obj try yield obj finally Obj sc lose Let s rewrite the assert_raises example as a generator Qcontextlib contextmanager def assert_raises type Ery yield except type return except Exception as value raise AssertionError wrong exception type else raise AssertionError exception expected Here we use a decorator to turn generator functions into context managers 7 3 Context managers 159 CHAPTER 8 Advanced Numpy
127. agic functions aliases and tab completion Like a UNIX shell IPython supports command history Type up and down to navigate previously typed commands In 1 x 10 In 2 Ub In 2 x 10 Python 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 aut omagi c which is enabled by default allows you to omit the preceding sign Thus you can just type the magic function and it will work Other useful magic functions are e cd to change the current directory in I21 cd tmp 7 cmp e S 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 533 39 ns Per loop e cpaste allows you to paste code especially code from websites which has been prefixed with the stan dard python prompt e g gt gt gt or with an ipython prompt e g in 3 In 5 cpaste Pasting code enter alone on the lime to Stop or use Ctrl D sra ISl qme x 10 1000 00000 Loops Desk of S 8529 ms per Loop In 6 cpaste Pasting code enter alone on the line to stop or use Ctrl D gt gt gt comet x 10 10000000 To00S best ort 5 66 nS per Loop e 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 debugg
128. amdexierror py gt home varoquau dev scipy lecture notes advanced debugging optimizing index error pW1 module gt UM Stall snapper bo raise an IndexErtor Pdb continue Traceback most recent call last huge munsedabastmemaso ps 9t daune rio in main pdb runsoript marinpyfile Rille ucr ib overtone eo Moe on le a a roor E self run statement Eile usr iki python 6 bdo py line CS An run exec cmd in globals locals Paleo Mm otri Wine D am module Pile index error py line 9 1n module index error File index errorzpy line 5 in andex error prine lotl lentor IndexError list index out of range Uncaught exception Entering post mortem debugging Running cont or step will restart the program gt home varoquau dev scipy lecture notes advanced debugging optimizing index error py5 index er gt print ete dense Pdb 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 e Run the script in Python with the debugger using Srun d wiener filtering p In 1 scrum d wiener 1 leering py Blank or comment Blank or comment xxx Blank or comment Breakpoint 1 at home varoquau dev scipy lecture notes advanced debugging optimizing wiener f NOTE Enter o at the uwpdbo prompt to start your script gt srring 1 mo
129. an 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 9 4 Debugging segmentation faults using gdb 201 Python Scientific lecture notes Release 2013 1 a simplified version in gdbinit but feel free to read Debugging WithGdb To debug with gdb the Python script segfault py we can run the script in gdb as follows S odo python gdb run segfault py Starting program Usr bin pyunonm seqtrault py Thread debugging using libthread_db enabled Program received signal SIGSEGV Segmentation fault _strided_byte_copy dst 0x8537478 360 343G outstrides 4 src 0x86c0690 Address 0x86c0690 out ot bounds instrides 32 N 3 elsize 4 au Mumpy core src muilivarray Crors se 3165 3565 PAST MOVE inte s2 i gdb 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 gdb s commands gdb mp 1 0x004af4f5 in copy from same shape dest lt value optimized out src lt value optimized out myfunc 0x496780 lt strided byte copy Swap 0 at Mumpy core sre mulliarray crors c 7 46 748 myf nc dit gt dataptr des
130. anced debugging optimizing wiener filtering py 37 36 l var local var noisy img size size gt 37 for i in rangel 38 res noisy img denoised_img ipdb prine l var SOS 25379 See ues XU d A799 de 9013 363 437 ses 240 262 4355 5579 20 S44 er S92 cod 377 259 5 262 203 samy Aro aos 637 bas 392 20 tae wee bor 1595 66 789 T20 cc 15255 17225 019429 qe prince d var min 0 Oh dear nothing but integers and O variation Here is our bug we are doing integer arithmetic 9 3 Using the Python debugger 199 Python Scientific lecture notes Release 2013 1 Raising exception on numerical errors When we run the wiener_filtering py file the following warnings are raised In 2 run wiener hilt eringapy wiener_filtering py 40 RuntimeWarning divide by zero encountered in divide noise level 1 horse lavar 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 Cum IS Adaya Orie aval en Wound s ete on er omore In 4 Srun wiener_filtering py Floating r ornt Error Traceback most recent call last home esc anaconda lib python2 7 site packages IPython utils py3compat pyc in execfil fname xw 176 else L77 filename fname gt 178 _ builtin_ execfile filename where home esc physique cuso python 2013 scipy lecture notes advanced debugging wiener fillfering py i 55 pi
131. aracters can also be handled in Unicode strings see http docs python org tutorial introduction html unicode strings 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 Pale lt stdine Line Jy m lt module gt TypeError str object does not support item assignment In 55 a teplace l z 1 Guelo ol Therzdlo world ine S61 a reolace i Tuer UUETS6ls heezo vorzol 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 Note Python offers advanced possibilities for manipulating strings looking for patterns or format ting The interested reader is referred to http docs python org library stdtypes html string methods and http docs python org library string html new string formatting String substitution 2 2 Basic types 15 Python Scientific lecture notes Release 2013 1 2 gt TAN anmeveger 347 ta Tae cct anoen sourings ses so Che Uh 7 suring tAm integer he ia s ost 07100000F another string String gt gt gt quom 102 gt gt gt filename processing of dataset d txt i gt gt gt filename processing of datacet 102 Dictionaries A dictionary is basically an efficient table that
132. aset gt gt gt import pylab as pl za PIE ena E er qc ea O a a oily e oaao mat plot libi collections COllectIon ODJECE b aor 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 17 5 Putting it all together face recognition An example showcasing face recognition using Principal Component Analysis for dimension reduction and Sup port Vector Machines for classification 17 5 Putting it all together face recognition 308 Python Scientific lecture notes Release 2013 1 mir Stripped down version of the face recognition example by Olivier Grisel http scikit learn org dev auto examples applications face recognition html original shape of images 50 37 W n 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 Laces cest y_train y_test lfw_people target train lfw_people target test
133. asi python ucc x xvin return seq start stop step In 101 rhyme one fish two fish red fish blues fish Spri In 102 rhyme Ou TIEN one n deiehie a xw CTh re ugs lee aes i In 103 st vcer rhyme Ore Siig eode upaesrete tueuot Cog sht c gegt emt cep et Yrs In 104 slicer rhyme step 2 Out LIOA M one l two red billie In 105 slicer rhyme 1 step 2 Cu S E eae ia ee Sesh Relies ESSE 2 4 Defining functions 00 12 Python Scientific lecture notes Release 2013 1 In 106 slicer rhyme start 1 stop 4 step 2 Cre ares JE Stu rash 1 The order of the keyword arguments does not matter In 107 slicer rhyme step 2 start 1 stop 4 Cu BE qe pe eg el roe but it is good practice to use the same ordering as the function s 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 2 4 4 Passing by value 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
134. ations 0 array cla lt i Note that compared to a conjugate gradient above Newton s method has required less function evaluations but more gradient evaluations as it uses it to approximate the Hessian Let s compute the Hessian and pass it to the algorithm gt gt gt def hessian x Computed with sympy return uper us ds a ee Oe cesse cass HaHa iu 2 gt gt gt optimize fmin ncg f 2 2 fprime fprime fhess hessian Optimization terminated successfully Current function value 0 000000 keerati ons 10 Function evaluatrons 12 Gradient evaluations 10 HeSseilanee vo luiet tome 80 array l TD Note At very high dimension the inversion of the Hessian can be costly and unstable large scale gt 250 Note Newton optimizers should not to be confused with Newton s root finding method based on the same principles scipy optimize newton 13 2 A review of the different optimizers 259 Python Scientific lecture notes Release 2013 1 Quasi Newton methods approximating the Hessian on the fly BFGS BFGS Broyden Fletcher Goldfarb Shanno algorithm refines at each step an approximation of the Hes sian An ill conditionned quadratic function On a exactly quadratic function BFGS is not as fast as Newton s method but still very fast An ill conditionned non quadratic function Here BFGS does better than Newton as its empirical estimate of the curvature is better than that giv
135. ations on them In 1 a np zeros 1le7 in 2 scimere a copy 10 loops best of 3 124 ms per loop In 3 timeit a 1 T0 Leces best or 3 112 ms per loop Beware of cache effects 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 page 173 In 1 c np zeros 1e4 1e4 order C In 2 timeit c sum axis 0 l loops best of 3 3 89 s per loop In 3 timeit c sum axis 1 l loops best of 3 188 ms per loop In 4 c strides Oural 900005 8 This is the reason why Fortran ordering or C ordering may make a big difference on operations In 5 a no random rand 20 2 18 in I6 b nperandom ranad 20 2 9 in I scumedc Ap dotb m 1 loops best of 3 194 ms per loop In 8 c np ascontiguousarray a T In 9 jtumeut npsde b5 s 10 loops best of 3 84 2 ms per loop Note that copying the data to work around this effect may not be worth it In 10 timeit c np ascontiguousarray a T L0 Loops best ot 3 106 ms per loop Using numexpr can be useful to automatically optimize code for such effects Use compiled code 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 cod
136. ats ttest_ind a b S37 5622 nO ec y Os O02 77 S65 so The resulting output is composed of The T statistic value it is a number the sign of which is proportional to the difference between the two random processes and the magnitude is related to the significance of this difference the p value the probability of both processes being identical If it is close to 1 the two process are almost certainly identical The closer it is to zero the more likely it is that the processes have different means 5 7 Interpolation scipy interpolate The scipy interpolate is useful for fitting a function from experimental data and thus evaluating points where no measure exists The module is based on the FITPACK Fortran subroutines from the netlib project By imagining experimental data close to a sine function gt gt gt measured time np linspace 0 1 10 gt gt gt nonse np random random l0 2 1 1le 1 gt gt gt measures np sin 2 np pi measured time noise The scipy interpolate interpid class can build a linear interpolation function gt gt gt from scipy interpolate import interpld gt gt gt linear interp interpld measured time measures Thenthe scipy interpolate linear interp instance needs to be evaluated at the time of interest pue computed time np linspace 0 1 50 gt gt gt linear results linear interp computed time A cubic interpolation can also be selected by providing t
137. author Pauli Virtanen Numpy is at the base of Python s scientific stack of tools Its purpose is simple implementing efficient operations on many items in a block of memory Understanding how it works in detail helps in making efficient use of its flexibility taking useful shortcuts and in building new work based on it This tutorial aims to cover Anatomy of Numpy arrays and its consequences Tips and tricks Universal functions what why and what to do if you want a new one Integration with other tools Numpy offers several ways to wrap any data in an ndarray without unnecessary copies Recently added features and what s in them for me PEP 3118 buffers generalized ufuncs Prerequisites e Numpy gt 1 2 preferably newer Cython gt 0 12 for the Ufunc example PIL used in a couple of examples In this section numpy will be imported as follows gt gt gt import numpy as np 160 Python Scientific lecture notes Release 2013 1 Chapter contents Life of ndarray page 161 It s page 161 Block of memory page 162 Data types page 163 Indexing scheme strides page 168 Findings in dissection page 174 Universal functions page 174 What they are page 174 Exercise building an ufunc from scratch page 176 Solution building an ufunc from scratch page 179 Generalized ufuncs page 182 Interoperability features page 183 Sharing multidime
138. bel im Find region of interest enclosing object gt gt gt slice x slice y ndimage find_objects label_im 4 0 gt gt gt roi im slice_x slice_y 12 6 Measuring objects properties ndimage measurements 247 Python Scientific lecture notes Release 2013 1 gt gt gt pit umshow totr matplotlib image AxesImage object at Other spatial measures ndimage center of mass ndimage maximum position etc Can be used outside the limited scope of segmentation applications Example block mean from scipy import misc l misc lena sx sy l shape xy S poorid Oer sw regions sy 6 X 4 Y 6 note that we use broadcasting block mean ndimage mean l labels regions index np arange l1 regsonsme x y 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 page 170 12 6 Measuring objects properties ndimage measurements 248 Python Scientific lecture notes Release 2013 1 Non regularly spaced blocks radial mean gt gt gt Sx Sy Lashape eee xu ps ogrid 0ssx Js gt gt gt r np hypot X sx 2 Y sy 2 2e rOin 204 ru masc east se pcs gt gt gt radial mean ndimage mean l labels rbin index np arange 1 rbin max 1 Exercise segmentation Load as an array the coins image from skimage skimage data coins or from https github com scikits image scikits ima
139. ble situation is when the problem is isolated in a small number of lines of code outside framework or application code with short modify run fail cycles Make it fail reliably Find a test case that makes the code fail every time Divide and Conquer Once you have a failing test case isolate the failing code e Which module e Which function e Which line of code gt isolate a small reproducible failure a test case Change one thing at a time and re run the failing test case Use the debugger to understand what is going wrong Take notes and be patient It may take a while 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 9 3 Using the Python debugger The python debugger pdb http docs python org library pdb html allows you to inspect your code interactively Specifically it allows you to View the source code Walk up and down the call stack Inspect values of variables Modify values of variables Set breakpoints 9 2 Debugging workflow 196 EE eee print Yes print statements do work as a debugging tool However to inspect runtime it is often more efficient to use the debugger 9 3 1 Invoking the debugger Ways to launch the debugger 1 Postmortem launch debugger after module errors 2 Launch the module with the debugger 3 Call the debugger insi
140. by a function of the values of neighboring pixels Neighbourhood square choose size disk or more complicated structuring element r r 12 4 1 Blurring smoothing Gaussian filter from scipy ndimage gt gt gt from scipy import misc gt gt gt lena misc lena gt gt gt blurred lena ndimage gaussian filter lena sigma 3 gt gt gt very blurred ndimage gaussian filter lena sigma 5 Uniform filter gt gt gt local mean ndimage uniform filter lena size 11 12 4 2 Sharpening Sharpen a blurred image gt gt gt from scipy import misc gt gt gt lena misc lena gt gt gt blurred_l ndimage gaussian_filter lena 3 increase the weight of edges by adding an approximation of the Laplacian gt gt gt filter_blurred_l ndimage gaussian_filter blurred_l 1 gt gt gt alpha 30 gt gt gt sharpened blurred_l alpha blurred 1 filter blurred 1 12 4 Image filtering 238 Python Scientific lecture notes Release 2013 1 Jic FEBRE QAM Man Gs HR Ps 12 4 3 Denoising Noisy lena from scipy import misc 1 misc lena Zoe 210 350 noisy 1 0 4 l std np random random l shape A Gaussian filter smoothes the noise out and the edges as well gt gt gt gauss_denoised ndimage gaussian_filter noisy 2 Most local linear isotropic filters blur the image ndimage uniform_filter A median filter preserves better the edges gt gt
141. cases gt gt gt def simple decorator function print doing decoration return function gt gt gt simple_ decorator det function print inside function doing decoration gt gt gt funmetionm imside Faunce aon 7 2 Decorators 150 Python Scientific lecture notes Release 2013 1 gt gt gt def decorator_with_arguments arg print defining the decorator def decorator function in this inner function arg is available too Princ doing decoration y arg return function return _decorator gt gt gt decorator_with_arguments abc def F umnct ion print inside function defining the decorator Going decoration abc gt gt gt function inside function 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 gt gt gt def replacing decorator with args arg print defining the decorator def decorator function in this inner function arg is available too Prine doing decoracion ard def _wrapper xargs xkKwargs print inside wrapper args kwargs return function xargs xxkwargs return wrapper return decorator gt gt gt replacing_decorator_with_args abc def function args kwargs print inside function y args kwargs T return 14 defining the decora
142. ce figures for reports or publications write presentations 1 1 2 Specifications Rich collection of already existing bricks corresponding to classical numerical methods or basic actions we don t want to re program the plotting of a curve a Fourier transform or a fitting algorithm Don t 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 com pany 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 1 1 3 Existing solutions Which solutions do scientists use to work Python Scientific lecture notes Release 2013 1 Compiled languages C C Fortran etc e Advantages Very fast Very optimized compilers For heavy computations it s difficult to outperform these lan guages Some very optimized scientific l
143. ch called Lasso can set some coefficients to zero Such methods are called sparse method and sparsity can be seen as an application of Occam s razor prefer simpler models to complex ones gt gt gt from sklearn import linear model gt gt gt regr linear model Lasso alpha 3 gt gt gt regr fit diabetes X train diabetes y train assolo o gt gt gt regr coef_ very sparse coefficients array o O p 497 3407 5667 199 17441034 e e 118 89291545 0 f 430 9379595 0 gt gt gt regr score diabetes X test diabetes y test 0 551083545330 being the score very similar to linear regression Least Squares gt gt gt lin linear_model LinearRegression gt gt gt lin fit diabetes X train diabetes y train LinearRegression gt gt gt lin score diabetes X test diabetes y test Dias S207 S507 Za t Different algorithms for a same problem Different algorithms can be used to solve the same mathematical problem For instance the Lasso object in the sklearn solves the lasso regression using a coordinate descent method that is efficient on large datasets However the sklearn also provides the LassoLARS object using the LARS which is very efficient for problems in which the weight vector estimated is very sparse that is problems with very few observations 17 6 Linear model from regression to sparsity 310 Python Scientific lecture notes Release 2013 1 17 7 Model selection
144. ch 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 10 2 Profiling Python code 206 Python Scientific lecture notes Release 2013 1 Qprofile def test data np random random 5000 1060 B S wv linalg svd data poa ME dor Ukae 0 aaea results fastica pca T whiten False Then we run the script using the kernprof py program with switches 1 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 deno py Wrote profile results to demo py lprof Timer unit le 06 s File demo py FUMCE LON test at line 5 More tame 4279958 Line Hits Time Per Hit Time Line Contents 5 profile 6 def test D 1 19015 19015 0 T data np random random 5000 100 8 1 14242163 14242163 0 oe Uy S Vv linalg svd data 9 1 10262 10282 0 Oel poa e De dee A O Gata RO dl 71199 TT99 0 Ori results fastica pca T whiten False The SVD is taking all the time We need to optimise this line 10 2 4 Running cProfile In the Python example above IPython simply calls the built in Python profilers cProfile and profile This can be useful if you wish to process the profiler output with a visualization tool python m cProfile o demo prof demo py Using the o switch will output the profile
145. col shape 4 4 gt gt gt mtx lt 4x4 sparse matrix of type type numpy into4 with 4 stored elements in COOrdinate format gt gt gt mtx todense mat ra pa y P 0 07 O O 0 O E 7 7 C W9 duplicates entries are summed together poo OW Movarray il 0 Jd 5rd ge oO pos Col TNovarray 0 xx 1 5 1 8 20 gt gt gt data Merarray id s e es Sh Sod gt gt gt mtx sparse coo matrix data row col shape 4 4 gt gt gt mtx todense Meise lise d wal HO e OF Oy Ls IL Oe TONS 0 Oe PO cil no slicing P mex 7 3 Traceback most recent call last TvpeRhrror coo matrix object 11 2 Storage Schemes 220 Python Scientific lecture notes Release 2013 1 Compressed Sparse Row Format CSR row oriented three NumPy arrays indices indptr data indices is array of column indices data is array of corresponding nonzero values indptr points to row starts in indices and data x lengthisn row 1 lastitem number of values length of both indices and data x nonzero values of the i th row are data indptr i indptr i 1 with column indices indices indptr i indptr itl item i j can be accessed as data indptr i k where k is position of j in r drces rndptr ril rndptr x tl subclass of cs matrix common CSR CSC functionality subclass of data matrix sparse matrix clas
146. 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 gt gt gt i for i in range 3 sert I0 xs 2N gt gt gt 1 1 x 2 for i in range 3 Ones OM esc ek cio ud If you are stuck at some previous Python version the syntax is only a bit worse gt gt gt set i for i in abc Sos Ru Mer 1S 10 poc Over ly Ord EOF i cmo 3590 teed cee eg ee Tired E Generator expression are fairly simple not much to say here Only one gotcha should be mentioned in old Pythons the index variable i would leak and in versions gt 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 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 doesn t 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
147. cos doubles func double in array int size in double out array int size out Calls the original funcion Providing ond the Size Of the Tirst a7 cos doubles tin array Out ariay Sizo in oo To use the Numpy typemaps we need include the numpy i file e Observe the call to import array which we encountered already in the Numpy C API example e Since the type maps only support the signature ARRAY SIZE we need to wrap the cos doubles as cos doubles func which takes two arrays including sizes as input e As opposed to the simple SWIG example we don t include the cos doubles h header There is nothing there that we wish to expose to Python since we expose the functionality through cos doubles func And as before we can use distutils to wrap this 18 4 SWIG 323 Python Scientific lecture notes Release 2013 1 from distutils core import setup Extension import numpy setup ext modules Extension cos doubles courcese cocos doubles c Teos Joubles Tip include dirs numpy get include 1 As previously we need to use include dirs to specify the location ls Lcos doubles e co doubles nh cos doubles Humpy 3 setup py test cosdoublescpy Imspvehon Serlpcey od eae i leunning lout le ext building _cos_doubles extension swigging cos _doubles i to cos doubles wrap c gwig python o cos doubles wrap c cos doubles i cos doubles 1 24 Warning 490 Fragment NumPy Backward C
148. ction extensive documentation print inside function T return 14 defining the decorator doing decoration abc 529 FUNCE TOM SMC mon wc thom at Ure a gt gt gt print function doc exrCensLlye CocumentTat Lom One important thing is missing from the list of attributes which can be copied to the replacement func tion 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 7 2 4 Examples in the standard library First it should be mentioned that there s a number of useful decorators available in the standard library There are three decorators which really form a part of the language e classmethod causes a method to become a class method which means that it can be invoked without creating an instance of the class When a normal method is invoked the interp
149. cture np ones 5 5 astype a dtype array bpo 2 02 0 0 0 0l lOr AO XO Or Ce Oe Oliy LO 07 07 O 07 OF Ol Or Oy Ie Opr Or S90 Oly Og O O Or O y Oy Qs 107 O OF Oy O 01 FO 07 oO 10 207 SO Erosion Dilation Opening Closing al n a Dilation maximum filter gt gt gt a np zeros 5 5 gt gt gt alz 2 d gt gt gt a rar TEO Cay Or Oz 0 KO diez Oey dus 2 D Dues Oep dns sk O Qe Wire Oer Wap U ex zn Whey Oep 0 gt gt gt ndimage binary dilation a curo ue Or Oey 0 Die Xue Le X U Ok tee they ee O i Oe Ger ese OU W ne 0 0 o 0 LE e astype a dtype ai Also works for grey valued images gt gt gt np random seed 2 gt gt gt x wc os2np random random 2 S ast ype np ine gt gt gt im x y np arange 8 gt gt gt bigger_points ndimage grey_dilation im size 5 5 structure np ones 5 5 12 4 Image filtering 241 Python Scientific lecture notes Release 2013 1 gt gt gt square np zeros 16 16 gt gt gt square 4 4 4 4 1 gt gt gt dist ndimage distance_transform_bf square gt gt gt dilate_dist ndimage grey_dilation dist size 3 3 structure np ones 3 3 Opening erosion dilation POO O 0 gt gt gt Opening removes small objects gt gt gt a n
150. d xr WF Uw iF dA CV F F T MM WM A Wy wF Dm 4 9 e AYVYV 4b 19 e ixete 44 9 e AV4b 9 k 1 XOOe D gt 00 0 AV4b 9 HEx ix 9e D gt 4 00 0 AV4b 9 HEx xx 9e 4b AY 006 0 0AV4b 49 BHEx xx 9oe gt 4 00 0 AV4b 9 HEx ix 9e lt gt Y yr 4 O AVIP 99 BHBxx 9e lt gt Y yr 4 O AVIP 0 XQO a e yr O avdr 9 B x e _ FE Y A a wA 4d i W m L E v h a 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 4 6 Quick references 102 Python Scientific lecture notes Release 2013 1 JIM kw CES urea Jouuns Duuds CONNNNNNNNEEEEMMEMMMSSSSNSZSsZXZS e132ads juusic MEET Moquiecs MM TTT wusud Pia aH HH Et Et Ft Gm a yuid uea20 jy EEEENW TT su EEE cC i 70y Aesb enor dnub Bie 0 MEE ul9js 3sib MUS I ZT iS XE Je2u 3sib jeau 1si6 Aep 31sib yes 3sib wee Fee FF ee Fee FF xiJ auaqno Jaddoo UWJEM 00 M 005 O e nq EET 2 99965 MENNNEENES 7 9 gs a a c19S 103 4 6 Quick references CHAPTER 5 Scipy high level scientific computing authors Adrien Chauve Andre Espaze Emmanuelle Gouillart Ga l Varoquaux Ralf Go
151. d 5 6 7 gt gt gt x np drtray li 2 3 4 dtype npeintlo gt gt gt x2 as strided x strides 0 1 2 shape 3 4 gt gt gt x2 gt gt gt y mp array 5 6 71 dtyoe np ane LG gt gt gt y2 as_strided y strides 1 2 0 shape 3 4 gt gt gt y2 array 5 ol Oly 7 dtype int160 TO 5 201 Eds dd Ap As xclivbe aqm lo gt gt gt Xx np array I1 4 dtype np int190 gt gt gt y np array b 7 dtype np intl6 gt gt gt x np newaxis y np newaxis array ME s LO Lo 208 ou ees lee ds vy T4 21l Well dtype intlo Internally array broadcasting is indeed implemented using O strides 8 1 Life of ndarray 171 Python Scientific lecture notes Release 2013 1 More tricks diagonals See Also stride diagonals py Challenge Pick diagonal entries of the matrix assume C memory order Poe x No Array Vill 2 45 ep xe UM SEV ev ie serie 3 po X diag as serided x shape 3 Ssterides 2 727 Pick the first super diagonal entries 2 6 And the sub diagonals Hint to the last two slicing first moves the point where striding starts from Solution Pick diagonals gt gt gt x diag as strided x shape 3 strides 3 1 x itemsize J gt gt gt x diag array Il 5 9 dtype int2 Slice first to adjust the data pointer gt gt gt as strided x 0 1 shape 2 strides 3 1 xx itemsize arra
152. d statement 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 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 it s 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 Let s define a generator which just prints what is passed in through send and throw gt gt gt import itertools gt gt gt def g print S HEL for i an tertools counc s print yieloing 1 1 try ans yield i except GeneratorExit print ciosiug e raise except Exception as e print ysold raised r e else print yield returned s ans
153. de Macr il ms Compute the cosine of each element in in array storing the result in s OUL arraya 7 void cos doubles double in array double out array int size int i For i1 0 7 Size T4 T 1 Cue arrayli Cos Cm orm ov las And since the library is pure C we can t use distutils to compile it but must use a combination of make and gcc m PHONY clean Ia oos deubles so s Coe doubles lt 6 gcc shared wi soname libcos_doubles so o libcos doubles so cos doublesso pos doubles o cos doubles e qoc oec PIC Cosudoubles 9 COS COuboles o clean r we lubpecos doubles sso cos doubles o cos doubles pyc We can then compile this on Linux into the shared library 1ibcos_doubles so B s cos doubles c cos doubles h cos doubles py makefile test cos doubles py make Gee coc i2 IC COs COuoles e O cos doubles 6 gcc shared Wil soname ll libcos doubles so o libcos doubles so cos doubles o S be cos doubles c cos doubles o libcos_doubles sox test_cos_doubles py cos_doubles h cos_doubles py makefile Now we can proceed to wrap this library via ctypes with direct support for certain kinds of Numpy arrays 18 3 Ctypes 319 Python Scientific lecture notes Release 2013 1 we Example Or wrapping aC NopEgmA Tunction Ener acce pts a C doubla array as Input using the mumpy cEypesiib TEN import numpy as np import numpy ctypeslib as npct from ctypes import c int input type for the co
154. de the module Postmortem Situation You re working in IPython and you get a traceback Here we debug the file index error py When running it an IndexError is raised Type debug and drop into the debugger indexError Traceback most recent call last home varoquau dev scipy lecture notes advanced debugging optimizing index error py in lt module gt 6 7 if name main gt 8 index error E home varoquau dev scipy lecture notes advanced debugging optimizing index error py in index erro 3 def index error 4 st hste qr ooboem cue E prine Ist Phen ks amp 6 eee re S IndexErprrtos t list Index out Of range In 2 debug gt home varoquau dev scipy lecture notes advanced debugging optimizing index error py 5 index err 4 lst list foobar EUIS prine Mec llven ise 6 iodo Nest L weromalil snippet to arse an rIndexError Z 3 def index error 4 Lst c last toober ME NIS print Vet hem tse 6 7 if name main 8 index error 9 ipdb len lst pdo print Ise bend sd l 9 3 Using the Python debugger 197 Python Scientific lecture notes Release 2013 1 a ipdbo gt guit ia lS Post mortem debugging without IPython In some situations you cannot use IPython for instance to debug a script that wants to be called from the command line In this case you can call the script with python m pdb script py gt python m pdb
155. dilating An opening operation removes small structures while a closing operation fills small holes Such operations can therefore be used to clean an image gt gt gt a np zeros 50 50 poo wIL9s hO0 dqseq0 s gt gt gt a t 0252p candom srandard normal aspe 5 10 Image processing scipy ndimage 124 Python Scientific lecture notes Release 2013 1 gt gt gt mask a gt 0 5 gt gt gt opened_mask ndimage binary_opening mask gt gt gt closed_mask ndimage binary_closing opened_mask mask opened_mask closed_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 gt gt gt a np zeros 7 7 dtype np int soc caso 6 3 gt gt gt a 4 4 2 a 2 3 1 gt gt gt a arcray Lp 35 07 0 39 5 07 eT KO 2 soe oe Se co COL Oe as 9e SA 25a oue doris Ese 27 Ee 3 3 OE Oy Se 2 35 e 2 Oly LM a S NA Sig Doe OL Ot VO We 2 Oe SIR gt gt gt ndimage grey_erosion a size 3 3 array 07 0 07 07 0 Qus Oe Ors 40 Oe EL fue da KOy Oe uc SES alte i32 SO irs dU WD Ro Shu Ws ORIS MO Que Se one dee SN dE FOR 40 X0 205 UO
156. dimage binary propagation eroded tmp mask t gt gt gt np abs mask close img mean ORDEI Ono oc gt gt gt np abs mask reconstruct final mean 0 0042572021484375 Exercise Check how a first denoising step median filter total variation modifies the histogram and check that the resulting histogram based segmentation is more accurate Graph based segmentation use spatial information Watershed segmentation gt gt gt from skimage morphology import watershed is local maximum p gt gt gt Generate an initial image with two overlapping circles gt gt gt x y np indices 380 90 gt gt gt Kle yl x2 y2 2904 26 44 52 gt gt gt ql r2 16 20 gt gt gt mask Circle x aljer y Ul ux alae Ce E E IE gt gt gt image np logical_or mask_circlel mask_circle2 gt gt gt Now we want to separate the two objects in image gt gt gt Generate the markers as local maxima of the distance gt gt gt to the background gt gt gt from scipy import ndimage gt gt gt distance ndimage distance_transform_edt image gt gt gt mask_circle2 gt gt gt local maxi is local maximum distanc image mp ones 3 3 gt gt gt markers ndimage label local_maxi 0 gt gt gt labels watershed distance markers mask image Spectral clustering normalized cuts segmentation gt gt gt from sklearn feature_extraction import image gt gt gt from sk
157. dle computations on a grid On the other hand np mgrid directly provides matrices full of indices for cases where we can t or don t want to benefit from broadcasting gt gt gt x y np mgrid 0 4 0 4 gt gt gt x duro ly 07 07 0l i ESS A AS uum Sa ote doe ox Sd gt gt gt y cans Aa lO F coo eere n n N N OOO However in practice this is rarely needed 3 2 4 Array shape manipulation Flattening gt gt gt Ja mnp array Lid 2e 495 db m old gt gt gt a ravel array OP a thy Sy xeu gt gt gt a T amran i 41 ue al Poy 306 13 gt gt gt a T ravel array his de 27 Sy 27 6 Higher dimensions last dimensions ravel out first Reshaping The inverse operation to flattening gt gt gt a shape 2 2 gt gt gt b a ravel gt gt gt b reshape 2 3 anco ss qe dus Se SII Creating an array with a different shape from another array gt gt gt a np arange 36 gt gt gt b a reshape 6 6 gt gt gt b arcar MN 0 IO oy 4 cul ge Ae BE DIESE dos SES A GER dios dene deos ou MN lc 22 ode xo DU uc S ols 304 3b 34 337 4 Oodd Or gt gt gt b a reshape 6 1 unspecified 1 value is inferred 3 2 Numerical operations on arrays 62 Python Scientific lecture notes Release 2013 1 Views and copies ndarray reshape may return a view cf help np reshape not a cop
158. double gt mp PyArray DATA Out array r in_array shape 0 And can be compiled using distutils from distutils core import setup Extension import numpy from Cython Distutils import build_ext setup emdcilass build ext build ext ext modules Extension cos doubles sources I eos doubles pyx cos doubles eci include_dirs numpy get_include As with the previous compiled Numpy examples we need the include dirs option Sie cos doubles c cos doubles h cos doubles pyx setup py test cos doubles py python setup py build ext i running Duild ext cychoning Cos doubles pyx lt to 20s doubles cC building cos doubles extension 18 5 Cython 327 Python Scientific lecture notes Release 2013 1 creating build creating build temp linux x86_64 2 7 gcc pthread fno strict aliasing 9 O2 DNDEBUG 9g lt wrapy O3 Wall Wstrici prototypes fPIC In file included from home esc anaconda lib python2 7 site packages numpy core include numpy nda from home esc anaconda lib python2 7 site packages numpy core include numpy nda from home esc anaconda lib python2 7 site packages numpy core include numpy arri trom cos doublesc 2534 home esc anaconda lib python2 7 site packages numpy core include numpy npy deprecated api h 11 2 nome esc anaconda lib python2 1 site packaces numpy Core inclUde numpy _ UtUne api h 236 warnin Gee Oelivead Most rice aliacing G O2
159. dule Set a break point at line 34 using b 34 ipdb gt n gt home varoquau dev scipy lecture notes advanced debugging_optimizing wiener_filtering py 4 9 e oc 4 import numpy as np gt Import Seip y adas Sp ipdb b 34 Breakpoint 2 at home varoquau dev scipy lecture notes advanced debugging optimizing wiener f 9 3 Using the Python debugger 198 Python Scientific lecture notes Release 2013 1 Continue execution to next breakpoint with c ont inue ipdbo gt c gt home varoquau dev scipy lecture notes advanced debugging optimizing wiener filtering py 34 9S MUT gcc 34 noisy img noisy img 35 denoised_img local_mean noisy_img size size e 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 1 e enable exploring inside function calls 2b s gt home varoquau dev scipy lecture notes advanced debugging optimizing wiener filtering py 35 2 34 noisy img noisy img 35 denoised img local mean noisy img size size 36 l var local_var noisy_img size size qSpsbccm gt home varoquau dev scipy lecture notes advanced debugging optimizing wiener filtering py 3 35 denoised_img local_mean noisy_img size size gt 96 l var local var noisy img size size E or a mm rangel e Step a few lines and explore the local variables 3pm gt home varoquau dev scipy lecture notes adv
160. dvanced interfacing with c cython cos modu Do c tring lt no docstring In 3 dir cos_module Out lS s De pult e doo E 5 olblder os name package test__ COs rune In 4 cos module cos fune 1 0 Cuc lal 0 5403022056513 In I5 coscmoduis coscrtumeto e es epo sc 10 in I6 cos module cos fune 3214159265359 COEPI On And testing a little for robustness we can see that we get good error messages TypeRrror Traceback most recent call last ipython input 7 11bee483665d in module 4osunodutescos unc too home esc git working scipy lecture notes advanced interfacing with c cython cos module so in cos TypeError a float is required Additionally it is worth noting that Cython ships with complete declarations for the C math library which simplifies the code above to become RAT SIm ler example OT wrapping cos Iunctrom Trom mach N using CyChon Tre from libc math cimport cos def cos_func arg return cos arg In this case the cimport statement is used to import the cos function 18 5 2 Numpy Support Cython has support for Numpy via the numpy pyx file which allows you to add the Numpy array type to your Cython code Le like specifying that variable i is of type int you can specify that variable a is of type 18 5 Cython 326 Python Scientific lecture notes Release 2013 1 numpy ndarray with a given dtype Also certain op
161. e In 1 import sys In 2 sys path Ou 2s T Io uot dm c musr Local imeclude entncoughkt straits 1 1407 Jaor iy ey ihion2 4 6 gt Lem eeu Hd bao qoae hon 416 eller a ee usq lib pyenon2 6 7 lib Ek sia Vay ey inom 6 iil ole masr Ae OV Rone 6 Lib dyniloae sp lib pytnen2 6 dist Packages ucr duree Toe s ptio 6 gt aer Lie oam eer bee dat bino arte dee 2 0 d s a5 rovibuom 2 6 dist backadges wx 2sosgti2 uniweosde s usr ltocal l uwbD pytlomn2 0 u04st peckages usr lib python2 6 dilst packages usr lib pymod les python2 6 IPytChon Extensions u home gouillar ipython Modules must be located in the search path therefore you can e write your own modules within directories already defined in the search path e g usr local lib python2 6 dist packages You may use symbolic links on Linux to keep the code somewhere else 2 5 Reusing code scripts and modules 30 Python Scientific lecture notes Release 2013 1 e modify the environment variable P Y THONPATH to include the directories containing the user defined mod ules On Linux Unix add the following line to a file read by the shell at startup e g etc profile profile export PYTHONPATH SPYTHONPATH home emma user defined modules On Windows http support microsoft com kb 310519 explains how to handle environment variables or modify the sys path variable itself within a Python script import sys new path
162. e For compiled code the preferred option is to use Cython it is easy to transform exiting Python code in compiled code 10 4 Writing faster numerical code 210 Python Scientific lecture notes Release 2013 1 and with a good use of the numpy support yields efficient code on numpy arrays for instance by unrolling loops 10 4 1 Additional Links f 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 f you need some interactive visualization why not try RunSnakeRun 10 4 Writing faster numerical code 211 CHAPTER 11 Sparse Matrices in SciPy author Robert Cimrman 11 1 Introduction dense matrix is mathematical object data structure for storing a 2D array of values important features e memory allocated once for all items usually a contiguous chunk think NumPy ndarray fast access to individual items 11 1 1 Why Sparse Matrices e the memory that grows like nx 2 e small example double precision matrix gt gt gt import numpy as np gt gt gt import matplotlib pyplot as plt gt gt gt x np linspace 0 1e6 10 psc plep 5 Due A2 vr leb ESO matploridblsxpnessbosne2D o5jeet at s gt gt gt plhtowlabelq suxze n l
163. e measurements 250 Python Scientific lecture notes Release 2013 1 2 4 6 86 10 12 14 16 18 12 6 Measuring objects properties ndimage measurements 251 CHAPTER 13 Mathematical optimization finding minima of functions authors Ga l Varoquaux Mathematical optimization deals with the problem of finding numerically minimums or maximums or zeros of a function In this context the function is called cost function or objective function or energy Here we are interested in using scipy optimize for black box optimization we do not rely on the mathe matical expression of the function that we are optimizing Note that this expression can often be used for more efficient non black box optimization Prerequisites e Numpy Scipy Python e matplotlib References Mathematical optimization is very mathematical If you want performance it really pays to read the books Convex Optimization by Boyd and Vandenberghe pdf available free online e Numerical Optimization by Nocedal and Wright Detailed reference on gradient descent methods Practical Methods of Optimization by Fletcher good at hand waving explainations 252 EE ee eee Chapters contents e Knowing your problem page 253 Convex versus non convex optimization page 254 Smooth and non smooth problems page 254 Noisy versus exact cost functions page 255 Constraints page 255 A review of the different optimizers page 255
164. e original array is not copied in memory When modifying the view the original array is modified as well gt gt gt a np arange 10 gt gt gt a I12 2 m CLEZAR ty y np arange 10 cuc qe ITA force a copy 12 This behavior can be surprising at first sight but it allows to save both memory and time 3 1 The numpy array object 50 Python Scientific lecture notes Release 2013 1 Warning The transpose is a view As aresult a matrix cannot be made symmetric in place gt gt gt a np ones 100 100 gt gt gt a t a T gt gt gt a arca i 22 215 Dogs Jung DT DP ZW xe se oa dese tm eae nee ks oer ees Soe dv eg ent a celos dace unge ie See eG ee ee Shep uw wy 2 dem eee de ills bh oie oli ES ie ee eID Worked example Prime number sieve 0123456 7 8 910111213 VN Compute prime numbers in 0 99 with a sieve Construct a shape 100 boolean array is_prime filled with True in the beginning gt gt gt is prime np ones 100 dtype bool Cross out 0 and 1 which are not primes gt gt gt 1g primel 2 0 For each integer j starting from 2 cross out its higher multiples gt gt gt N max int np sgrt len is_prime gt gt gt for j in range 2 N_max is prime 2 j j False Skim through help np nonzero and print the prime numbers Follow up Move the above code into a script file named prime_sieve py Run it to check it work
165. e 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 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 weg return self edgex x 2 area setter def area self area self edge area x 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 get ter 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 set ter 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 inter preter executes attribute access assignment or deletion the job is delegated to the methods of the property object To make everything crystal clear let s define a debug exa
166. e like object stream defaults to the current sys stdout sep string inserted between values default a space end string appended after the last value default a newline 1 3 2 Elaboration of the algorithm in an editor Create a file my_file py in a text editor Under EPD Enthought Python Distribution you can use Scite available from the start menu Under Python x y you can use Spyder Under Ubuntu if you don t already have your favorite editor we would advise installing Stani s Python editor In the file add the following lines S Hello world print s Now you can run it in IPython and explore the resulting variables In I run mm Enlbepy Hello world In 2 s ouela Hello world In 3 whos Variable Type Waray Inte S Siew Hello world 1 3 The interactive workflow IPython and a text editor 6 Python Scientific lecture notes Release 2013 1 From a script to functions While it is tempting to work only with scripts that is a file full of instructions following each other do plan to progressively evolve the script to a set of functions A script is not reusable functions are Thinking in terms of functions helps breaking the problem in small blocks 1 3 3 IPython Tips and Tricks The Python user manual contains a wealth of information about using IPython but to get you started we want to give you a quick introduction to three useful features history m
167. e notes Release 2013 1 max release 100 0 head 60 efficiency O0 reservoir configure_traits Reservoir Max storage 30 0 Max release 100 0 Head 60 0 Efficiency 0 0 14 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 class ReservoirState HasTraits Keeps track of the reservoir state given the initial storage mnm 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 monta ce uU SS inflows Float desc inflows hm3 release Range low min release high max release spillage Float desc Spillage hm3 def print_state self print Storage tRelease tInflows tSpillage Ar format VE Jorn 4 7s2rr for cin tanga A print str format format self storage self release self inflows self spillage Print x 79 l if name main projectA Reservoir name Project A max storage 30 max release 100 0 hydraulic head 60 efficiency 0 8 14 3 What are Traits 274 Python Scientific lecture notes Release 2013 1 State ReservoirState reservoir projectA storage 10
168. e used to program these changes click on the red button as you modify those properties and it will generate the corresponding lines of code 15 2 Interactive work 293 CHAPTER 16 Sympy Symbolic Mathematics in Python author Fabian Pedregosa Objectives Evaluate expressions with arbitrary precision Perform algebraic manipulations on symbolic expressions Perform basic calculus tasks limits differentiation and integration with symbolic expressions Solve polynomial and transcendental equations Solve some differential equations What is SymPy SymPy is a Python library for symbolic mathematics It aims become a full featured computer algebra system that can compete directly with commercial alternatives Mathematica Maple while keeping the code as simple as possible in order to be comprehensible 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 sympy org 294 Python Scientific lecture notes Release 2013 1 Chapters contents e First Steps with SymPy page 295 Using SymPy as a calculator page 295 Exercises page 296 Symbols page 296 Algebraic manipulations page 296 Expand page 296 Simplify page 296 Exercises page 297 Calculus page 297 Limits page 297 Differentiation page 297 Series expansion page 298 Exercises pa
169. ear approximation inequality constraints only gt gt gt Op imize fmin ccobvd ts nNp array I0 Oly cOms Gonscrainc Normal rercurcn fromosubroutuene COBY LA NFVALS aye F 2 474874E 00 MAXCV 0 000000E 00 x 1 250096E 00 ze A990 0E 01 arra InZa009622 0249902781 Warning The above problem is known as the Lasso problem in statistics and there exists very efficient solvers for it for 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 non constrained optimization problems using a mathematical trick known as Lagrange multipliers 13 5 Optimization with constraints 267 CHAPTER 14 Traits author Didrik Pinte The Traits project allows you to simply add validation initialization delegation notification and a graphical user interface to Python object attributes In this tutorial we will explore the Traits toolset and learn how to dramatically reduce the amount of boilerplate code you write do rapid GUI application development and understand the ideas which underly other parts of the Enthought Tool Suite Traits and the Enthought Tool Suite are open source projects licensed under a BSD style license Intended Audience Intermediate to advanced Python programmers Requirements e Python 2 6 or 2 7 www python org Either wxPython http www w
170. ease 2013 1 2 Standard Library Note Reference document for this section e The Python Standard Library documentation http docs python org library index html e Python Essential Reference David Beazley Addison Wesley Professional 2 1 os module operating system functionality A portable way of using operating system dependent functionality Directory and file manipulation Current directory In 17 os cercwd Qutli Users7 cburms src scipy2000 7scipy 2000 tutorial source List a directory in 131 os listdrr os curdir Cue Lodi index TSt SWO Oy enon lenguage TST Sw view array py swp SSS we y templates pasic 26 DOS EE a 1 SONE DS oontrol riow rst debugging rst Make a directory In 32 os mkdir qunkdir In 33 J3unkowr iIin os listdir os curdir Out 3 gt True Rename the directory In 36 os remame 7 junkdir f oodir In 37 Junkar zn os lisrdir os curdi 1 Out S712 False in 3812 tooorr an os lwsitdin osscurdi Out lel True In 411 os emdr C EOOdir A In 4212 A OCL xn OS ligro r OS Curea Out 42 False Delete a file In 44 fp open junk txt w 2 7 Standard Library 34 In 45 In 46 Ot ue In 47 In 48 oue ps Python Scientific lecture notes Release 2013 1 fp close de big Grace EM lrue Ino ioe lwstdagm 0o sc eub CO
171. ecture notes Release 2013 1 Warning extent If we specified extents for a plotting object mlab outline and mlab axes don t get them by default mlab_scripting_interface rst interaction rst 15 2 Interactive work The quickest way to create beautiful visualization with Mayavi is probably to interactivly tweak the various set tings 15 2 1 The pipeline dialog Click on the Mayavi button in the scene and you can control properties of objects with dialogs Mayavi pipeline S284 0 o Pipeline Scalar LUT Vector LUT ModuleManager v Mayavi Scene 1 LUT Look Up Table Manager v GridSource v Lut mode EN PolyDataNormals m v Colors and legends m Surface Number of colors 256 m Outline Reverse lut f a Mayavi Scene PemlI mls x e m Axes Edit LUT properties Y GridSource a EY v 4 PolyDataNormals amp c pue SE ey Launch LUT editor Show legend m Surface ral d m Title Number of labels 0 Shadow Use default name 4 Data name Edit bar Title Edit bar Text Edit bar Actor Edit bar Widget e Set the background of the figure in the Mayavi Scene node e Set the colormap in the Colors and legends node Right click on the node to add modules or filters 15 2 2 The script recording button To find out what code can b
172. ed buddy temo Tinu oC 764 2 1 7 cos modulo o buila temp linux e0 64 2 7 cos_modi SRS build cos module c cos module h cos_module i cos module py _cos_module so x cos module wrap We can now load and execute the cos module as we have done in the previous examples In 1 import cos module En I2 cos module Tvpe module Sering Form lt module cos module from eosemocdcudtespy gt File home esc git working scipy lecture notes advanced interfacing with c swig cos module DOCSEELNG lt mo CoOCcSL ring In 3 dir cos_ module Out bee pM n sce B oec b able 45 name package secos module newclass object cSwadgegetsbtr J Swig property PESNIJ repr C Swig setabttr Swig setattr nondynamic LCOS spe in 4 cos imodule cos fune 1 0 Ome lAl 02542030220 Se6e 1398 In 31 cos module cos func 0 0 Ope DS ss eder TO in 6 cos module cos tune 3 14159765352 Cue ole s Again we test for robustness and we see that we get a better error message although strictly speaking in Python there is no double type TypeRrror Traceback most recent call last ipython input 7 11bee483665d in lt module gt gt gt cog mocule cos DC C ESQ TypeError in method cos func argument 1 of type double 18 4 SWIG 322 Python Scientific lecture notes Release 2013 1 18 4 2 Numpy Support Numpy provides support for SWIG with t
173. edUnivariateSpline and LSQUnivariateSpline on which errors checking is going to change In case a 2D spline is wanted the BivariateSpline class family is provided All those classes for 1D and 2D splines use the FITPACK For tran subroutines that s why a lower library access is available through the splrep and splev functions for respectively representing and evaluating a spline Moreover interpolation functions without the use of FITPACK parameters are also provided for simpler use see interpld interp2d barycentric_interpolate and so on For the Sprog maxima wind speeds the UnivariateSpline will be used because a spline of degree 3 seems to correctly fit the data gt gt gt from scipy interpolate import UnivariateSpline gt gt gt quantile func UnivariateSpline cprob sorted max speeds The quantile function is now going to be evaluated from the full range of probabilities nprob np linspace 0 1 1e2 gt gt gt fitted max speeds quantile func nprob 2 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 ac FLEC O pron ie OE So the storm wind speed occurring every 50 years can be guessed by poc Euspe wind guan ile Uno TiL ProD gt gt gt fifty wind ua OON DU S The results are now gathered on a Matplotlib figure Exercise with the Gumbell distribution The interested readers are now
174. ee oo eae 2 10 gt gt gt ax b arra l 207 4 Ong O51 gt gt gt J np arange 5 ar egy ch eb oes arcay ur 2 SF Op Ws 2d Python Scientific lecture notes Release 2013 1 Warning Array multiplication is not matrix multiplication gt gt gt c np ones 3 3 gt gt gt C owe array i 13 Hye du ee We dal das Esse l Note Matrix multiplication gt gt gt c dot c auro S Day Ours xcu un ES Sek See a Comparisons pac a Noxvarvay Gil 2 3 47 soc b Mp earray 4 72 2 wq gt gt gt a b array False True False gt gt gt a gt b NOT matrix multiplication True dtype bool array False False True False dtype bool Logical operations gt gt gt a Nowarray l1 1 95 0 dteype boo gt gt gt b Nowarray 1 0 I 0 dtype bocl eee MP2 logiealwou a array True True True False dtype bool 2 np logical anda D array True False False False dtype bool Shape mismatches gt gt gt a np arange 4 vox a Npwarray b 210 Traceback most recent call last Piles sec line 1 imn lt mocule gt ValueError operands could not be broadcast together with shapes 4 2 Broadcasting We ll return to that ater page 59 Transposition 3 2 Numerical operations on arrays 54 Python Scientific lecture notes Release 2013 1 o wq MD eriui np ones 3 3 9 T see help np triu
175. elease 2013 1 A Few Notes on Preconditioning problem specific often hard to develop if not sure try ILU available in dsolve as spilu 11 3 3 Eigenvalue Problem Solvers The eigen module arpack acollection of Fortran77 subroutines designed to solve large scale eigenvalue problems e lobpcg Locally Optimal Block Preconditioned Conjugate Gradient Method works very well in com bination with PyAMG example by Nathan Bell m 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 Dougndary cong tions wee import scipy from scipy sparse linalg import lobpcg from pyamg import smoothed_aggregation_solver from pyamg gallery import poisson 100 9 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 le 8 largest False plot the eigenvectors import pylab pylab rrgure fiogstze 9 9 for i in range K Py labes UbPIlot 37 3 ait 1b pylab trcle BErgenvector lt d z 1 pylab pcolor V 1i reshape N N pylab axis equal Py habeas off pylab show 11 3 Linear Sys
176. en by the Hessian An ill conditionned very non quadratic function gt gt gt def f x The rosenbrock function zx return 5c 1 9005 95352 x 1 gt gt gt def fprime x return unp arravecc2e5swL lec ssepe sp seo s2 0 xc soho 2 gt gt gt optimize fmin bfgs f 2 2 fprime fprime Optimization terminated successfully Current function value 0 000000 Teerabrvons 96 bPunction evaluations 24 Gradient evaluations 24 arra 1200000017 1 2000000226 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 gt gt gt def f x The rosenbrock function he return 5s cecus gt gt gt def fprime x return up arraday 2 5 L sp0 s Ole Cll cropwe2 4 oc pp o sober 2 pO OODptdqaqdzegumarndlcbrgscbu E xe dporuime sptcme larray I 1 00000005 To UDINE cquo to a a CONVERGENCE Note If you do not specify the gradient to the L BFGS solver you need to add approx_grad 1 13 2 4 Gradient less methods A shooting method the Powell algorithm Almost a gradient approach 13 2 A review of the different optimizers 260 Python Scientific lecture notes Release 2013 1 Error on f x An ill conditionned quadratic function Powell s method isn t too sensitive to loca
177. ent 8 4 Array siblings chararray maskedarray matrix 186 Python Scientific lecture notes Release 2013 1 gt gt gt mx 1 9 gt gt gt mx masked array data 1 9 3 5 mask False False False True False fill value 999999 The mask is also available directly gt gt gt mx mask array False False False True False dtype bool The masked entries can be filled with a given value to get an usual array back gt gt gt x2 mx filled 1 gt gt gt x2 array i L oy Sy le 99 The mask can also be cleared gt gt gt mx mask np ma nomask gt gt gt mx massedcarray daeta 1 9 3 99 5 mask False False False False False fill value 999999 Domain aware functions The masked array package also contains domain aware functions See p Maas log np cerae ail uve oS Sn maskcedharray data 030 0 609314718056 1209861229907 1y mask False False True True False True fill value le 20 Note Streamlined and more seamless support for dealing with missing data in arrays is making its way into Numpy 1 7 Stay tuned 8 4 Array siblings chararray maskedarray matrix 187 Python Scientific lecture notes Release 2013 1 Example Masked statistics Canadian rangers were distracted when counting hares and lynxes in 1903 1910 and 1917 1918 and got the numbers are wrong Carrot farmers stayed alert though Compute the mean populations over time i
178. entation 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 10 3 Making code go faster 208 Python Scientific lecture notes Release 2013 1 In 13 Stsmeve np linalg svd data l loops best or 3 1445 Ss per loop In 4 from scipy import linalg In 5 lt timeit linmalo svda daca L loops best of of 14 2 9 per loop In 6 Stimeit linalg svd data full_matrices False L Loops best OE 33 295 ms per Loco In 7 timeit np linalg svd data full matrices False Ll loops best ot 3 295 ms per loop We can then use this insight to optimize the previous code In 1 import demo In 2 timeit demo demo fastica demo np demo prof pdf demo py demo pyc demo linalg demo prof demo prof png demo py lprof demo test in I2 35 Scumert demo rest ica py 65 RuntimeWarning invalid value encountered in sgrt D u eoe to cto be DI Age tenemus gt UT a We Wo NE Wel Oly cu Ll oops best of 3 1 35 Ss per loop In 3 import demo_opt In 4 timeit demo_opt test l loops best of 3 2 208 ms per loop Real incomplete SVDs e g computing only the first 10 eigenvectors can be computed with arpack available in Scipy sparse linalg eigsh Computational linear algebra For certain algorithms many of the bottlenecks will be linear algebra computations In this case using the right function to solve the right
179. entific computing with Python high level data process ing in particular with the scipy package matplotlib users Q lists sourceforge net for plotting with matplotlib 142 Part Il Advanced topics 143 CHAPTER Advanced Python Constructs author Zbigniew Jedrzejewski Szmek This chapter is about some features of the Python language which can be considered advanced in the sense that not every language has them and also in the sense that they are more useful in more complicated programs or libraries but not in the sense of being particularly specialized or particularly complicated It is important to underline that this chapter is purely about the language itself about features supported through special syntax complemented by functionality of the Python stdlib which could not be implemented through clever external modules The process of developing the Python programming language its syntax is unique because it is very transparent proposed changes are evaluated from various angles and discussed on public mailing lists and the final decision takes into account the balance between the importance of envisioned use cases the burden of carrying more language features consistency with the rest of the syntax and whether the proposed variant is the easiest to read write and understand This process is formalised in Python Enhancement Proposals PEPs As a result features described in this chapter were added after it
180. entific lecture notes Release 2013 1 _storage Float Traits property implementation ffeeeeeeeeeeeeeeeeeeeeeeeee tt erF def _get_storage self new storage self storage self release self inflows return min new storage self max storage Set storage self storage value self storage storage value get spillage self new storage self storage self release self inflows overflow new storage self max storage return max overflow 0 print_state self print Storage tRelease tInflows tSpillage Str formae XE soi 13 feet Eor in range print str_format format self storage self release self inflows self spillage print gt 79 if name a main projectA Reservoir name Project A max_storage 30 max release 5 hydraulic_head 60 efficiency 0 8 ReservoirState reservoir projectA storage 25 release 4 inflows 0 Orine stave YCONELGUre ira Ss Edit properties Name Project A Storage 21 0 Spillage 0 Inflows 0 0 Release 0 0 735 0 4 0 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 Python Scientific lecture notes Release 2013 1 turbine type Str power Float 1 0 desc Maximal
181. ents are considered True If no structuring element is provided an element is generated with a square connectivity equal to one iterations int float optional The dilation is repeated iterations times one by default If iterations is less than 1 the dilation is repeated until the result does not change anymore mask array_like optional If a mask is given only those elements with a True value at the corresponding mask element are modified at each iteration output ndarray optional Array of the same shape as input into which the output is placed By default a new array is created origin int or tuple of ints optional Placement of the filter by default 0 border value int cast to 0 or 1 Value at the border in the output array Returns out ndarray of bools Dilation of the input by the structuring element See Also Find help Previous Next Highlight all Match case Reached end of page continued from top e Scipy s cookbook http www scipy org Cookbook gives recipes on many common problems frequently en countered such as fitting data points solving ODE etc e Matplotlib s website http matplotlib sourceforge net 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 amp matplotlib I home search examples galler
182. eq gt freq 0 The resulting filtered signal can be computed by the scipy fftpack ifft function porcum mess gl a pack lcs see The result can be viewed with gt gt gt import pylab as plt gt gt gt plt figure o plt ploc time vec sid gt gt gt plt plot time vec main sig linewidth 3 gt gt gt plt xlabel Time s gt gt gt plt ylabel Amplitude Amplitude 0 5 10 15 20 Time s numpy fft Numpy also has an implementation of FFT numpy ft However in general the scipy one should be preferred as it uses more efficient underlying implementations 5 4 Fast Fourier transforms scipy fftpack 108 Python Scientific lecture notes Release 2013 1 Worked example Crude periodicity finding 80 70 60 50 40 30 20 Population number 10 10 1500 1905 1910 1915 1920 Year 300 250 200 150 Power 10 100 50 Ul 10 15 20 Period 5 4 Fast Fourier transforms scipy fftpack 109 Python Scientific lecture notes Release 2013 1 Worked example Gaussian image blur Convolution Ties fa K t t fo t 5 4 Fast Fourier transforms scipy fftpack 110 Python Scientific lecture notes Release 2013 1 ing image Exercise Denoise moon land m o 58 0 05 0 0 y DES Uu Op o LJ SEE Je yi ODORON m same ate ey oO RR p ds ERR Egos api SOSOSADI DU Sni da e eie 4A tenth Pu AREE brite
183. er at the point where the exception was thrown In 7 x 10 Pile z pythou input o6 L22f0421D5f290 Line 1 x 10 SINE dE ror Invalid syntax 1 3 The interactive workflow IPython and a text editor 7 Python Scientific lecture notes Release 2013 1 In 8 debug gt home esc anaconda lib python2 7 site packages IPython core compilerop py 87 ast_parse 86 and are passed to the built in compile function gt 87 return compile source filename symbol self flags PyCF ONLY AST 88 pub locals source u x 10 n symbol exec self IPython core compilerop CachingCompiler instance at O0x2ad8ef0 palondme uw csrposhon imput o 12t0d422150955229 9 Note The built in IPython cheat sheet is accessible via the quickref magic function Note A list of all available magic functions is shown when typing magic Furthermore Python ships with various aliases which emulate common UNIX command line tools such as 1s 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 BOE Es Aca Cat S clear clear NEON uy CO a aps Vea le Ww er color qom con less bess dug Als E o ScolLor eL grep cv ld x Dips aE o Color sl J grep dde g qe E eo SSO LOE iy lxv 8s F o sa color sk il gren euk y Mei 7 imei WV meer ne ete ahs more
184. ercises on scientific computing page 126 Warning 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 scipy is composed of task specific sub modules 104 Python Scientific lecture notes Release 2013 1 They all depend on numpy but are mostly independent of each other The standard way of importing Numpy and these Scipy modules is gt gt gt import numpy as np gt gt gt from scipy import stats same for other sub modules 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 there s usually no reason to use import scipy in your code 5 1 File input output scipy io Loading and saving matlab files gt gt gt from scipy import io as spio gt gt gt a np ones 3 3 gt gt gt spio savemat file mat a a savemat expects a dictionary gt gt gt data spuroloadmact rilemac struct es record True gt gt gt data a arcar S IF den dien Wa hod a Pino XS Tes SIS Reading images gt gt gt from scipy import misc gt gt gt misc imread fname png pco gw MOCcoTOLISD also fas m Similar Pune eron gt gt gt import matplo
185. erences ETS repositories http github com enthought 144 References 8 Python Scientific lecture notes Release 2013 1 Traits manual http github enthought com traits traits_user_manual index html e Traits UI manual http github enthought com traitsui traitsui_user_manual index html e Mailing list enthought dev enthought com 144 References 8G CHAPTER 15 3D plotting with Mayavi author Ga l Varoquaux Chapters contents e Mlab the scripting interface page 287 3D plotting functions page 288 Points page 288 Lines page 288 Elevation surface page 288 K Arbitrary regular mesh page 289 Volumetric data page 289 Figures and decorations page 290 Figure management page 290 Changing plot properties page 290 Decorations page 292 Interactive work page 293 The pipeline dialog page 293 The script recording button page 293 15 1 Mlab the scripting interface The mayavi mlab module provides simple plotting functions to apply to numpy arrays Try them using in IPython by starting Python with the switch gui wx 287 15 1 1 3D plotting functions Points X Y Z Value mp random random 4 mbkabe Dome ssaiec y EM Z value Lines mu sp dE Clear the figure nprdanmspace 0 20 200 mlabr plor o dnp Sab agen MOIS e os E Ol eee Elevation surface imd deseas m x4 y Me amorid 10 1021007 r nposqre ox 2
186. es not admit a unique local minimum which can be hard to test unless the function is convex and you do not have prior information to initialize the optimization close to the solution you may need a global optimizer Brute force a grid search scipy optimize brute evaluates the function on a given grid of parameters and returns the parameters corresponding to the minimum value The parameters are specified with ranges given to numpy mgrid By default 20 steps are taken in each direction gt gt gt def f x The rosenbrock function ud return 5o d cu ND 2 ascii je LO a poc Oot imi 7 eMbENDGUE Wiha Zi NE 2 array T 00001416 dass od 5 Simulated annealing Simulated annealing does random jumps around the starting point to explore its vicinity progressively narrowing the jumps around the minimum points it finds Its output depends on the random number generator In scipy it is implemented in scipy optimize anneal gt gt gt def f x Ihe rosenbrock function return or 4 009925 ae sell sese DO oo po Opbrmuze anunesltr T221 Warning Cooled to 505776950 mb 20 2727742 93464712523 Dut this is not the smallest point found pauses i a fO4lZ Ibo eod boom 5 It is a very popular algorithm but it is not very reliable Note For function of continuous parameters as studied here a strategy based on grid search for rough exploration and running optimizers
187. etests with the s flag 9 3 Using the Python debugger 200 Python Scientific lecture notes Release 2013 1 Graphical debuggers and alternatives For stepping through code and inspecting variables you might find it more convenient to use a graph ical debugger such as winpdb e Alternatively pudb is a good semi graphical debugger with a text user interface in the console Also the pydber project is probably worth looking at 9 3 2 Debugger commands and interaction a Printthe Tocal variables O O O Execute the given Python command by opposition to pdb commands Warning Debugger commands are not Python code 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 then your local variable when typing code in the debugger Getting help when in the debugger Type h or help to access the interactive help ipdb gt help Documented commands type help lt topic gt EOF oie Cone enable jump pdef ip tbreak W a C continue exit 3 pdoc restart u whatis alias Peal d ie list pinfo return unalias where args clear debug help n pp TUN ume b commands disable ignore next q S E break condition down j p edule step up Miscellaneous help topics reveal ry 9 4 Debugging segmentation faults using gdb If you have a segmentation fault you cannot debug it with pdb as it crashes the Python interpreter before it c
188. extraction in topograph ical lidar data page 129 for another more advanced example 5 6 Statistics and random numbers scipy stats The module scipy stats contains statistical tools and probabilistic descriptions of random processes Random number generators for various random process can be found in numpy random 5 6 1 Histogram and probability density function Given observations of a random process their histogram is an estimator of the random process s PDF probability density function 5 6 Statistics and random numbers scipy stats 115 Python Scientific lecture notes Release 2013 1 gt gt gt a np random normal size 1000 gt gt gt bins np arange 4 5 gt gt gt bins array l 4r 2 i 0 lf 2 SF 41 gt gt gt histogram np histogram a bins bins normed True 0 gt gt gt bins 0 5 oins ble bine 2 1 gt gt gt bins arrar Neto son cR iM so ween ae gt gt gt from scipy import stats 23 gt p Stats norm pdr bins T NORM sg ug ccc lon In Il pli plot bidms histogram In 2 pl plot bsms D 0 40 0 35 0 30 0 25 0 20 0 15 0 10 6 2 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 gt gt gt loc std stats norm fit a 2
189. f user interfaces and can pop up a default view for the Reservoir class reservoirl Reservoir reservoirl edit traits P a AU F um Edit properties Efficiency 0 07 4 1 0 0 8 Head 10 Hydraulic head 60 Max release 100 0 Max storage 30 0 Name Project A OK Cancel 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 le6 desc Maximal storage hm3 max release Float 10 desc Maximal release m3 s head Float 10 desc Hydraulic head m efficiency Range 0 1 traits view View name max storage max release head efficiency title Reservoir resizable True energy_production self release Returns the energy production Wh for the given release m3 s Ton power 1000 x 9 81 x self head release x self efficiency return power x 3600 Tf name a5 mnaan s reservoir Reservoir name Project A max storage 30 Python Scientific lectur
190. ferent 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 CHAPTER 3 NumPy creating and manipulating numerical data authors Emmanuelle Gouillart Didrik Pinte Ga l Varoquaux and Pauli Virtanen This chapter gives an overview of Numpy the core tool for performant numerical computing with Python 3 1 The numpy array object Section contents What are Numpy and numpy arrays page 42 Reference documentation page 43 Creating arrays page 44 Basic data types page 46 Basic visualization page 46 Indexing and slicing page 49 Copies and views page 50 Adding Axes page 51 Fancy indexing page 52 3 1 1 What are Numpy and numpy arrays Python has built in containers lists costless insertion and append dictionaries fast lookup high level number objects integers floating point Numpy is extension package to Python for multi dimensional arrays closer to hardware efficiency designed for scientific computation convenience 42 Python Scientific lecture notes Release 2013 1 gt gt gt import numpy as np gt gt gt a MoOrerray 0 1 2 3 gt gt gt a arcay ro b 27 31 For example An array containing values of an experimen
191. file import numpy as np from scipy import linalg from ica import fastica def test data np random random 5000 100 Uy S V linalg svd data pea Nosdek Ae e Ona data results fastica pca T whiten False if name main test 10 2 Profiling Python code 205 Python Scientific lecture notes Release 2013 1 Note This is a combination of two unsupervised learning techniques principal component analysis PCA and independent component analysis ICA lt http en wikipedia org wiki Independent_component_ana lysis gt _ 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 I1 eun St demo py EPython CPU timings estimated User 14090 9 ke System 0250016 6 and profile it In 2 mun p demo py 9lo function Calls an 14 901 CPU Seconds Ordered by internal time ncalls tottime percall cumtime percall filename lineno function 1 14 457 14 457 14 479 14 479 decomp py 849 svd 1 0 054 0 054 0 054 0 054 method random sample of mtrand RandomS tate
192. fill value 999999 aoc y pera ser iy 27 8 2 ee ly gt gt gt X y masked_array data 2 mask False True True True fill value 999999 3 3 More elaborate arrays 75 Python Scientific lecture notes Release 2013 1 Masking versions of common functions po MPman s ome ea rea Masked array data l120 gt 1 41421356237 mask False True False True fill value 1e 20 Note There are other useful array siblings page 186 While it is off topic in a chapter on numpy let s take a moment to recall good coding practice which really do pay off in the long run Good practices Explicit variable names no need of a comment to explain what is in the variable e Style spaces after commas around etc A certain number of rules for writing beautiful code and more importantly using the same conven tions 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 3 4 Advanced operations Section contents Polynomials page 76 Loading data files page 78 3 4 1 Polynomials Numpy also contains polynomials in different bases For example 3z 2z 1 po p mpopolye E35 25 S gt gt gt p 0 2 D lt KOOLS array I tet re 0 BS SS S gt gt gt p order 2 gt gt gt x np linspace 0 1 20 gt gt gt y np
193. function python passes the reference to the object to which the variable refers the value Not the variable itself If the value is immutable the function does not modify the caller s variable If the value is mutable the function may modify the caller s variable in place gt gt gt def try Co modifyl x vp Z x 23 y append 42 z 99 new reference print x print y print z gt gt gt a 77 immutable variable gt gt gt b L99 mutable variable gt gt gt c 28 rS ey uO MOC An 2 c doy e ce Looe Z 224 gt gt gt print a vy gt gt gt print b IPM gt gt gt print c 28 Functions have a local variable table called a local namespace The variable x only exists within the function fry fo modify 2 4 5 Global variables Variables declared outside the function can be referenced within the function In 114 x 5 In 115 def addx y E e return x y 2 4 Defining functions 23 Python Scientific lecture notes Release 2013 1 In 116 addx 10 Qut ee 5 But these global variables cannot be modified within the function unless declared global in the function This doesn t work In 117 def setx y ase d Q Print x is s In 118 setx 10 5S ais O In 120 Out eos This works In 121 def setx y global x X y prine x ia 90 In 122 setx 10 x is 10 In 123 Oui isis 2 4 6 Variable number of para
194. g with Python Now that the basics of working with Numpy and Scipy have been introduced the interested user is invited to try these exercises 5 11 1 Maximum wind speed prediction at the Sprogo station The exercise goal is to predict the maximum wind speed occurring every 50 years even if no measure exists for such a period The available data are only measured over 21 years at the Sprog meteorological station located in Denmark First the statistical steps will be given and then illustrated with functions from the scipy interpolate module At the end the interested readers are invited to compute results from raw data and in a slightly different approach 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 iis defined as p i
195. ge 298 Integration page 298 Exercises page 298 Equation solving page 298 Exercises page 299 Linear Algebra page 299 Matrices page 299 Differential Equations page 300 Exercises page 300 16 1 First Steps with SymPy 16 1 1 Using SymPy as a calculator SymPy defines three numerical types Real Rational and Integer 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 gt gt gt from sympy import a Rational 1 2 gt gt gt a be gt gt gt ax2 je SymPy uses mpmath in the background which makes it possible to perform computations using arbitrary precision arithmetic That way some special constants like e pi oo Infinity are treated as symbols and can be evaluated with arbitrary precision gt gt gt pi 27 piss gt gt gt pi evalf 3414159265350979 gt gt gt pi exp 1 evalf 5 85987448204884 as you see evalf evaluates the expression to a floating point number There is also a class representing mathematical infinity called oo 16 1 First Steps with SymPy 295 Python Scientific lecture notes Release 2013 1 gt gt gt oo gt 99999 True z gt OO r l OO 16 1 2 Exercises 1 Calculate v2 with 100 decimals 2 Calculate 1 2 1 3 in rational arithmetic 16 1 3 Symbols In contrast to othe
196. ge raw master skimage data coins png Display the histogram and try to perform histogram segmentation Try two segmentation methods an edge based method using skimage filter canny and scipy ndimage binary_fill_holes and a region based method using skimage morphology watershed and skimage filter sobel to compute an ele vation map Compute the sizes of the coins 12 6 Measuring objects properties ndimage measurements 249 Python Scientific lecture notes Release 2013 1 Other measures Correlation function Fourier wavelet spectrum etc One example with mathematical morphology granulometry http en wikipedia org wiki Granulometry_ 28morphology 29 gt gt gt def disk structure n Struct Neezeros 2 om r de om r ix xy x ex pea NGOS su Ard db 2 dec bs ode mask x n 2 y n 2 lt nx xZ struct mask 1 return struct astype np bool D gt gt gt def granulometry data sizes None S max data shape if sizes None sizes range l1 s 2 2 granulo ndimage binary opening data structure disk_structure n sum for n in sizes return granulo np random seed 1 n 10 l 256 im npzeros 1 d points Jeno vrandom random 2 mese zem oom ess OT leastype nip rnt Points I vase yoe Em Eo imc im ndimage gaussian_filter im sigma 1 4 n mask im gt im mean granulo granulometry mask sizes np arange 2 12 6 Measuring objects properties ndimag
197. 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 poo der f yield 1 yield 2 gt gt gt SEN generator object t st Oxea gt gt gt gen gt gt gt gen next 1 7 1 Iterators generator expressions and generators 146 Python Scientific lecture notes Release 2013 1 gt gt gt gen next 2 gt gt gt gen next Traceback most recent call last prio Vasrdine line d iw module StoplIteration Let s go over the life of the single invocation of the generator function gt gt gt def f Print scare yield 3 print middle yield 4 print finished gt gt gt gen f gt gt gt next gen Seat 3 gt gt gt next gen middle 4 gt gt gt next gen Finished Traceback most recent call last GLtoprIteratron 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 m
198. gnoring the invalid numbers gt gt gt date nploadsxt dats populations t b gt gt gt populations np ma masked array data 1 gt gt gt year datal 0 gt gt gt bad_years year gt 1903 amp year lt 1910 year gt 1917 amp year lt 1918 gt gt gt means and and l means or gt gt gt populations bad_years 0 np ma masked gt gt gt populations bad_years 1 np ma masked gt gt gt populations mean axis 0 masked array data 40472 7272727 18627 2727273 42400 0 mask False False False fill value 1e 720 gt gt gt populations std axis 0 masked array data 21087 056469 TIE ooo a 3322 5062255 8l mask False False False le 20 fill value Note that Matplotlib knows about masked arrays gt gt gt ile LOE year POPUL tions oe ma poeb lineon Line D Ob ect uode uu sonal 80000 70000 60000 50000 40000 A 30000 20000 10000 1800 1905 1910 1915 1920 8 4 Array siblings chararray maskedarray matrix 188 Python Scientific lecture notes Release 2013 1 8 4 3 recarray purely convenience ee Aer Darry la ar ue QUIS gs de yoe 4 ese 7 vue Oy Em p gt gt gt arr2 arr view np recarray gt gt gt arr2 x Chacaray a p o dtype S1 gt gt gt arrzZ y arcay L 21 8 4 4 matrix convenience e always 2 D e x is the matrix product not the elementwise one
199. gt 2D array gt gt gt a shape LLLI gt gt gt a durs 0l 10 20 90913 gt gt gt ad b array px Ue s EOS odios Ars 20 dur mons ese Seale Se EN We have already used broadcasting without knowing it gt gt gt a np ones 4 5 gt gt gt a 0 2 we assign an array of dimension 0 to an array of dimension 1 gt gt gt a guru Wb Z2 ep Sey een o ud EK dhens wea fre wiley hee odes files Iles ikar Dels Pa 1 iL al BEN le BRA BRA BR c 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 Example Let s construct an array of distances in miles between cities of Route 66 Chicago Springfield Saint Louis Tulsa Oklahoma City Amarillo Santa Fe Albuquerque Flagstaff and Los Angeles gt gt gt mu wleposts Npeakray 0 199 209 7364 ol 117571475 1544 P 1913 2448 gt gt gt distance array np abs mileposts mileposts np newaxis gt gt gt distance array ende vC Oj 198 9035 753567 99 1175 1475 1544 1913 l 198 OF MOS S38 OUO Ds AU L346 1715 L035 LOS Or 483 S66 ule iy L241 1610 7367 SL 433 Oe geo 4395 739 Xe 117 Ll erl Gls Boe aaa iS On 304 604 Olp 1042 e 977 clay A307 304 O 3007 369 739 Lavo erp Lilie Feo 04 300 OF 69 Wc 15443 13467 1241 390904 Gia 269 69 0a 267 Pode ile Velo
200. gt gt deco instance 7 2 Decorators 151 def function x args prine An rune ron in decorator call 2o fpumetlomt xxkwargs BOSE FOO X La TUNGE d DS Python Scientific lecture notes Release 2013 1 kwargs Contrary to normal rules PEP 8 decorators written as classes behave more like functions and therefore their name often starts with a lowercase letter In reality it doesn t 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 gt gt gt class def init__ self arg this method is called in print ino cecoraror init self arg arg call self function this method is called to print in decorator call Self rurnctbxon return self wrapper _wrapper self print in the wrapper return self tunctron args def function def sargo gt gt gt deco_instance in GCeCoracor iNT E LOO gt gt gt deco_instance def function args print inr Tunecion in decorator call foo Pe FUNG Eom ly 12 in the wrapper 11 A ie xxkwargs args ADS i tJ Lin CuUncCELON args replacing_decorator_class object the decorator expression arg do the job sell arg kwargs kwargs kwargs replacing decorator class 60 kwargs A decorator like this can do pre
201. gt med_denoised ndimage median_filter noisy 3 Gaussian filter Median filter d 8 Median filter better result for straight boundaries low curvature im np zeros 20 2071 Sms cu se im ndimage distance transform bf im im noise im F 0 2 np random randn xim shape im med ndimage median filter im noise 3 I Median filter Error Other rank filter ndimage maximum filter ndimage percentile filter Other local non linear filters Wiener scipy signal wiener etc Non local filters 12 4 Image filtering 239 Python Scientific lecture notes Release 2013 1 Total variation TV denoising Find a new image so that the total variation of the image integral of the norm L1 of the gradient is minimized while being close to the measured image gt gt gt from skimage filter import tv denoise gt gt gt tv denoised tv denoise noisy weight 10 gt gt gt More denoising to the expense of fidelity to data gt gt gt tv denoised tv denoise noisy weight 50 noisy TV denoising more TV denoising y Exercise 2 denoising Create a binary image of Os and 1s with several objects circles ellipses squares or random shapes Add some noise e g 20 of noise Try three different denoising methods for denoising the image gaussian filtering median filtering and total variation denoising Compare the histograms of the three different denoised images Which one
202. h np array scikit image scikit learn Common tasks in image processing Input Output displaying images Basic manipulations cropping flipping rotating mage filtering denoising sharpening mage segmentation labeling pixels corresponding to different objects Classification Feature extraction Registration More powerful and complete modules OpenCV Python bindings e CellProfiler 232 Python Scientific lecture notes Release 2013 1 TK with Python bindings many more Chapters contents Opening and writing to image files page 233 Displaying images page 234 Basic manipulations page 236 Statistical information page 236 Geometrical transformations page 237 Image filtering page 238 Blurring smoothing page 238 Sharpening page 238 Denoising page 239 Mathematical morphology page 240 Feature extraction page 243 Edge detection page 243 Segmentation page 243 Measuring objects properties ndimage measurements page 246 12 1 Opening and writing to image files Writing an array to a file from scipy import misc 1l misc lena misc imsave lena png 1 uses the Image module PIL import matplotlib pyplot as plt pu ums mow il pit show Creating a numpy array from an image file gt gt gt from scipy import misc gt gt gt lena misc imread lena png gt gt gt type lena 12 1 Open
203. hange some parts of the image ie Er X L 1 d P UTR 5 i 5 ame I P s ge 7 pou 4 1 Let s use the imshow function of pylab to display the image In 3 import pylab as plt In 4 lena misc lena In 5 plt imshow lena Lena is then displayed in false colors A colormap must be specified for her to be displayed in grey In 6 plt imshow lena cmap plt cm gray Create an array of the image with a narrower centering for example remove 30 pixels from all the borders of the image To check the result display this new array with imshow In 9 crop lena Penal30 30 302 30 e We will now frame Lena s face with a black locket For this we need to create a mask corre sponding to the pixels we want to be black The mask is defined by this condition y 256 2 x 250 427 In 15 v s npsogrvdl0 95125 0 5512 4 x and y indices Ol pixels In 16 y shape x shape OTI dusk 55 35 25 In 17 centerx centery 256 256 center of the image In PIS moek ly cemtery 22 ww Wx cemberx xu2 5 250942 4 circle then we assign the value O to the pixels of the image corresponding to the mask The syntax is extremely simple and intuitive In 19 lena mask 0 In 20 plt imshow lena Out 20 lt matplotlib image AxesImage object at 0xa36534c gt
204. he context manager can swallow the exception by returning a true value from exit Exceptions can be easily ignored because if exit doesn t 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 7 3 Context managers 158 Python Scientific lecture notes Release 2013 1 if issubclass type self type return True swallow the expected exception raise AssertionError wrong exception type with assert raises KeyError Dau Roe 7 3 2 Using generators to define context managers When discussing generators page 146 it was said that we prefer generators to iterators implemented as classes because they are shorter sweeter and the state is stored as local not instance variables On the other hand as described in Bidirectional communication page 147 the flow of data between the generator and its caller can be bidirectional This includes exceptions which can be thrown into the generator We would like to implement context man
205. he k ind optional keyword argument gt gt gt cubic_interp interpld measured_time measures kind cubic gt gt gt cubic results cubic interp computed time The results are now gathered on the following Matplotlib figure 5 7 Interpolation scipy interpolate 117 Python Scientific lecture notes Release 2013 1 1 0 e e measures inear interp cubic interp 0 5 0 0 0 5 1 0 1 35 0 2 0 4 0 6 0 8 1 0 scipy interpolate interp2d is similar to scipy interpolate interpld but for 2 D arrays Note that for the interp family the computed time must stay within the measured time range See the sum mary exercise on Maximum wind speed prediction at the Sprog station page 126 for a more advance spline interpolation example 5 8 Numerical integration scipy integrate The most generic integration routine is scipy integrate quad gt gt gt from scipy integrate import quad no ares err usc npe m sap aoe Np allelose res 2 True soc VpwalUeOLese erry L res qe Others integration schemes are available with ixed quad quadrature romberg scipy integrate also features routines for integrating Ordinary Differential Equations ODE In particular scipy integrate odeint isa 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
206. he numpy i file This interface file defines various so called typemaps which support conversion between Numpy arrays and C Arrays In the following example we will take a quick look at how such typemaps work in practice We have the same cos doubles function as in the ctypes example void cos doubles double in array double out array int size include meus men Compute the cosine of each element in in array storing the result in Ob array 47 void cos doubles double in array double out array int size int i tor 05309509265 99 o t arr yli 3eossscic revu This is wrapped as cos_doubles_func using the following SWIG interface file Example of wrapping a C function that takes a C double array as input using numpy typemaps for SWIG x emodule coscdoubles zd the resulting C file should be built as a python extension define SWIG FILE WITH INIT Includes the header in the wrapper code x Tu CUM GOs Coubleg A oe include the numpy typemaps x include numpy i jx need this for correct module initialization 27 Sinit import array o typemaps for the two arrays the second will be modified in place x Sapply double IN ARRAY1 int DIM1 double in array int size in Sapply double INPLACE ARRAY1 int DIM1 double x out array int size out Wrapper for cos doubles that massages the types Sinline takes as input two numpy arrays void
207. he other one is the expression adhering to the decorator syntax i e an at symbol and the name of the decorating function Function can be decorated by using the decorator syntax for functions Qdecorator e def function 0 pass e A function is defined in the standard way e An expression starting with placed before the function definition is the decorator The part after must be a simple expression usually this is just the name of a function or class This part is evaluated first and after the function defined below is ready the decorator is called with the newly defined function object as the single argument The value returned by the decorator is attached to the original name of the function 7 2 Decorators 149 Python Scientific lecture notes Release 2013 1 Decorators can be applied to functions and to classes For classes the semantics are identical the original class definition is used as an argument to call the decorator and whatever is returned is assigned under the original name 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 name of the decorated function doubling as a temporary variable must be used at least three times which is pro
208. hing is possible when something different is substituted for the original function or class the new object can be completely different Nevertheless such behaviour is not the purpose of decorators they are intended to tweak the decorated object not do something unpredictable Therefore when a function is decorated by replacing it with a different function the new function usually calls the original function after doing some preparatory work Likewise when a class is decorated by replacing if with a new class the new class is usually derived from the original class When the purpose of the decorator is to do something every time like to log every call to a decorated function only the second type of decorators can be used On the other hand if the first type is sufficient it is better to use it because it is simpler 7 2 2 Decorators implemented as classes and as functions 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 witha ca11 method or in theory even as lambda functions Let s 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
209. hon Scientific lecture notes Release 2013 1 gt gt gt ndimage binary_erosion a structure np ones 5 5 astype a dtype arraya ED 0 gre 07 70 O XS O 0 0 0 0 O 0 O 0 0 0 0 O Ol LOr 07 Or Or U7 07 0 O 0 0 0 0 O 0 O 0 0 0 0 O0 Ol Oo Up 0 0 0 0 9o Dilation gt gt gt a np zeros 5 5 aro a2 2 2 gt gt gt a eub cn ez ez ez ly Ws Wen Woe Won lz Dur dier dus Ouz sly Os Op Oar Og le U Osp Day Ory Oz 1 gt gt gt ndimage binary dilation a astype a dtype DOLOT TOTON 1S UN C MUN Ce LSS cana tv MM Os cs cs Ose Je DM n OX Sis Oto Wer dis ies die edis Cee dU Jine XU ile Xs ee Oe Oro 1 Opening gt gt gt a np zeros 5 5 dtype np int Soo sg pb pj qd 24 gt gt gt a array ITO 07 0 0p U1 Gis hers aller O Ch eee vile alee O9 a Gi Sl S SNR Ds os On 3079 Ms 1 gt gt gt Opening removes small objects gt gt gt ndimage binary_opening a structure np ones 3 3 astype np int gusce ror e lt 0 bacs dier alba Uds MO css ib Vite MOE Doe ex ao poc dou Or On O Os UNUS gt gt gt Opening can also smooth corners gt gt gt ndimage binary opening a astype np int ambo Po 0 0 07 Ol Des Oke Se 3E uu ie these dis ale rules OG CO EIE lu UIS RO 20 0520 Oa Closing ndimage binary closing Exercise Check that opening amounts to eroding then
210. hresholding use Gaussian mixture model Python Scientific lecture notes Release 2013 1 histogram gt gt gt mask im gt im mean astype np float gt gt gt mask 0 1 im gt gt gt img mask cnp random randn masks shape gt gt gt from sklearn mixture import GMM gt gt gt classif GMM n_components 2 gt gt gt classif fit img reshape img size GMM aa gt gt gt classif means aire Cll Wes e eee sue QUOS OQ IO 259 No sgrE elassii cOvarsa navel arra O20746 Oe2e725327 gt gt gt classif weights agra e409 So Eo NEED NECS o CO ROPA OMEN REY gt gt gt threshold np mean classif means gt gt gt binary img img gt threshold Use mathematical morphology to clean up the result gt gt gt Remove small white regions histogram gt gt gt open img ndimage binary opening binary img 2 x Remove small olack hole gt gt gt close img ndimage binary closing open img 244 12 5 Feature extraction EE ES eee Exercise Check that reconstruction operations erosion propagation produce a better result than opening closing gt gt gt eroded img ndimage binary erosion binary img gt gt gt reconstruct img ndimage binary propagation eroded img mask binary img gt gt gt tmp np logical not reconstruct img gt gt gt eroded tmp ndimage binary erosion tmp gt gt gt reconstruct final np logical not n
211. 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 5 11 Summary exercises on scientific computing 126 Python Scientific lecture notes Release 2013 1 Computing the cumulative probabilities The annual wind speeds maxima have already been computed and saved in the numpy format in the file examples max speeds npy thus they will be loaded by using numpy gt gt gt import numpy as np gt gt gt max speeds np load intro summary exercises examples max speeds npy gt gt gt years_ nb Max speeds siape 0 Following the cumulative probability definition p i from the previous section the corresponding values will be gt gt gt cprob np arange years nb dtype np float32 1 years nb 1 and they are assumed to fit the given wind speeds gt gt gt sorted_max_speeds np sort Max Speeds Prediction with UnivariateSpline In this section the quantile function will be estimated by using the UnivariateSpline class which can represent a spline from points The default behavior is to build a spline of degree 3 and points can have different weights according to their reliability Variants are Interpolat
212. ials have some advantages in interpolation 3 4 2 Loading data files Text files Example populations txt year hare lynx Carrot 1300 30e3 4e3 48300 MOONI 47 2e3 6 1e3 48200 1902 70 2693 9 883 41500 1903 77 4e3 35 2e3 38200 gt gt gt data np loadtxt dala populealLtons txt gt gt gt data ges 1900 30000 7 4000 48300 OUI 4720057 GIU 4320051 9022 020057 P8008 sooo al gt gt gt np savetxt pop2 txt data gt gt gt data2 np loadtxt pop2 txt Note If you have a complicated text file what you can try are e np genfromtxt e Using Python s I O functions and e g regexps for parsing Python is quite well suited for this 3 4 Advanced operations 78 Python Scientific lecture notes Release 2013 1 Reminder Navigating the filesystem with Python In 1 pwd show current directory Zhomev user stutt 201T1 numpy tutoriat In 2 cd ex homeZuser stutt 20r1l numpy tutorral ex In LSls ds populetronstxt Spoecres bb Images Using Matplotlib gt gt gt img plt imread data elephant png gt gt gt img shape img dtype 020025 2007 3 dtype rlobt2 gt gt gt plt imshow img lt matplotlib image AxesImage object at gt po plt savefig plor pnag gt gt gt plt imsave red elephant img 0 cmap plt cm gray This saved only one channel of RGB gt gt gt plt imshow plt imread red elephant png matplotlib
213. ibraries have been written for these languages Example BLAS vector matrix operations e Drawbacks Painful usage no interactivity during development mandatory compilation steps verbose syntax amp etc manual memory management tricky in C These are difficult languages for non com puter scientists Scripting languages Matlab e Advantages Very rich collection of libraries with numerous algorithms for many different domains Fast execution because these libraries are often written in a compiled language Pleasant development environment comprehensive and well organized help integrated editor etc Commercial support is available Drawbacks Base language is quite poor and can become restrictive for advanced users Not free Other scripting languages Scilab Octave Igor R IDL etc e 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 What about Python e Advantages Very rich scientific computing libraries a bit less than Matlab though Well thought out language allowing to write very re
214. id void Py_InitModulle cos module np CosMethods IMPORTANT this must be called importe array To compile this we can use distutils again However we need to be sure to include the Numpy headers by using numpy get include from distutils core import setup Extension import numpy define the extension module cos module np Extension cos module np sources cos module np c include dirs numpy get include run the setup setup ext modules cos module np 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 x np pi 0 1 y Cos _module np cos func np x pylab plot x y pylab show And this should result in the following figure 18 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 e Part of the Python standard library Does not need to be compiled Wrapping code entirely in Python Disadvantages e Requires code to be wrapped to be available as a shared library roughly speaking d11 in Windows x SO in Linux and x dylib in Mac OSX e No good support for C 18 3 1 Example As advertised the wrapper code is in pure Python 18 3 Ctypes 317 Python Scientific lecture notes
215. iddle 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
216. ientation resolution gt gt gt from scipy import misc gt gt gt lena misc lena gt gt gt shifted_lena ndimage shift lena 50 50 gt gt gt shifted_lena2 ndimage shift lena 50 50 mode nearest gt gt gt rotated_lena ndimage rotate lena 30 gt gt gt cropped lena lena 50 50 50 50 gt gt gt zoomed lena ndimage zoom lena 2 gt gt gt zoomed_lena shape 1024 1024 In 35 subplot 151 Qut 35 3 matploblvb sxes AxcsSubplot object at 0x925Fr46c In 36 pl imshow shifted lena cmap cm gray Out 36 lt matplotlib image AxesImage object at 0x9593f6c gt in 37 axis out Eu Sr COS bU bo scu In 39 etc 5 10 2 Image filtering from scipy import misc lena misc lena import numpy as np noisy lena np copy lena astype np float noisy lena lena std 0 5 np random standard_normal lena shape blurred_lena ndimage gaussian_filter noisy_lena sigma 3 median lena ndimage median filter blurred lena size 5 from scipy import signal wiener lena signal wiener blurred lena 5 5 noisy lena Gaussian filter median filter Wiener filter Many other filters in scipy ndimage filters and scipy signal can be applied to images 5 10 Image processing scipy ndimage 122 Python Scientific lecture notes Release 2013 1 Exercise Compare histograms for the different filtered images 5 10 3 Mathematical morphology Mathematical
217. inates Blended transformations Using offset transforms to create a shadow effect The transformation pipeline 4 5 2 Matplotlib documentation User guide FAQ Installation Usage How To Troubleshooting Environment Variables e Screenshots 4 5 3 Code documentation The code is well documented and you can quickly access a specific command from within a python session gt gt gt import pylab as pl pom nelpotplcpibost Help om function plot an module matplotlib pyplort Olor rargs r kwargs Plot lines and or markers to the class ematplotlrb axes Axes aros s a variable length argument allowing for multiple x y pairs with an optional format string For example each of the following is egal DOE 9 y t plot x and y using default line style and color 4 5 Beyond this tutorial 99 Python Scientific lecture notes Release 2013 1 plotxe vy Dor plot x and y using blue circle markers plot y T DLOL yw Using x 49 andex array 921 1 Plott yv Er t ditto but with red plusses TE xw and or yv ws Z dimensional then the corresponding columns will be plotted 4 5 4 Galleries The matplotlib gallery is also incredibly useful when you search how to render a given graphic Each example comes with its source A smaller gallery is also available here 4 5 5 Mailing lists Finally there is a user mailing list where you can ask for help and a developers mailing list that is
218. ing and writing to image files 233 Python Scientific lecture notes Release 2013 1 Eee MUM c3 eo 1s gt gt gt lena shape lena dtype 051257 512 dtbype uints dtype is uint8 for 8 bit images 0 255 Opening raw files camera 3 D images gt gt gt l tofile lena raw Create raw file gt gt gt lena_from_raw np fromfile lena raw dtype np int64 gt gt gt lena from raw shape 262144 gt gt gt lena from raw shape 512 512 gt gt gt import os gt gt gt os remove lena raw Need to know the shape and dtype of the image how to separate data bytes For large data use np memmap for memory mapping data are read from the file and not loaded into memory Working on a list of image files gt gt gt for i in range 10 im np random random integers 0 255 10000 reshape 100 100 EM Mmisc imsave random U2d png lt i m gt gt gt from glob import glob gt gt gt filelist glob random png So gt Tilelisce sort 12 2 Displaying images Use matplotlib and imshow to display an image inside amatplotlib figure gt gt gt 1 misc lena gt gt gt import matplotlib pyplot as plt gt gt gt Dit amshow 4 omapepltJom ogrey matplotlib image AxesImage object at 0x3c7f710 Increase contrast by setting min and max values gt gt gt plt imshow l cmap plt cm gray vmin 30 vmax 200 matplotlib image AxesImage object at
219. invited to make an exercise by using the wind speeds measured over 21 years The measurement period is around 90 minutes the original period was around 10 minutes but the file size has been reduced for making the exercise setup easier The data are stored in numpy format inside the file examples sprog windspeeds npy Do not look at the source code for the plots until you have completed the exercise 5 11 Summary exercises on scientific computing 127 Cumulative probability Python Scientific lecture notes Release 2013 1 1 0 0 8 e Cn e B 0 2 Vig 32 98 m s ue 22 24 26 28 30 32 34 Annual wind speed maxima m s Figure 5 1 Solution Python source file Summary exercises on scientific computing 128 Python Scientific lecture notes Release 2013 1 The first step will be to find the annual maxima by using numpy and plot them as a matplotlib bar figure 30 25 20 15 10 Annual wind speed maxima m s 5 10 15 20 Year Figure 5 2 Solution Python source file The second step will be to use the Gumbell distribution on cumulative probabilities p_i defined as log log p i for fitting a linear quantile function remember that you can define the degree of the UnivariateSpline Plotting the annual maxima versus the Gumbell distribution should give you the following figure The last step will be to find 34 23 m s for the maximum wind speed occurring every 50 years 5 11 2 Non linear
220. ir class ReservoirEvolution HasTraits reservoir Instance Reservoir name DelegatesTo reservoir inflows Array dtype np float604 shape None releass Array dtype np float64 shape None initial stock Float stock Property depends_on inflows releases initial_stock month Property depends_on stock Traits view teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee eee eee HH HH HEA THE traits view View item 7 name Group 14 3 What are Traits 284 Python Scientific lecture notes Release 2013 1 ChacoPlocitent Monch stock 7 show Label Pelse E widen 500 resizable True Traits properties 9T STq3qTTT PTTSTTTTHTTTScrPEPTSTTSSSPRSPETESTPSygqsrpSsPySS3y get stock self i m m fixme should handle cases where we go over the max storage wee return self initial stock self inflows self releases cumsum get month selt return np arange self stock size if name as matu 7 3 reservoir Reservoir name Project A max storage 30 max release 100 0 head 60 efficiency 0 8 qe dal sroek 10 ini Lows ts Np array Oez releases_ts np array 4 view ReservoirEvolution reservoir reservoir inflows inflows_ts releases releases ts view configure_traits Edit properties Name Project A Plot Editar stock c O bho ht el ete ERES Lee ee Ee Ine D zn m na Ix n e e 14 4 Ref
221. is kind of indexing 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 3 1 The numpy array object 52 Python Scientific lecture notes Release 2013 1 gt gt gt a np arange 10 soo ax cmm ES ils umb que 71 2o sl array Lbs Als JE ll gt gt gt b np arange 10 The image below illustrates various fancy indexing applications gt gt gt a 0 1 2 3 4 1 2 3 4 5 array 1 12 23 34 45 gt gt gt a 3 I0 2 5 array 30 32 35 40 42 45 50 52 55 gt gt gt mask array 1 0 1 0 0 1 dtype bool gt gt gt a mask 2 array 2 22 52 We can even use fancy indexing and broadcasting page 59 at the same time gt gt gt a np arange 12 reshape 3 4 peice Oy DE 2710 same as afi 2 np ones 2 2 dtype int 3 2 Numerical operations on arrays Section contents Elementwise operations page 53 Basic reductions page 55 Broadcasting page 59 Array shape manipulation page 62 Sorting data page 65 Some exercises page 66 Summary page 72 3 2 1 Elementwise operations With scalars 3 2 Numerical operations on arrays 53 gt gt gt a np array Il 2 3 41 a uw x array Z 3 4 51 gt gt gt 2xxa array 2 4 Qu bed All arithmetic operates elementwise gt gt gt b np ones 4 1 gt gt gt lt a BD Hugo i ie
222. is 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 In addition to the basic use case of wrapping native code Cython supports an additional use case namely interac tive optimization Basically one starts out with a pure Python script and incrementally adds Cython types to the 18 5 Cython 324 Python Scientific lecture notes Release 2013 1 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 While others solutions that autogenerate code can be quite difficult to debug for example SWIG Cython comes with an extension to the GNU debugger that helps debug Python Cython and C code Note The autogenerated C code uses the Python C Api Advantages Python like language for writing C extensions Autogenerated code e Supports incremental optimization ncludes a GNU debugger extension e Support for C Since version 0 13 Disadvantages Must be compiled Requires an additional library but only at build time at this problem can be overcome by shipping the generated C files 18 5 1 Example The main Cython code for our cos module is
223. is used to scale the colormap If None the min of the data will be used Example In 1 import numpy as np in 2 wc icheva np morid 0 07 serio mesas In 3 X renp costtheta In 4 y r np sin theta In 5 24 noesinir 7 In 6 from enthought mayavi import mlab In 7 2 miab mesh x y x CoOlormap Gist earch petent 0 1 0 Xe du Out 7 lt enthought mayavi modules surface Surface object at Oxde6f08c 15 1 Mlab the scripting interface 291 Python Scientific lecture notes Release 2013 1 In Iel miabemesh x uw Zy extenk 0 e cs representation wireframe line width 1 color 0 5 0 5 0 5 Out 8 enthought mayavi modules surface Surface object at Oxdd6a71c gt 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 orrlientatrion vertical OUL I tvekeclasses scalar bari aceor ocallarBarhcecorm Ob yece at scoop In 10 mlab title polar mesh Out 10 enthought mayavi modules text Text object at Oxd8ed38c gt In 11 mlab outline Out 7 OuL lil lt enthouoht mayav i modulss outline 0utline object at OxddZlbooc In 12 mlab axes Out 7 Out 12 enthought mayavi modules axes Axes object at Oxd2e4bcc gt l 60e 16 0 847 0 546 0 399 0 25 0 103 D 0442 B 192 15 1 Mlab the scripting interface 292 Python Scientific l
224. 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 207 Reminder Python functions def f a b c return some result 3 2 Numerical operations on arrays 70 Python Scientific lecture notes Release 2013 1 Exercise Mandelbrot set 1 5 1 0 0 5 0 0 0 5 2 0 1 1 0 0 5 0 0 0 5 1 0 Write a script that computes the Mandelbrot fractal The Mandelbrot iteration N max 50 some threshold 50 Qr Sos dey for j in xrange N max Z Z A2 C Point x y belongs to the Mandelbrot set if c lt some threshold Do this computation by 1 Construct a grid of c x 1j y values in range 2 1 x 1 5 1 5 2 Do the iteration 3 Form the 2 d boolean mask indicating which points are in the set 4 Save the result to an image with gt gt gt import matplotlib pyplot as plt gt gt gt plic rmshtowimask r extent 2 2 Ll L 5 d4 5 matplotlib image AxesImage object at gt poc pde gt gt gt plt savefig mandelbrot png 3 2 Numerical operations on arrays 71 Python Scientific lecture notes Release 2013 1 Exercise Markov chain Pj l J Markov chain transition matrix P and probability distribution on the states p 1 0 lt P i j lt 1 probability to go from state i to state j 2 Transition rule Phew P void 3 all sum P axis 1 1 p sum 1
225. ix common CSR CSC functionality subclass of data matrix sparse matrix classes with data attribute fast matrix vector products and other arithmetics sparsetools constructor accepts dense matrix array sparse matrix 11 2 Storage Schemes 223 Python Scientific lecture notes Release 2013 1 shape tuple create empty matrix data ij tuple data indices indptr tuple e many arithmetic operations considerably more efficient than CSR for sparse matrices with dense sub matrices use like CSR vector valued finite element discretizations Examples create empty BSR matrix with 1 1 block size like CSR gt gt gt mtx sparse bsr matrix 3 4 dtype np int8 gt gt gt mtx 2x4 Sparse Matrix of type stvpe numpy ince gt with 0 stored elements blocksize 1x1 in Block Sparse Row format gt gt gt mtx todense iene a sec Oe 07 07 0 BOs Oy tO Ol 0 0 O 0 dtype int89 create empty BSR matrix with 3 2 block size gt gt gt MEX sparse bsr matrix 3 4 blocks rze 5 2 dtypeenp irnbs gt gt gt mtx lt 3x4 sparse matrix of type type numpy int8 with 0 stored elements blocksize 3x2 in Block Sparse Row format gt gt gt mtx todense Merci VOR 0 kOe 0l Lee Os O DR E L0 0 0 du dtype inte a bug e create using data ij tuple with 1 1 block size like CSR poc row No abray TOP Oa
226. k most recent call last NotImplementedError fancy indexing supported over one axis only Coordinate Format COO also known as the ijv or triplet format three NumPy arrays row col data data i isvalueat row i col i position permits duplicate entries subclass of data matrix sparse matrix classes with data attribute fast format for constructing sparse matrices constructor accepts dense matrix array 11 2 Storage Schemes 219 Python Scientific lecture notes Release 2013 1 sparse matrix shape tuple create empty matrix data ij tuple very fast conversion to and from CSR CSC formats fast matrix vector sparsetools fast and easy item wise operations manipulate data array directly fast NumPy machinery no slicing no arithmetics directly use facilitates fast conversion among sparse formats when converting to other format usually CSR or CSC duplicate entries are summed together facilitates efficient construction of finite element matrices Examples create empty COO matrix gt gt gt mtx sparse coo matrix 3 4 dtype np int8 gt gt gt MEX LOdense maccs y A Oe Oil igi onem Me Lom 2059 ds Dl uite spe 3 TO create using data ij tuple gt gt gt TOW Op array Up 3 15 01 poo coL Hosarray 0 9 Ly 22 gt gt gt data np array 4 5 7 9 gt gt gt mtx sparse coo_matrix data row
227. l ill conditionning in low dimensions Error on f x An ill conditionned very non quadratic function 70 30 1300 350 200 250 Simplex method the Nelder Mead The Nelder Mead algorithms is a generalization of dichotomy approaches to high dimensional spaces The al gorithm works by refining a simplex the generalization of intervals and triangles to high dimensional spaces to bracket the minimum Strong points it is robust to noise as it does not rely on computing gradients Thus it can work on functions that are not locally smooth such as experimental data points as long as they display a large scale bell shape behavior However it is slower than gradient based methods on smooth non noisy functions iterations function calls Error on f x An ill conditionned 50 100 150 200 250 non quadratic function iterations function calls Error on f x An ill conditionned very 50 100 150 200 250 non quadratic function In scipy scipy optimize fmin implements the Nelder Mead approach gt gt gt def f x The rosenbrock function ae returm 5 wi ecce nO 2 Pow ODESmuze Lmarmet Ee 2 Optimization terminated successfully Current function value 02000000 Iterations 46 puncectron evyalviarions gi eabray 02999985685 0 99996682 13 2 A review of the different optimizers 261 Python Scientific lecture notes Release 2013 1 13 2 5 Global optimizers If your problem do
228. l local variables must be declared with edet Nole also Lhat this function receives 4pointers CO ihe data the traditional solution to passing complex variables around cdef double complex z z in 0 cdef double complex c c in 0 cdet int k the integer we use in the for loop Straightforward iteration for Kk am Tange lOO 2 Zee a NE ik Zee kes sexes 1o 000 break Return the answer for this point z uou z Boilerplate Cythom definitions it YOu dom to really need bo read this park xt Just pulls an stuff from the Numpy C headers 8 2 Universal functions 179 Python Scientific lecture notes Release 2013 1 cedet GxXteun from Tnhumpy arrayob ect ia vord import array ctypedef int npy_intp det enum NPY TYPES NPY_CDOUBLE ecce nam Trom Mune Ur runcob ces h Vod Import Urune etypeder vold PyUPumnmcGenerTePunetvon char x npy intp Moy rntp object PyUPunc cPromBPuncAndDste PyUPuncGenerrcPuncrrvone func woddese data Chars types int ntypes int Min mb nout ini identity Char nane hare doc 10t C VOLT RyUP Une DD D charsx Mey Inept APY Intp wes ds Required module initialization import array import ufunc 7 The actual ufune secnm du on cdef PyUFuncGenericFunction loop func 1 cdef char input output types 3 cdef void xelementwise funcs 1 loop lfune 0 PyUrune DD ID input output types 0 NPY_CDOUBLE input our put types NPY
229. le endian integer e 44 byte block of raw data in the beginning of the file 4 byte unsigned little endian integer 4 byte unsigned little endian integer e followed by data size bytes of actual sound data The wav file header as a Numpy structured data type gt gt gt wav header dtype np dtype heb ba sere ub flexible sized scalar type item size 4 Me Me SS IG Meca little endian unsigned 32 bit integer PEOUMAG 4 Sog 4 byte string Wok tie cts rea imp store vaudiro Eme Yuzu iin Se heme la Ae more of the same sample rate sgg byte rate Tu ock o Lia Cis bits per samplet uz oua ad OCS SU ie wes airas quss OB data size gd the sound data itself cannot be represented here it does not have a fixed size See Also wavreader py gt gt gt wav header dtype format dryper gd gt gt gt wav header dtype fields lt dictproxy obe SE 4545 gt gt gt wav_header_dtype fields format dey pet s4 uo The first element is the sub dtype in the structured data corresponding to the name format The second one is its offset in bytes from the beginning of the item 8 1 Life of ndarray 164 Python Scientific lecture notes Release 2013 1 Exercise Mini exercise make a sparse dtype by using offsets and only some of the fields gt gt gt wav header dtype np dtype dict
230. learn cluster import spectral_clustering gt gt gt 1 100 gt gt gt x y Mp indices 1 1 12 5 Feature extraction 245 gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt Python Scientific lecture notes Release 2013 1 Centerl 28 24 centers 40 50 center3 67 58 center4 24 70 radsusly xrgdius2 radiuss rsdrus4 16 14 15 14 eqxrTOolel x centerl 0 2 Cy centerll l 2 radiusl 2 Circle x center20 w2 sb ty cencerZ Vere x radius ka cirolas Centers 0 e442 4 yo centerslllex2 s radiuso 2 circle4 x center4 0 2 y center4 1 2 lt radius4x 2 4 circles img cCirelel circle t circle circled mask img astype bool img img astype float img t 1 t 0 24np random randn ximg shape Convert the image into a graph with the value of the gradient on the edges graph image img_to_graph img mask mask Take a decreasing function of the gradient we take it weakly dependant from the gradient the segmentation is close to a voronoi graph data np exp graph data graph data std labels spectral_clustering graph k 4 mode arpack label im
231. lease 2013 1 Chapters contents e Introduction page 82 Python and the pylab mode page 83 pylab page 83 e Simple plot page 83 Using defaults page 84 Instantiating defaults page 84 Changing colors and line widths page 85 Setting limits page 86 Setting ticks page 86 Setting tick labels page 87 Moving spines page 87 Adding a legend page 88 Annotate some points page 88 Devil is in the details page 89 Figures Subplots Axes and Ticks page 89 Figures page 90 Subplots page 90 Axes page 90 Ticks page 91 Other Types of Plots examples and exercises page 91 Regular Plots page 93 Scatter Plots page 93 Bar Plots page 94 Contour Plots page 94 Imshow page 95 Pie Charts page 95 Quiver Plots page 96 Grids page 96 Multi Plots page 96 Polar Axis page 97 3D Plots page 97 Text page 98 Beyond this tutorial page 98 Tutorials page 98 Matplotlib documentation page 99 Code documentation page 99 Galleries page 100 Mailing lists page 100 Quick references page 100 Line properties page 101 Line styles page 102 Markers page 102 Colormaps page 102 4 1 Introduction 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
232. 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 you re impatient and want to practice now please skip it and go directly to Loading and visualization page 131 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 Earth s topography see for more details 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 1sprsjprs 2008 09 007 5 11 Summary exercises on scientific computing 129 Python Scientific lecture notes Release 2013 1 Jp hd Gumbell cumulative probability Vo 34 23 m s 20 25 30 35 40 45 Annual wind speed maxima m s Figure 5 3 Solution Python source file 5 11 Summary exercises on scientific computing 130 Python Scientific lecture notes Relea
233. 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 7 1 4 Bidirectional communication Each yield statement causes a value to be passed to the caller This 1s the reason for the introduction of generators by PEP 255 implemented in Python 2 2 But communication in the reverse direction is also useful One obvious way would be some external state either a global variable or a shared mutable object Direct communication is possible thanks to PEP 342 implemented in 2 5 It is achieved by turning the previously boring yield statement into an expression When the generator resumes execution after a yield statement the caller can call a method on the generator object to either pass a value into the generator which then is returned by the yield statement or a different method to inject an exception into the generator 7 1 Iterators generator expressions and generators 147 Python Scientific lecture notes Release 2013 1 The first of the new methods is send value which is similar to next but passes value into the generator to be used for the value of the yield expression In fact g next and g send None are equivalent The second of the new methods is throw type value None traceback None which is equivalent to raise type value traceback at the point of the yiel
234. lso defined 8 3 Interoperability features 185 Python Scientific lecture notes Release 2013 1 8 4 Array siblings chararray maskedarray matrix 8 4 1 chararray vectorized string operations gt gt gt X np arrdgyv clta DO 2 ccc view np chararray Do Seo T Chararvay ate bbb eee dtype S5 gt gt gt x upper Chnararcray A p BBB Ce Te dtype S5 Note view hasa second meaning it can make an ndarray an instance of a specialized ndarray subclass 8 4 2 masked array missing data Masked arrays are arrays that may have missing or invalid entries For example suppose we have an array where the fourth entry 1s invalid gt gt gt x mnp array i 2 Ig I One way to describe this is to create a masked array gt gt gt mx np ma masked_array x mask 0 0 0 1 0 gt gt gt mx Imasked array data 127 5 mask False False False True False fill_value 999999 Masked mean ignores masked data gt gt gt mx mean De gt gt gt np mean mx Z9 The masked array returns a view to the original array gt gt gt mx 1 9 gt gt gt x array ihe 9 3 99 Sx The mask You can modify the mask by assigning gt gt gt mx 1 np ma masked gt gt gt mx masked array data 1 3 5 mask False True False True False till valus 999999 The mask is cleared on assignm
235. lution gt gt gt x0 np array 3 50 20 1 dtypesrlost compare the result of scipy optimize leastsq and what you can get with scipy optimize fmin_slsqp when adding boundary constraints 5 11 Summary exercises on scientific computing 133 Python Scientific lecture notes Release 2013 1 5 11 3 Image processing application counting bubbles and unmolten grains Det Spot Mag 10 4 mm 15 0 kY SSD 5 8 41x 3 25 mm MV 15 05 2009 1280 C Statement of the problem 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 This Scanning Element Microscopy image shows a glass sample light gray matrix with some bubbles on black and unmolten sand grains dark gray We wish to determine the fraction of the sample covered by these three phases and to estimate the typical size of sand grains and bubbles their sizes etc 2 Crop the image to remove the lower panel with measure information 3 Slightly filter the image with a median filter in order to refine its histogram Check how the histogram changes 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
236. maps keys to values It is an unordered container gt gt gt tel emmanuelle 5752 sebastian 5578 gt gt gt Cel francis 5915 gt gt gt tel sebastian t 5579 rtrauncris 5915 emmanuelle S757 gt gt gt tell sebastian BSO gt gt gt tel keys 7 sebastian francis emmanuelle gt gt gt tel values ESS Se Sols dS oe Aranes an tel True It can be used to conveniently store and retrieve values associated with a name a string for a date a name etc See http docs python org tutorial datastructures html dictionaries for more information A dictionary can have keys resp values with different types More container types Tuples Tuples are basically immutable lists The elements of a tuple are written between parentheses or just separated by commas gt gt gt t 12345 54321 hello gt gt gt t 0 12345 gt gt gt t hZ345 s23202 hemne gt gt gt u 0 2 Sets unordered unique items SSS ca E UE M Tbe ee a gt gt gt 5S Sec al ele Si ae gt gt gt s difference Seen eee a LON 2 2 3 Assignment operator Python library reference says 2 2 Basic types 16 Python Scientific lecture notes Release 2013 1 Assignment statements are used to re bind names to values and to modify attributes or items of mutable objects In short it works as follows simple assignment 1
237. meters Special forms of parameters xargs any number of positional arguments packed into a tuple e xxkwargs any number of keyword arguments packed into a dictionary In 35 def variable args xargs xkwargs print args 15 ards print kwargs is kwargs In 36 variable args one two x 1 y 2 z 3 args 1s oner two kvaro cie ae Ae oe ep cvs cn sues on 2 4 7 Docstrings Documentation about what the function does and its parameters General convention In 67 def funcname params Concise one line sentence describing the function Extended summary which can contain multiple paragraphs wee F function Dody pass 2 4 Defining functions seg Python Scientific lecture notes Release 2013 1 In 68 funcname Type 1 Ligie 6 I e ia Base Class type nunc pomis Sring Form function funcname at Oxeaa0f0 gt Namespace Interactive File lt ipython console gt Definition funcname params DOGS T Concise one line sentence describing the function Extended summary which can contain multiple paragraphs Note 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 func tions that you may want to follow for your own functions with a Parameters section an Examples
238. mmers 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 Matlab s 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 imple mented 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 Scipy s routines are optimized and tested and should therefore be used when possible Chapters contents File input output scipy io page 105 Special functions scipy special page 105 Linear algebra operations scipy linalg page 106 Fast Fourier transforms scipy fftpack page 107 Optimization and fit scipy optimize page 111 Statistics and random numbers scipy stats page 115 Interpolation scipy interpolate page 117 Numerical integration scipy integrate page 118 Signal processing scipy signal page 120 Image processing scipy ndimage page 121 Summary ex
239. more details odeint solves first order ODE systems of the form dy dt rhs yl y2 t0 As an introduction let us solve the ODEdy dt 2ybetweent 0 4 with the initial condition y t O 1 First the function computing the derivative of the position needs to be defined gt gt gt def calc derivative ypos time counter arr counter arr 1l 5 8 Numerical integration scipy integrate 118 Python Scientific lecture notes Release 2013 1 return 2 x ypos 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 gt gt gt counter np zeros 1 dtype np urntl65 The trajectory will now be computed gt gt gt from scipy integrate import odeint gt gt gt time vec np linspace 0 4 40 gt gt gt yvec info odeint calc derivative 1 time vec args counter full output True Thus the derivative function has been called more than 40 times which was the number of time steps gt gt gt counter array 129 dtype uint1i19 and the cumulative number of iterations for each of the 10 first time steps can be obtained by soos aod mctu ts array lol 309 454 49 Dor 57 59 9554 05 99 udtvpe ulito2 Note that the solver requires more iterations for the first time step The solution yvec for the trajectory can now be plotted 1 0 0 8 0 6 0 4 y
240. more technical 4 6 Quick references Here is a set of tables that show main properties and styles 4 6 Quick references 100 Python Scientific lecture notes Release 2013 1 4 6 1 Line properties Description Appearance antialiased True or False use antialised Al E sed rendering Anti aliased matplotlib color arg linestyle or Is see Line properties page 101 float the line width in points Cap style for solid lines Join style for solid lines Cap style for dashes Join style for dashes see Markers page 102 markeredgewidth line width around the marker mew symbol markeredgecolor edge color if a marker is used mec markerfacecolor face color if a marker is used mfc size of the marker in points 4 6 Quick references 101 Python Scientific lecture notes Release 2013 1 4 6 2 Line styles TEE 600 OL VM Aun FTX TAN MtAoOaO_ AZ E oa F A Y a FA B T A I O O E cw 8 a I5 e AV 4 8 949 7 908796 I Pie AY 4 H 9 99 909 rijo OAVA4bRBE x9 2001 24 90 E c a rite AVIAPH XOYr x 100 1 O E I i o o Q A V 4 E x99 ry zc 4 Oe 9 bp rise O AV4bH x 9 209 99 rile OAV RH KO y x LOW Oe f rite AV4IPRPH XOyr x 1001 O ps f moo tie avrvearPrm ix y yr 46084 e 8 F E 7 a Ah o C o d END 01 os 0 o 0 5 00 oh d 0 a 4 6 3 Markers Gp au OS NMS Em SV Ae DA ua sx z
241. mple gt gt gt class D object property def a self print getting 1 return 1 a setter def a self value print setting value a deleter def a self print deleting gt gt gt D a property object st Ux gt gt gt D a fget lt function a at Ox oo gt gt gt D a fset Pumietr Wem a aci Os S S a gt gt gt D a fdel EUNICE qon a at Ox coo gt gt gt d D X Varies this is not the same a function gt gt gt d a getting 1 il gt gt gt d a 2 Decorators 154 Python Scientific lecture notes Release 2013 1 Sem tal mone gt gt gt del d a deleting gt gt gt 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 e functools lru_cache memoizes an arbitrary function maintaining a limited cache of argu ments answer pairs Python 3 2 e functools total_ordering is a class decorator which fills in missing ordering methods __1t__ gt le based on a single available one Python 2 7 9 7 2 5 Deprecation of functions Let s say we want to print a deprecation warning on stderr on the first invocation of a function we don t like anymore If we don t want to modify the function we can
242. multi dimensional problems in scipy optimize Exercise Curve fitting of temperature data The temperature extremes in Alaska for each month starting in January are given by in degrees Celcius Me dre or aba ee ooe cy 2 22 7 TA crue EIE imc xod SOO pi a deu o Hen o eke 5257 ceo Sal Soe Plot these temperature extremes 2 Define a function that can describe min and max temperatures Hint this function has to have a period of 1 year Hint include a time offset Fit this function to the data with scipy optimize curve_fit Plot the result Is the fit reasonable If not why Is the time offset for min and max temperatures the same within the fit accuracy 5 5 Optimization and fit scipy optimize 114 Python Scientific lecture notes Release 2013 1 Exercise 2 D minimization Six hump Camelback function The six hump camelback function 4 a f x y 4 212 ze zy Ay Ay has multiple global and local minima Find the global minima of this function Hints e Variables can be restricted to 2 lt x lt 2and 1 lt y lt 1 e Use numpy meshgrid and pylab imshow to find visually the regions e 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 See the summary exercise on Non linear least squares curve fitting application to point
243. n d ing d root find ing an 1 curve fitt 1mensiona RE S gt gt gt from scipy import opt lon f a scalar funct inimum o Finding the m Let s define the following function gt gt gt def f x X s n return x 2 10 np It and plot no arcange 10 gt gt gt X E gt gt gt DIE plor x gt gt gt plt show 111 imize opt scipy ion and fi imizat 5 5 Opt Python Scientific lecture notes Release 2013 1 120 100 80 60 40 20 2075 5 y 5 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 2o Optimize min bros iy 0 Optimization terminated successfully Current function value 7 945823 Iterations 5 Function evaluations 24 Gradient evaluations 8 ara 092421995 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 gt gt gt optimize fmin bfgs f 3 disp 0 SDRap 1595595746969 If we don t 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 the sim
244. n it converges 26 cd in 3 iterations as the quadratic approximation is then exact 10 15 20 25 Brent s method on a non convex function note that eration the fact that the optimizer avoided the local minimum is a matter of luck gt gt gt from scipy import optimize gt gt gt def f x return np exp x 7 w 2 gt gt gt x min optimize brent f It actually converges in 9 iterations gt gt gt x min 0 059 999090 Q9 TSO urs SO CIT x 2 L605 4 lt 6 10 Note Brents method can be used for optimization constraint to an intervale using Scipy optimize fminbound Note Inscipy 0 11 scipy optimize minimize scalar gives a generic interface to 1D scalar mini mization 13 2 2 Gradient based methods Some intuitions about gradient descent Here we focus on intuitions not code Code will follow Gradient descent basically consists consists in taking small steps in the direction of the gradient Table 13 1 Fixed step gradient descent A well conditionned quadratic function A i EON m An ill conditionned quadratic function DE E S The core problem of gradient methods on ill conditioned problems is that the gradient tends not to point in the direction of the minimum We can see that very anisotropic ill conditionned functions are harder to optimize 13 2 A review of the different optimizers 256 Python Scientific lecture notes Release 2013 1
245. n 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 orwhile 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 IndentationError unexpected indent test py line 2 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 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 Scite is already configured this way 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 gt gt gt long line Here is a very very long line that we break in two parts Spaces Write well spaced code put whitespaces after commas around arithmetic operators etc gt gt gt a 1 yes
246. n gt line 1 in lt module gt File Tmtrand pyx line 23311 in mtrand Randomstate permutation File mtrangspysx Line 3254 if mtrand Randomotate lt shuff le TypeError len of unsized object This also happens with long arguments and so np random permutation X shape 0 where X is an array fails on 64 bit windows where shape is a tuple of longs It would be great if it could cast to integer or at least raise a proper error for non integer types I m using Nunmpy 124 1 buile from ene oficial tarball om Windows 64 with visual ctudia 0007 on Pyemon org osse Python 0 What are you trying to do 1 Small code snippet reproducing the bug if possible What actually happens What you d expect 2 Platform Windows Linux OSX 32 64 bits x86 PPC 3 Version of Numpy Scipy gt gt print Mp version 2 Check that the following is what you expect gt gt gt print Op tile _ oe In case you have old broken Numpy installations lying around If unsure try to remove existing Numpy installations and reinstall 8 6 3 Contributing to documentation 1 Documentation editor e http docs scipy org numpy Registration Register an account Subscribe to scipy dev mailing list subscribers only 8 6 Contributing to Numpy Scipy 190 Python Scientific lecture notes Release 2013 1 Problem with mailing lists you get mail But you can turn mail delivery off change your subscription
247. nal Expressions if lt OBJECT gt Evaluates to False e any number equal to zero 0 0 0 0 0j an empty container list tuple set dictionary e False None Evaluates to True everything else a b Tests equality with logics gt gt gt l True a is b Tests identity both sides are the same object gt gt gt al is ie False gt gt gt lan e gt gt gt b 1 gt gt gt a is D True a in b For any collection b b contains a gt gt gt b 1 2 3 gt gt gt 2 in b True gt gt gt 5 in b False If b is a dictionary this tests that a is a key of b 2 3 5 Advanced iteration Iterate over any sequence You can iterate over any sequence string list keys in a dictionary lines in a file gt gt gt vowels aeiouy gt gt gt for i in powerful if i in vowels print i 2 3 Control Flow Python Scientific lecture notes Release 2013 1 gt gt gt message Hello Now are your gt gt gt message split returns a list Hello Bow ste your gt gt gt for word in message split print word Hello how are you 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 don t care about Warning Not safe to modify the sequence you are iterating over
248. names format sample rate data id OftfsSocLs otset I gt ottseoLt 2 otftsot 3l x Counted From Stare or Structure vn b formats list of dtypes for each of the fields and use that to read the sample rate and data id as sub array gt gt gt f open data test wav r gt gt gt wav header np fromfile f dtype wav header dtype count 1 po fa Coce gt gt gt print wav_header L CRIER A02 AWAVE p VENE 8s leb dy A EOD 22000 2 126 xd an Ta a l gt gt gt wav header sample rate array 16000 dt yoe uinc3Z Let s try accessing the sub array gt gt gt wav header data id array MES a i Bs NE INE dtype S1 gt gt gt wav header shape 1 gt gt gt wav header data id shape due 2s 2 When accessing sub arrays the dimensions get added to the end Note There are existing modules such as wavfile audiolab etc for loading sound data Casting and re interpretation views casting on assignment on array construction on arithmetic etc e and manually astype dtype data re interpretation e manually view dtype Casting Casting in arithmetic in nutshell only type not value of operands matters largest safe type able to represent both is picked scalars can lose to arrays in some situations Casting in general copies data 8 1 Life of ndarray 165 Note Exact rules see documentation http
249. nd umfpack can be used if the latter is installed as follows prepare a linear system gt gt gt import numpy as np gt gt gt from scipy import sparse Soe ex a codiace Ill 2 8 4 i 16 Secs SO Do oe E 5 pomo EOdemSe Dus dos Ae Sr OF OF Ole O 2 8 0 UV 0 i0 doc By By Og 0 O O 2 10 LO Op W Oe So gt gt gt rhs nmp array Lis 2 3 4 51 11 3 Linear System Solvers 226 Python Scientific lecture notes Release 2013 1 solve as single precision real gt gt gt mtxl mtx astype np float32 gt gt gt x dsolve spsolve mtxl rhs use_umfpack False gt gt gt print x EOS Zhe gt D l ile gt gt gt print Errore Mlk oe ee DECOR MOR Oe On OF Ore solve as double precision real gt gt gt mtx2 mtx astype np floato4 gt gt gt x dsolve spsolve mtx2 rhs use_umfpack True gt gt gt print x 106 SZ ily 2125 5 T gt gt gt print VRrror y nox x eis Ero TOF 0 OL 0 om solve as single precision complex gt gt gt mtxl mtx astype np complex64 gt gt gt x dsolve spsolve mtxl rhs use_umfpack False gt gt gt print x LO CaO Ou eA reorua e Le OOs gt gt gt print Error y mexi se 6 PhS Pru oU L 4Q EO QuFO 3g O 0 7 Oet0 7 04047 solve as double precision complex gt gt gt mtx2 mtx astype np complex128 gt gt gt x dsolve spsolve mtx2 rhs use_umfpack T
250. ne to errors Nevertheless the example above is equivalent to def fu nction e pass EUNCE Lom decor tor ECL vom 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 7 2 1 Replacing or tweaking the original object Decorators can either return the same function or class object or they can return a completely different object In the first case the decorator can exploit the fact that function and class objects are mutable and add attributes e g add a docstring to a class A decorator might do something useful even without modifying the object for example register the decorated class in a global registry In the second case virtually anyt
251. nflows self spillage print s 79 if name main projectA Reservoir name Project A max_storage 30 max release 5 0 hydraulic head 600 efficiency 0 8 State ReservoirState reservoir projectA storage 15 state release 5 0 state inflows Python Scientific lecture notes Release 2013 1 release the maximum amount of water during 3 time steps state update_storage True state print state State update storage True state print_state state update_storage True state print_state Dependency between objects can be made automatic using the trait Property The depends_on attribute ex presses 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 e get XXX for the getter of the XXX Property trait e set XXX for the setter of the XXX Property trait from traits api import HasTraits Instance DelegatesTo Float Range from traits api import Property from reservoir import Reservoir class ReservoirState HasTraits Keeps track of the reservoir state given the initial storage For the simplicity of the example the release is considered in hm3 timestep and not in m3 s mmm reservoir Instance Reservoir max storage DelegatesTo reservoir Float DelegatesTo reservoir min_release max_release state attributes storage Pr
252. ng 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 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 t
253. njugate 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 Table 13 3 Conjugate gradient descent iterations function calls Error on f x P 0 80 100 120 An ill conditionned non quadratic function Error on f x 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 gt gt gt def f x Ihe rosenbrock function return 2521 Seo pe oll sO RE uA po Oprmuze rmunecgcoo2 2 Optimization terminated successfully Current function value 0 000000 iterations 13 Punch Lom evaluacions 120 Gradient evaluations 30 cU C OO Oe c c These methods need the gradient of the function They can compute it but will perform better if you can pass them the gradient gt gt gt def fprime x return unp asrav t 25 5w r sc sc bro e Osee zer etse Eq epo 2 gt gt gt optimize fmin cg f 2 2 fprime fprime Optimization terminated successfully Current functvon value 0000000 Iterations 13 punctrohn evaluations 30 Gradient evaluations 30 array lL 0 99999199 0 99997536 Note that the function has only been evaluated 30 times compared to 120 without the gradient 13 2 3 Newton and quasi newton methods Newton methods using the Hessian
254. non convex optimization A convex function A non 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 Optimizing convex functions is easy Optimizing non convex functions can be very hard Note A convex function provably has only one minimum no local minimums 13 1 2 Smooth and non smooth problems A smooth function A non smooth function The gradient is defined everywhere and is a continuous function Optimizing smooth functions is easier 13 1 Knowing your problem 254 Python Scientific lecture notes Release 2013 1 13 1 3 Noisy versus exact cost functions Noisy blue and non noisy green functions Noisy gradients Many optimization methods rely on gradients of the objective function If the gradient function is not given they are computed numerically which induces errors In such situation even if the objective function is not noisy 13 1 4 Constraints Optimizations under constraints Here lt x lt 1 lt z2 lt 1 13 2 A review of the different optimizers 13 2 1 Getting started 1D optimization Use scipy optimize brent to minimize ID functions It combines a bracketing strategy with a parabolic approximation 13 2 A review of the different optimizers 255 Python Scientific lecture notes Release 2013 1 Error on f x i Brent s method on a quadratic functio
255. normalization Write a script that works with 5 states and e Constructs a random matrix and normalizes each row so that it 1s a transition matrix e Starts from a random normalized probability distribution p and takes 50 steps gt p 50 e Computes the stationary distribution the eigenvector of P T with eigenvalue 1 numeri cally closest to 1 Z2 p stationary Remember to normalize the eigenvector I didn t e Checks if p 50 and p stationary are equal to tolerance le 5 Toolbox no random rand dot no linalg eig reductions abs argmin comparisons all np linalg norm etc 3 2 7 Summary What do you need to know to get started Know how to create arrays array arange ones zeros 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 soc ala 0l 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 3 3 More elaborate arrays 3 3 More elaborate arrays 72 Python Scien
256. ns hore The Ufunc loop runs with the Python Global Interpreter Lock released Hence the nogil t And so all local variables must be declared with edef tf Note also that this function receives Spoilnters to the dala 8 2 Universal functions 176 Python Scientific lecture notes Release 2013 1 cdef double complex z z in 0 cdef double complex c c in 0 cder unb k the integer we use in the for oop TODO write the Mandelbrot iteration for one point here as you would write 1t 1n Python Say use 100 as the maximum number of iterations and 1000 as Ehe CULOLE for ZerealxxZ 4 Zeimag Z se HE db db db odb od TODO mandelbrot iteration should go here Return the answer for this point z out v Boilerplate Cvthonm definitions it The litany below is partic larly long but you don t really meed to t read this part it just pulls in stutr from the Numpy C headers cdef extern from numpy arrayobject h yoid impor array ctypedef int npy_intp eder enum NPY TYPES NEY DOUBLE NPY SCUOUB TEE NPY LONG Cdet extern irom Thum y U Uncob ject h vord Impor urunc Ctypedef void xPyUPuncGenervchRupnctron charese Ney _intps MNpy_imeps void object PyUPFunc RromPuncArndDsta PyUPGuncGenerrcFunctrone tunc wvodxw data Chars types Int Meypes dne Nin ams mous int identity Char Name Char doc sb x List of pre defined loop functions vord PyUPUMC E f As d eharkte
257. nsional typed data page 183 The old buffer protocol page 183 The old buffer protocol page 184 Array interface protocol page 185 Array siblings chararray maskedarray matrix page 186 chararray vectorized string operations page 186 masked_array missing data page 186 recarray purely convenience page 189 matrix convenience page 189 Summary page 189 Contributing to Numpy Scipy page 189 Why page 189 Reporting bugs page 189 Contributing to documentation page 190 Contributing features page 191 How to help in general page 192 8 1 Life of ndarray 8 1 1 It s ndarray block of memory indexing scheme data type descriptor raw data how to locate an element how to interpret an element 8 1 Life of ndarray 161 Python Scientific lecture notes Release 2013 1 array scalar ndarray typedef struct PyArrayObject PyODjecc HEAD Block of memory char data Data type descriptor PyArray Descr xdescr Indexing scheme int nd npy intpp dimensioms npy intp xstrides Zu Other Stuff 7 PyObject xbase int flags PyObject xweakreflist PyArrayOb ject 8 1 2 Block of memory gt gt gt x np arrday ll 2 3 4 y dtypesnp rnt32 gt gt gt x data lt read write buffer for size 16 offset 0 at gt gt gt strix ddtka PASSO T EOD 00 cs 02 x00 700 x00 x03 x00 vos 00 04 200 QD xe D Memor
258. nt Documentation e Annotating axis e annotate command Python Scientific lecture notes Release 2013 1 Let s annotate some interesting points using the annotate command We chose the 27 3 value and we want to annotate both the sine and the cosine We ll first draw a marker on the curve as well as a straight dotted line Then we ll use the annotate command to display some text with an arrow t 2 Mover 7 2 Cli plou ite lx 10 np costl Color Diue unewrdthe2 9 Linestyle plsstobtesX eL Lbupuecsdiss yes scoop de ploasnmnotate r Ssan Fra pi 9 wvEroac iwsgrtio 12h9 xy t np sSin t lt yecoords daca xytext t0 3005 cextecoords oOtrsetecpothHLs Ponbpsrxeele arrowprops dict arrowstyle gt connectionstyle arc3 rad 2 Pl plol Dee tls mpysini t le color red Jmnewrdth 7 5 Jd unestylesete p Searcer lic wl pss ume ily Oy codlor aed pisanmotacrei Geos irac 2 poi 13 eae tly Zhe xy t np cos t xycoords data xytext 90 50 textcoords otrset poincs tontsrze 1l90 arrowprops dict arrowstyle connectionstyle arc3 rad 2 4 2 10 Devil is in the details cosine p sine Hint Documentation e Artists e 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 they ll be rendered on a semi transparent white background This
259. ode literal notation to insert a character by using its name in the unicode database EM DASH 7 2 Decorators 156 Python Scientific lecture notes Release 2013 1 If the Unicode character was inserted directly it would be impossible to distinguish it from an en dash in the source of a program 7 2 8 More examples and reading e PEP 318 function and method decorator syntax e PEP 3129 class decorator syntax http wiki python org moin PythonDecoratorLibrary http docs python org dev library functools html http pypi python org pypi decorator Bruce Eckel Decorators I Introduction to Python Decorators Python Decorators II Decorator Arguments Python Decorators III A Decorator Based Build System 7 3 Context managers A context manager is an object with enter and exit methods which can be used in the with state ment with manager as var do something var is in the simplest case equivalent to var manager enter try do_something var finally manager exit 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 isn t present the value returned by enter issimply ignored
260. ok into what x 0 1 actually means moo 9505501 0 0402 71697 1026 8 1 4 Indexing scheme strides Main point The question gt gt gt x np array l1 2 3 m Io op Fle sche yoe nip mes gt gt gt str x data EXO 02 x03 04 x05 OG x07 9 401090 E34 At which byte in x data does the item x 1 2 begin The answer in Numpy strides the number of bytes to jump to find the next element stride per dimension gt gt gt x strides Syr 8 2S2 byte orrsert 249 x 1592 Pts me Sepak gt gt gt x data byte_offset rA x06 gt gt gt x 2 6 simple flexible C and Fortran order gt cp array Die 5 4 5 6 Li eo 9 sy deypeenp rntl6 order Cr gt gt gt x strides 168 8 1 Life of ndarray Python Scientific lecture notes Release 2013 1 cn gt gt gt Sir x data ISO IO Vx OF sc010 03x00 vend 500 seg x00 06 00 0 T Nee D 08 voco De 00 Need to jump 6 bytes to find the next row Need to jump 2 bytes to find the next column gt gt gt y np array x order F gt gt gt y Strides 27 gt gt gt Ser ysdatad E Ol ec 00 504 se 07 x00 102 eO xO 00 veo 00 03 x00 06 00 e010 Need to jump 2 bytes to find the next row Need to jump 6 bytes to find the next column e Similarly to higher dimensions C last dimensions vary fastest smaller strides F first dimensions vary fastest shape di ds dn strides
261. ompatibility mot found cos doubles a 24 Warning 490 Fragment NumPy Backward Compatibility mob Found cosc doubles r 24 Warning 490 Fragment NumPy Backward Compatibility mot found creating build creating build temp linux x86 64 2 7 gee pehpcgdesnescel1cs cce IBEBUSCqesmu2gp oS Weeriece preeotypes fPIC qeo pthread rfno strzct alrassng g 02 DNDEBUG g EWwrapvy O3 Nall Wstrict prototypes rPIC gt In file included from home esc anaconda lib python2 7 site packages numpy core include numpy nda from home esc anaconda lib python2 7 site packages numpy core include numpy nda Peony Wome ese eimiaeoudey Ib Py hnonz acm essckggesmimpo core melde numpy arr irom eoscdoubles wrapccsi27065 home esc anaconda lib python2 7 site packages numpy core include numpy npy deprecated api h 11 2 gcc pthread shared build temp linux x86 064 2 7 cos doubles o EN Iu c UN 41 2 7 cos do 1s Portia de A cos doubles h cos doubles py cos doubles wrap c setup py Qoscedoublesoc cos doubles Cos doubles sex noy test cos doubles py And as before we convince ourselves that it worked import numpy as np import pylab import cos doubles np arange 0 2 x np pi 0 1 np empty like x X y cos_doubles cos_doubles_func x y pylabwelerix 7 l pylab show 18 5 Cython Cython is both a Python like language for writing C extensions and an advanced compiler for th
262. on Scientific lecture notes Release 2013 1 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 1s In 21 print com basic Wes s exceptions rst CODE Sb standard library Trst contiol Flow rst Tirst stoper ot python language mse demo2 py PUMICE HONS rst Dython logo pag demo py aCe Sie reusing_code rst In 22 print com exit_code 0 In 23 type com Out 423 7 sh RunningCcommand Walking a directory os path walk generates a list of filenames in a directory tree In 10 for d rpath dirnames filenames in os walk os curdrr for fp in filenames print os Pall aospach Ep Users courms sre scipy 2009 7 scrpy 2009_ctuborial scurce amdex 7st yswo Users courns src scipy2009 scipy 2009 _tuborial source view artay py swp Users cbhurns src scipy2009 scipy 2009 CLulorial source basic types rst Users7 courns sre scipy2009 scipy 2009 curerial source omo Users cbourns src scipy 720007 scipy 2009 o1 3107 Sci ce control or low St Environment variables In 9 import os In DII os envosromn kevs Out aie vt ded CESSISSE TERM PROGRAM VERSION PE SLREMOTECALL USER HOME T PATH pSt SHELL EDITOR WORRON HOME Ey LAO PAiEH 7 In 12 os environ PYTHONPATH Ou deg s3 Users churns
263. onstrated 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 e All the examples have been done on Linux they should be possible on other operating systems You will need a C compiler for most of the examples 18 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 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 Disadvantages May requires a substantial amount of effort Much overhead in the code Must be compiled High maintenance cost No forward compatibility across Python versions as C Api changes Note 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 9946 of the use cases you will be better off using an alternative technique 18 2 1 Example
264. operty depends_on inflows release y control attributes inflows Float desc Inflows hm3 f release Range low min_release high max_release spillage Property desc Spillage hm3 depends_on storage inflows release Ht Private traits TESTRRESESERERETRETRERERSEEE ATRSERSTRESAERER AEHTTEEESESTETTTTT storage Float Traits property implementation T b9tf yT syTSSdP STESTPETPSTPSPT STSTPST ST T def get storage self new storage self storage self release self inflows return min new storage self max storage def set storage self storage value self storage storage value def get spillage self new storage self storage self release self inflows overflow new storage self max storage return max overflow 0 def print state self print Storage tRelease tInflows tSpillage Str format VE join 27 22 for in rauge 4 1 print str_format format self storage self release self inflows self spillage print 79 Python Scientific lecture notes Release 2013 1 if name e maim ni 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 state print state Note Caching property Heavy computation or long running computation might be a problem when accessing a p
265. options at the bottom of http mail scipy org mailman listinfo scipy dev Send a mail scipy dev mailing list ask for activation To SCipy cevescipy ord Hai ird like to edit Numey Seipy docstrindgo My accoume ds XXXXX Cheers DIDI Check the style guide http docs scipy org numpy Don t be intimidated to fix a small thing just fix it e Edit 2 Edit sources and send patches as for bugs 3 Complain on the mailing list 8 6 4 Contributing features 0 Ask on mailing list if unsure where it should go 1 Write a patch add an enhancement ticket on the bug tracket 2 OR create a Git branch implementing the feature add enhancement ticket Especially for big invasive additions http projects scipy org numpy wiki GitMirror http www spheredev org wiki Git for the lazy Clone numpy repository gie clore origin sva Ua tege ce bL odo S EST SCENES ome Cit mm scummy cd numpy Create a feature branch git checkout b name of my feature branch ss E CE lt edit stuff gt Gite Commit c Create account on http github com or anywhere Create a new repository Github Push your work to github git remote add github gitG8github YOURUSERNAME YOURREPOSITORYNAME git git push github name of my reature branch 8 6 Contributing to Numpy Scipy 191 Python Scientific lecture notes Release 2013 1 8 6 5 How to help in general Bug fixes always welcome What irks you most
266. or 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 2 Compile the cos module wrap cintothe cos module so Luckily distutils knows how to handle SWIG interface files so that our setup py is simply from distutils core import setup Extension setup ext modules Extension cos module Sources ocosmodule c oos module e cd advanced intertacing with c swig ls cos module c cos module h iooscmodulesr setup py 18 4 SWIG 321 Python Scientific lecture notes Release 2013 1 python setup py build ext inplace r naing build ext building cos module extension swigging cos _module i to cos module wrap c swig python o Cos module wrap C Cos_module a creating build creating Duild temp linux x260 0472 7 gce pthread rno strict aliasing 9 O2 DNDEBUG 9g EWwrapy O gt Nall mwnstrict prototypes fPIC gee Pentead ino oae iee alaan G e DNDEBUG g Puea Os Wall Wetrice ererotypes fPIC Gee pthread shar
267. orgs g 0 Optimization terminated successfully Current uncer won value 0 000000 Tteractronss uv Function evaluations 144 Gradient evaluations 12 array L r 599992778 09 T LI TR obe ZAMBIE ie D 09551 91425071 4 44449794e 01 52 5556049se 01 6 66672149e 01 DRE DUO 8 88882036e 01 1000010266400 BFGS needs more function calls and gives a less precise result Note 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 Warning If the function is linear this is a linear algebra problem and should be solved with scapy lrinalg lstsqti 13 4 2 Curve fitting 1 0 0 5 0 0 0 5 13 6 0 5 1 0 1 5 2 0 2 5 3 0 Least square problems occur often when fitting a non linear to data While it is possible to construct our optimization problem ourselves scipy provides a helper function for this purpose scipy optimize curve_fit gt gt gt def f t omega phi return np cos omega x t phi pow cc eounpuicbnnmepacet0 Ov 50 gt gt gt y qox Ls dy t 2 ene candom normal size 50 s ODULI mTAescurwve fu Eos v array Unique M 3926600949 anwey Ul 00007994 ou OO O 0000 05560 95 SIS 3 OR 13 4 Special case non linear least squares 265 Python Scientific lecture notes Release 2013 1 Exercise Do the same with omega 3 What is the difficulty 13 5 Optimization with constraints 13 5
268. ort Vector Machines 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 17 2 Classification 304 Python Scientific lecture notes Release 2013 1 gt gt gt from sklearn import svm gt gt gt svc svm SVC kernel linear pou SVC ie eee Seddi ey dS varger SVC 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 Excercise Train an svm SVC on the digits dataset Leave out the last 10 and test prediction performance on these observations 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 Polynomial kernel RBF kernel Radial Basis Func tion E Svm SVC kerneldg rbf icd degree 3 gt gt gt gamma inverse of size of gt gt gt degree polynomial de xe radial kernel Exercise Which of the kernels noted above has a better prediction performance on the digits dataset 17 2 Classification 305 Python Scientific lecture notes Release 2013 1 1
269. oy sparsetools C module by Nathan Bell assume the following is imported gt gt gt import numpy as np gt gt gt import scipy sparse as sps gt gt gt import matplotlib pyplot as plt warning for NumPy users the multiplication with is the matrix multiplication dot product not part of NumPy passing a sparse matrix object to NumPy functions expecting ndarray matrix does not work 11 2 Storage Schemes 214 Python Scientific lecture notes Release 2013 1 11 2 1 Common Methods all scipy sparse classes are subclasses of spmat rix default implementation of arithmetic operations always converts to CSR subclasses override for efficiency shape data type set get nonzero indices format conversion interaction with NumPy toarray todense 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 e data usually stored in NumPy arrays 11 2 2 Sparse Matrix Classes Diagonal Format DIA very simple scheme e diagonals in dense NumPy array of shape n_diag length fixed length gt waste space a bit when far from main diagonal subclass of data matrix sparse matrix classes with data a
270. p functions With the Hessian e If you can compute the Hessian prefer the Newton method sclpy optimize tfmin negct If you have noisy measurements Use Nelder Mead scipy optimize fmin Or Powell scipy optimize fmin powell 13 3 2 Making your optimizer faster Choose the right method see above do compute analytically the gradient and Hessian if you can Use preconditionning when possible Choose your initialization points wisely For instance if you are running many similar optimizations warm restart one with the results of another Relax the tolerance if you don t need precision 13 3 3 Computing gradients Computing gradients and even more Hessians is very tedious but worth the effort Symbolic computation with Sympy page 294 may come in handy Warning A very common source of optimization not converging well is human error in the computation of the gradient 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 ss Optiumtze cheok oradi Prines Z 21 2 584 eo ONOLOS625e6 07 See also scipy optimize approx fprime to find your errors 13 3 Practical guide to optimization with scipy 263 Python Scientific lecture notes Release 2013 1 13 3 4 Synthetic exercices Exercice A simple quadratic function Optimize the following function using K 0 a
271. p zeros 5 5 dtype np int soo alta pes Sl a4 4 Sa gt gt gt a anran uS 0 10 9T Re ls whe sl On 280055 1r eleven ills Ohh Oe alee wie a Con gt gt gt ndimage binary_opening a structure np ones 3 3 astype np int Buscas C O 07 X 07 Hor uus ie Ugo es rds Dore alia tlhe Soni Or le tle ai ox De Du ue SO us 107 dS gt gt gt Opening can also smooth corners gt gt gt ndimage binary_opening a astype np int arcay IrO 07 07 07 0l COO ee Ole AO OS cigs cR Glee One Oia Ore lbs SO ROS Orr WO Oe 108 OTT Application remove noise gt gt gt sq are np zeros 32 32 0 oo sque 3m cst a gt gt gt np random seed 2 22 gt x y 3 np random random t2 20 1 299t vpetnp dme gt gt gt squarelx s 1 gt gt gt open_square ndimage binary_opening square gt gt gt eroded_square ndimage binary_erosion square gt gt gt reconstruction ndimage binary propagation eroded square mask square Closing dilation erosion Skeletonization reduce objects to one pixel thin lines keeping the same topology Many other mathematical morphology operations hit and miss transform tophat etc 12 4 Image filtering 242 Python Scientific lecture notes Release 2013 1 12 5 Feature extraction 12 5 1 Edge detection Synthetic data gt gt gt am Nps Zeros 256 256 gt gt gt im 64 64 64 64 1 SSS gt gt g
272. plest algorithm is the brute force algorithm in which the function is evaluated on each point of a given grid gt gt gt grid 10 dO 0 1 gt gt gt xmin global optimize brute f grid poc xmin global arise LOS 9 5 For larger grid sizes scipy optimize brute becomes quite slow scipy optimize anneal provides an alternative using simulated annealing More efficient algorithms for different classes of global opti mization problems exist but this is out of the scope of scipy Some useful packages for global optimization are OpenOpt IPOPT PyGMO and PyEvolve To find the local minimum lets constraint the variable to the interval 0 10 using 5 5 Optimization and fit scipy optimize 112 Python Scientific lecture notes Release 2013 1 scipy optimize fminbound pos omin local e pue hmaimoound tt Oy T0 gt gt gt xmin_local Boo 467 le Note Finding minima of function is discussed in more details in the advanced chapter Mathematical optimiza tion finding minima of functions page 252 Finding the roots of a scalar function To find a root ie a point where f x 0 of the function f above we can use for example Scipy optimize fsolve seo FOOL Optimize solve 1 our initial guess is 1 gt gt gt root array Olan Note that only one root is found Inspecting the plot of reveals that there is a second root around 2 5 We find the exact value of it by adjusting our initial guess
273. position m 0 2 000 05 10 15 20 25 30 35 40 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 gt gt gt mass 0 5 kg gt gt gt kspring 4 N m gt cviscous 0 4 is eS m so the system will be underdamped because gt gt gt eps Cviscous 7 2 x mass np osqrt kspring mass gt gt gt Cpo l rrue 5 8 Numerical integration scipy integrate 119 Python Scientific lecture notes Release 2013 1 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 mandom wo 2 k m gt gt gt U Coe NM VM eo SESS gt gt gt om coef kspring mass Thus the function will calculate the velocity and acceleration by gt gt gt def calc deri yvec time nuc omc return yvec 1 nuc x yvec 1 omc yvec 0 gt gt gt time vec np linspace 0 10 100 gt gt gt yarr odeint calc deri 1 0 time vec args nu coef om coef The final position and velocity are shown on the following Matplotlib figure 0 2 4 6 8 10
274. pport 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 x 5 X Maro gt gt gt integrate sin x x COS X gt gt gt integrate log x x xe Log x gt gt gt integrate 2 x sinh x x esi a ix Also special functions are handled easily gt gt gt integrate exp x 2 xerf x x Diet ly Ay Cerna 27 4 It is possible to compute definite integral gt gt gt integrate x 3 x 1 1 ne cx Ime eCgrarc siii lt y qo P v5 29 1 gt gt gt Integrate lcos x x Eom A p72 p Also improper integrals are supported as well gt gt gt integrate exp x x 0 oo 1 Integrate en XA x 005 9 1 pases T 16 3 6 Exercises 16 4 Equation solving SymPy is able to solve algebraic equations in one and several variables he IP SU VENERE S MES eere scc ME bosses om 16 4 Equation solving 298 Python Scientific lecture notes Release 2013 1 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
275. presented by playing with strides nog opaan 6 ade a aa a eaae 2 Doe uwcr gt gt gt b strides LA So far so good However gt gt gt str a data 25 40 0 0 1 X02 549160 0040 2057 gt gt gt b array T0 2 X ly 3 Sil dtiypesinte9 gt gt gt C b reshape 3 2 gt gt gt C array l0 2 4 lp 37 Si dtiypesexmnte 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 Example fake dimensions with strides Stride manipulation gt gt gt from numpy lib stride tricks import as strided gt gt gt help as strideg as strided x shape None strides None Make an ndarray from the given array with the given shape and strides 2239 3x Mosarray lly RS wditvpeseup unmbd6 gt gt gt as strided x strides 2 2 shape 2 array ll 3 dtype intic posco array l 3 dtiyvpesrnti6 See Also stride fakedims py 8 1 Life of ndarray 170 Python Scientific lecture notes Release 2013 1 Exercise dtype np int8 Spoiler Stride can also be 0 gt gt gt x np array 1 2 3 4 dtype np int8 gt gt gt y as_strided x strides 0 1 shape 3 4 gt gt gt y arre cU DE 27 gt 37 41 ins reto pert tnus l 2 37 Girly dtype intg gt gt gt y base base is x True Broadcasting Doing something useful with it outer product of 1 2 3 4 an
276. ps track of the reservoir state given the initial storage n m reservoir Instance Reservoir min storage Float max storage DelegatesTo reservoir min release Float max_release DelegatesTo reservoir Python Scientific lecture notes Release 2013 1 state attributes storage Range low min_storage high max_storage control attributes inflows Float desc Inflows Tamsil release Range low min_release high max_release spillage Float desc Spillage hm3 def print_state self print Storage tRelease tInflows tSpillage Str format E voim I 44 426 for 2 an range 4 print str_format format self storage self release self inflows self spillage Print x 79 Prr Traits listeners FFFFTEEERETEEEREEE EERE EEE EET ET ETE EE HE EE def _release_changed self new COV et the release is higher than zero warn all the inhabitants orf the valley m if new gt 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 600 efficiency 0 8 State ReservoirState reservoir projectA storage 10 state release 90 state inflows 0 state print_state The static trait notification signatures can be e def _release_changed self pass e def release changed self new pass e def release changed
277. r Computer Algebra Systems in SymPy you have to declare symbolic variables explicitly gt gt gt from sympy import x gt gt gt x Symbol x gt gt gt y Symbol y Then you can manipulate them gt gt gt x y x y 2X gt gt gt xty eZ oC ey ea Z Symbols can now be manipulated using some of python operators arithmetic amp gt gt lt lt boolean 16 2 Algebraic manipulations SymPy is capable of performing powerful algebraic manipulations We ll take a look into some of the most frequently used expand and simplify 16 2 1 Expand Use this to expand an algebraic expression It will try to denest powers and multiplications im 23 expand cxt Ole PAS S Saxtyxn Bayer Beers SS yas Further options can be given in form on keywords In 28 expand xty complex True Outil Tims simy F rols F rey im a Ol exeand Cos Cos we Orig rue Que qq 39 cos x cos y ssim ses VA 16 2 2 Simplify Use simplify if you would like to transform an expression into a simpler form In 19 simplify x x y x Out Sos 16 2 Algebraic manipulations 296 Python Scientific lecture notes Release 2013 1 Simplification is a somewhat vague term and more precises alternatives to simplify exists powsimp simplifica tion of exponents trigsimp for trigonometric expressions logcombine radsimp together 16 2 3 Exercises 1
278. r noi 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 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 As with other objects you can set figure properties also setp or with the set_something methods 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 Axes 1 subplot 2 1 1 subplot 2 2 1 subplot 2 2 2 subplot 1 2 1 subplot 1 2 2 Axes 2 Axes 3 subplot 2 1 2 subplot 2 2 3 subplot 2 2 4 Axes 4 Axes 5 4 3 3 Axes Axes are very similar to subplots but allow placement of plots at any location in the fig ure So if we want to put a smaller plot inside a bigger one we do so with axes axes 0 1 0 1 8 8 4 3 Figures Subplots Axes and Ticks 90 Python Scientific lecture notes Release 2013 1 4 3 4 Ticks Well formatted ticks are an important part of publishing ready figures Matplotlib provides a totally
279. r results to the file demo prof 10 2 5 Using gprof2dot In case you want a more visual representation of the profiler output you can use the gprof2dot tool S GererZde f per te Cemo prot det lond o demo pret pne Which will produce the following picture 10 2 Profiling Python code 207 Python Scientific lecture notes Release 2013 1 del Stest MNT 106 lt module gt 96 46 0 76 init 128 emodul amp e 0 0096 0 01 ae 1 basic 6 lt module gt 0 5290 0 0195 il Which again paints a similar picture as the previous approaches 10 3 Making code go faster Once we have identified the bottlenecks we need to make the corresponding code go faster 10 3 1 Algorithmic optimization The first thing to look for is algorithmic optimization are there ways to compute less or better For a high level view of the problem a good understanding of the maths behind the algorithm helps However it is not uncommon to find simple changes like moving computation or memory allocation outside a for loop that bring in big gains Example of the SVD 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 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 implem
280. re and were kindly provided by the GIS DRAIX 5 11 Summary exercises on scientific computing 131 Python Scientific lecture notes Release 2013 1 Fitting a waveform with a simple Gaussian model 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 e callscipy optimize leastsq Model A Gaussian function defined by Bat B Aexp c can be defined in python by gt gt gt def model t coeffs return coeffs 0 coeffs 1 np exp t coeffs 2 coeffs 3 2 where e coeffs 0 is B noise e coeffs 1 is A amplitude e coeffs 2 is u center e coeffs 3 is o width Initial solution An approximative initial solution that we can find from looking at the graph is for instance gt gt gt xD np array 3 30 15 ll dtvpe rloat 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 gt gt gt def residuals coeffs Vy t return y model t coeffs So let s get our solution by calling scipy optimize leastsq with the following arguments e the function to minimize e an initial solution the additional arguments to pass to the function from scipy optimize import leastsq gt g
281. re thus a good way to organize code in a hierarchical way Actually all the scientific computing tools we are going to use are modules gt gt gt import numpy as np data arrays gt gt gt Nps inspace 0 10 6 pires cr Oy par AR Gr Saye OL gt gt gt import scipy scientific computing 2 5 Reusing code scripts and modules 27 Python Scientific lecture notes Release 2013 1 In Python x y Ipython x y executes the following imports at startup gt gt gt import numpy gt gt gt import numpy as np gt gt gt from pylab import x gt gt gt import scipy and it is not necessary to re import these modules 2 5 3 Creating modules If we want to write larger and better organized programs compared to simple scripts where some objects are defined variables functions classes and that we want to reuse several times we have to create our own modules Let us create a module demo contained in the file demo py A demo module def print_b dicinamin gps qe print p def print a Teas 9 print a 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 emospuewnt swW a In 3 demo erin b b Impor
282. reter inserts the instance object as the first positional parameter self When a class method is invoked the class itself is given as the first parameter often called cls Class methods are still accessible through the class namespace so they don t pollute the module s names pace Class methods can be used to provide alternative constructors class Array object def init self data self data data classmethod def fromfile cls file data numpy load file return cls data This is cleaner then using a multitude offlagsto init e staticmethod is applied to methods to make them static i e basically a normal function but acces sible 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 doesn t require this e 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 gt gt gt class A object property def a self an important attribute return a value gt gt gt A a 7 2 Decorators 153 7 2 Python Scientific lecture notes Release 2013 1 Sproperty object at 5l gt gt gt A a a Value In this example A a is an read only attribute It is also documented help A includes th
283. ricFunction loop func 1 cdei char ptit output ypes cdef void xelementwise_funcs 1 Reminder some pre made Ufunc loops 2222 2222222222 SAA SO PEE a e aa float elementwise func float input 1 SX NEP SHUT NC SEE eee NO float ebtementwise Ttunco btloat anpur i float Input T SUME UE des double elementwise func double input 1 me Y pU Ecce double elementwise func double input 1 double input 2 po CXNEUTurmesp De elementwise func complex double xinput complex double complex double m NEUEN DEOD elementwise func complex double xinl1 complex double xin2 complex doublex 22222222222222 col222llllllllllllllllllllllllllllllllllllllllllllllcc o The full list Xs aboye Type codes NPY_BOOL NPY_BYTE NPY_UBYTE NPY_SHORT NPY_USHORT NPY_INT NPY_UINT NPY LONG NPY_ULONG NPY LONGLONG NPY ULONGLONG NPY FLOAT NPY DOUBLE NPY LONGDOUBLE NPY CFLOAT NPY CDOUBLE NPY CLONGDOUBLE NPY DATETIME T NPY TIMEDELTA NPY OBJECT NEY STRING NPY_UNICODE NPY VOID Toop runc Ol S 225 ODO Suitable PYUFUNO taput our Put IE V Des TO 222 TODO TODOS rill ay roest Of Input onl DUE types T Ihis thing is passed as the data parameter for the generic r PyUbUume loop to let at know which function at should call elementwise funcs 0 void x mandel single point a Construct che fS Hc mandel PyUFunc_FromFuncAndData Loop rune elementwise funcs Emu
284. roperty where the inputs have not changed The Q cached property decorator can be used to cache the value and only recompute them once invalidated Let s 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 For the simplicity of the example the release is considered in hm3 timestep and not in m3 s mm reservoir Instance Reservoir mO name DelegatesTo reservoir max storage DelegatesTo reservoir max release DelegatesTo reservoir min_release Float 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 fg fTf ST fSydTZsTSESTSTSSTSSTESTSTPSTSSTSSTSTSSTSSTSTTSTPSTPST ST Y traits view View Group VGroup Item name Item storage Item spillage label State style readonly VGroup Item inflows Item release label Control ff fT Private traits fTESTRESSTERRREEESRETEEERTREEEEATETTEEESESETETTTRRESATSTSTTTTT Python Sci
285. rting website for details 2 2 2 Containers Python provides many efficient types of containers in which collections of objects can be stored Lists A list is an ordered collection of objects that may have different types For example gt gt gt L red blue green black white gt gt gt type L Soe Hg Indexing accessing individual objects contained in the list gt gt gt L 2 green Counting from the end with negative indices gt gt gt TI NI white gt gt gt mp2 plack Warning Indexing starts at 0 as in C not at 1 as in Fortran or Matlab Slicing obtaining sublists of regularly spaced elements gt gt gt L xred blue green black white gt gt gt Oh ed green black 2 2 Basic types 12 Python Scientific lecture notes Release 2013 1 Warning Note that L start stop contains the elements with indices i suchas start lt i lt stop i ranging from start to stop 1 Therefore L start stop has stop start elements Slicing syntax L start stop stride All slicing parameters are optional gt gt gt L red blune green black white gt gt gt L 3 L eo was 2o m9 red blue green so ues red green white Lists are mutable objects and can be modified gt gt gt L 0 yellow gt gt gt L yellow blue green black white
286. rue gt gt gt print x LOG 00u J 21 0402 55 0 9 1 550 7 Ors UT Jui gt gt gt print Errors gt mios we co rhs EEror ORRO O Op OO O T m Construct a 1000x1000 I 1 matrix and add some values to zt convert if to CSR format and solve A x b for x and solve a linear system with a direct solver import numpy as np import scipy sparse as sps from matplotlib import pyplot as plt from scipy sparse linalg dsolve import linsolve rand Mp random rand mtx sps lil matrix 1000 1000 dtype np float64 mes lO sos and 100 eck EDS OO amex LO es MEX Setdvag rand 1000 pul sc plt spy mtx marker markersize 2 puc sow mtx mtx tocsr rand 1000 linsoilve spsolve mex rhs print rezidusl moe linalo norm mex o rhs examples direct_solve py 11 3 Linear System Solvers 227 Ea i ee EE CIS DIES 11 3 2 Iterative Solvers the isolve module contains the following solvers bicg BIConjugate Gradient bicgstab BIConjugate Gradient STABilized cg Conjugate Gradient symmetric positive definite matrices only cgs Conjugate Gradient Squared gmres Generalized Minimal RESidual minres MINimum RESidual qmr Quasi Minimal Residual 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
287. s page 94 Pie Chart pl pie Make a pie chart of an array page 96 Multiplot pl subplot Plot several plots at once page 96 Plot 2D or 3D data page 97 page 98 Python Scientific lecture notes Release 2013 1 Quiver Plot pl quiver Plot a 2 D field of arrows i f X A A ow yg ow F gt gt gt 4 WD YR AR Y A X VOX OX page 95 Grid pl grid Draw ticks and grid page 95 page 96 Text pl text Draw any kind of text pe 1 ma T r pd Vi Vp uvV t pg dp P y AE A i l 2 UP gt dai UP Td Vae Wing tae nn az gu A Oden Sap L tb ur e comet G pr 42M a Y gt Lat g s Tip Tg ee sing PTS C p T pe R vor Vinee nv Rm Xan e dr J m page 97 4 4 Other Types of Plots examples and exercises 92 4 4 1 Regular Plots Hint You need to use the fill between command Starting from the code below try to reproduce the graphic on the right taking care of filled areas Python Scientific lecture notes Release 2013 1 n 256 X p elinspace np o15 np pi Y np sin 2 X Dl plore X d J color blue DL plLOEtx X cxx color blue endpoint True alpha 1 00 alpha 1 00 Click on the figure for solution 4 4 2 Scatter Plots Hint Color is given by angle of X Y Starting from the code below try to reprod
288. s Convert the simple sieve to the sieve of Eratosthenes 1 Skip j which are already known to not be primes 2 The first number to cross out is j 3 1 8 Adding Axes Indexing with the np newaxis object allows us to add an axis to an array 3 1 The numpy array object 51 Python Scientific lecture notes Release 2013 1 gt gt gt z np array l1 gt gt gt zZ arra tl 2 Jm gt gt gt Z np newaxis durs c DM gt gt gt z np newaxis array TIL css 3 1 9 Fancy indexing Numpy arrays can be indexed with slices but also with boolean or integer arrays masks This method is called fancy indexing It creates copies not views Using boolean masks gt gt gt np random seed 3 gt gt gt a np random random_integers 0 20 15 gt gt gt a arkay DES Oy de E aly 9 10 Oc O 20 a Ze Wa dl gt gt gt a 3 0 array False True False True False False False True False True True False True False False dtype bool gt gt gt mask a 0 gt gt gt Gxtragcot Troma a mask or a a 3 0 gt gt gt extract From a extract a sub array with the mask eu SS URS Or OR lt 6 O XM gt gt gt a np arange 10 gt gt gt a Hus ss Indexing can be done with an array of integers where the same index is repeated several time gt gt gt eZ oue du vo 22 1 P ROEE T2 Sp Ze cbe cec Pyenenm Eres anran U2 ue y p21 New values can be assigned with th
289. s return NULL ye construct the output array like che input array wv out array PyArray NewLikeArray in array NPY_ANYORDER NULL 0 if out array NULL return NULL create the iterators TODO this iterator API is deprecated since 1 6 7 replace in favour of the new Npylter API in iter PyArrayIterObject PyArray IterNew PyObject in array out iter PyArrayIterObject PyArray IterNew out array lif in iter NULL out iter NULL goto fail iterate over the arrays while in iter index lt in iter size amp amp out iter index lt out iter size get the datapointers double x in dataptr double in iter dataptr double out dataptr double out_iter gt dataptr lso cosine Of DIM QUEE Ww wOUL dataptr os in dataptr update the iterator x PyArray TIER NEIN Iter PyArray LIEP NEXT T OUL lac et clean up and return the result PY DECREE ion Ior Py DECREE CUI I E TO RER OUt Tra return out_array in case bad things happen fail EXEC EB OUt TS Py qECBEBDI SUCI po DECREE OUt Si EU return NULL define Sg uwnctyonms m Inoue 27 static PyMethodDef CosMethods tacos Vac No4 COS Func Mop MELH VARABGS evaluate the cosine on a numpy array NULG NIU Or NOL Yu moule Initialization 27 PyMODINIT_FUNC 18 2 Python C Api 316 Python Scientific lecture notes Release 2013 1 initcos_module_np vo
290. s a starting point np random seed 0 K np random normal size 100 100 def f x return nunp sum np dot K x 1 2Z 4 no sum x Z x2 Time your approach Find the fastest approach Why is BFGS not working well Exercice A locally flat minimum Consider the function exp 1 1 x 2 yx x2 This function admits a minimum in 0 0 Starting from an initialization at 1 1 try to get within le 8 of this minimum point 13 4 Special case non linear least squares 13 4 1 Minimizing the norm of a vector function Least square problems minimizing the norm of a vector function have a specific structure that can be used in the Levenberg Marquardt algorithm implemented in scipy optimize leastsq Lets try to minimize the norm of the following vectorial function gt gt gt def f x return Np arcran x np earctam np luvumspaee 0 1 Lent zx X0 Mp Zeros 10 13 4 Special case non linear least squares 264 Python Scientific lecture notes Release 2013 1 gt gt gt optimize leastsq f x0 larray I 0 EET EU Le DERE 222225 n 35999 257 ORMAZA PES sisi eis 0 66666667 OVIT he 0 88888889 Jj Jes 2 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 gt gt gt def g x return np sum f x 2 gt gt gt optimize rtmaon
291. s 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 2 8 1 Exceptions Exceptions are raised by errors in Python ZeroDivisionError integer division or modulo by zero TyoeError unsupported operand type s for s aint and str En sles id AB 4554 2e7 KevyEE ror 3 In I5 b TE 2 2 Indexkirror list index out of range TATI 1 foobar AttributeError list object has no attribute foobar As you can see there are different types of exceptions for different errors 2 8 Exception handling in Python 38 Python Scientific lecture notes Release 2013 1 2 8 2 Catching exceptions try except In 8 while True Iwan ge x int raw_input Please enter a number break except ValueError print Ihat was no valid number Try again Please enter a number a That was NO valid number Try again Please enter a number 1 In 9 x run eet try finally In 10 try x int raw input Please enter a number finally Pring Thank yow for your input Please enter a number a Iman you For your input yaluebrrorz Anvalic literal for inr with base 10 Important for resource management e g closing a file Easier to ask for forgiveness than for permission In
292. s data array facilitates fast le conversion aH has data array fast row wise 225 Python Scientific lecture notes Release 2013 1 11 3 Linear System Solvers sparse matrix eigenvalue problem solvers live in scipy sparse linalg e the submodules dsolve direct factorization methods for solving linear systems isolve iterative methods for solving linear systems eigen sparse eigenvalue problem solvers e all solvers are accessible from gt gt gt import scipy sparse linalg as spla Pe Splas all LinearOperator Tester arpack aslinearoperator fisse Piquostetb 4 eg 4 COs CSc matr e v Cor matri a CaSOl Ote eigen eigen symmetric factorized gmres interface solys upepdgpdve a 7 lLomces X3umsolbwe T Polbpog J9cu amp o ou gam ga Conan iPspomosde spa s spi a spec lye fd test umf pack use solver utils p warnings 11 3 1 Sparse Direct Solvers default solver SuperLU 4 0 included in SciPy real and complex systems both single and double precision optional umfpack real and complex systems double precision only recommended for performance wrappers now live in scikits umfpack check out the new scikits suitesparse by Nathaniel Smith Examples e import the whole module and see its docstring gt gt gt from scipy sparse linalg import dsolve gt gt gt help dsolve both superlu a
293. s doubles function must be a double array with single dimension that is contiguous array ld double npct ndpointer dtype np double ndim 1 flags CONTIGUOUS load the library using numpy mechanisms Luped mpeusloadulibmary libcos2doublesg 8 setup the return typs and argument types libcd cos_doubles restype None Jed cos doubles farguypes larray 1d double array Id doubles Comune def cos doubles func in_array out_array return Jibocd cos_doubles in_ array out array ben in cacray Note the inherent limitation of contiguous single dimensional Numpy arrays since the C functions requires this kind of buffer e Also note that the output array must be preallocated for example with numpy zeros and the function will write into it s buffer e 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 import numpy as np import pylab import cos doubles x np arange 0 2 x np pi 0 1 y np empty like x coscdoublesccos doubles rune y py US Set y pybastsmev 18 4 SWIG 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
294. s from a setup py which is rather convenient from distutils core import setup Extension 4 derine the extension Module cos module Extension cos module sources cos module c run the setup setup ext_modules cos_module This can be compiled cd advanced intertacing with c python Cc api ls cos module c setup py python setup py build ext inplace 18 2 Python C Api 314 Python Scientific lecture notes Release 2013 1 running build ext building cos module extension creating build creating burlcd temps 55396 0422 Gee pthread fno strict aliasing 9 O02 DNDEBUG G Ewrapy O wall nstrict prototypes fPIC gcc pthread shared build temp linux x86_64 2 7 cos_module o L home esc anaconda lib lpython2 Bo sive build cos_module c cos_module so setup py build ext is to build extension modules inplace will output the compiled extension module into the current directory The file cos module so contains the compiled extension which we can now load in the Python interpreter In 1 import cos module In 2 cos module Types module SEring Form module cos module Trom ocos module so File home esc git working scipy lecture notes advanced interfacing_with_c python_c_api co Docstring seno docetring in Sle dur cos modulbe Sie oe a OC a ee ee a cce t aa ae 7 uos WO In 4 cos module cos func 1 0 Out 4i gt 0 5403
295. s of an Ufunc 1 Provided by user void ufunc_loop void xxargs int xdimensions int xsteps void xdata x int8 output elementwise function int8 input 1 INES input 2 x This function must compute the ufunc for many values at once in the way shown below a char xinput_1 ebhar argsl char input 2 charx args char output charx args 2 Int i DIT LI ii for i 05 3 dimensqonsq s q30 4 xoutput elementwise function x xinput 1 input_2 domu otl t 4S dero eus input 2 stepsll output steps 2 2 The Numpy part built by char types 3 Byees LOLs NEY EYTE ze Eye Of FIPS mpi Jaro w types NEV EYE type of second input arg tyres 2 e NEY BYTE A Cpe Of Third ZNDUL Arg wv PyObject xpython_ufunc PyUFunc_FromFuncAndData ucrume Loop NULLE types 1 ntypes x 2 Ye Dini neues 2 lp Ye pum oul puls 7 identity element name docstring unused e A ufunc can also support multiple different input output type combinations Making it easier 3 ufunc_loop is of very generic form and Numpy provides pre made ones PyUfunc f f float elementwise_func float input 1 PyUfunc ff ffloat elementwise func float input 1 float input 2 PyUfunc d d double elementwise func double input 1 PyUfunc dd ddouble elementwise func double input 1 double input 2 PyUfunc D D elementwise func npy cdouble xinput npy cdoublex output PyUfunc DD Delemen
296. s pointers as to what to look at next so pick the ones that you find more interesting If you have good ideas for exercises please let us know 1 Download the source code for each example and compile and run them on your machine 2 Make trivial changes to each example and convince yourself that this works E g change cos for sin 3 Most of the examples especially the ones involving Numpy may still be fragile and respond badly to input errors Look for ways to crash the examples figure what the problem is and devise a potential solution Here are some ideas a Numerical overflow b Input and output arrays that have different lengths c Multidimensional array d Empty array e Arrays with non doub1e types 4 Use the t imeit Python magic to measure the execution time of the various solutions 18 8 1 Python C API 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
297. se 2013 1 In this tutorial the goal is to analyze the waveform recorded by the lidar system 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 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 Therefore we use the scipy optimize module to fit a waveform to one or a sum of Gaussian functions Loading and visualization Load the first waveform using gt gt gt import numpy as np gt gt gt waveform 1 np load data waveform 1 npy and visualize it gt gt gt import matplotlib pyplot as plt gt gt gt t np arange len waveform 1 gt gt gt plt plot t waveform 1 gt gt gt plt show Intensity bins 0 10 20 30 AQ 50 60 70 80 Time ns As you can notice this waveform is a 80 bin length signal with a single peak The data used for this tutorial are part of the demonstration data available for the FullAnalyze softwa
298. section etc See http projects scipy org numpy wiki CodingStyleGuidelines docstring standard and http projects scipy org numpy browser trunk doc example py L37 2 4 8 Functions are objects Functions are first class objects which means they can be assigned to a variable an item in a list or any collection passed as an argument to another function In 38 va variable_args In 39 va three x 1 y 2 args is three kwargs 19 Be 2r xan L 2 4 9 Methods Methods are functions attached to objects You ve seen these in our examples on lists dictionaries strings etc 2 4 10 Exercises Exercise Fibonacci sequence Write a function that displays the n first terms of the Fibonacci sequence defined by e u 0 1 u 1 1 eu_ nt 2 u_ ntl1l un 2 4 Defining functions 25 Python Scientific lecture notes Release 2013 1 Exercise Quicksort Implement the quicksort algorithm as defined by wikipedia function quicksort array var list less greater if length array lt 2 return array select and remove a pivot value pivot from array for each x in array if x lt pivot then append x to less else append x to greater return concatenate quicksort less pivot quicksort greater 2 5 Reusing code scripts and modules For now we have typed all instructions in the interpreter For longer sets of instructions we need to change tack and write the code in text files using a text editor that
299. ses with data attribute fast matrix vector products and other arithmetics sparsetools constructor accepts dense matrix array sparse matrix shape tuple create empty matrix data ij tuple data indices indptr tuple efficient row slicing row oriented operations slow column slicing expensive changes to the sparsity structure use actual computations most linear solvers support this format Examples create empty CSR matrix gt gt gt mtx sparse csr matrix 3 4 dtype np int89 gt gt gt mtx todense t Metis IOs OF aS ED POs Oe era Ti Oy Up 07 Ollie dbypesxmbe create using data ij tuple gt gt gt oW Mp anra IOP Op by 2 327 2 boo Col eco ui 2a Oe nen gt gt gt data np array il 2 3 4 9 61 gt gt gt mtx sparse csr matrix data row col shape 3 3 gt gt gt mtx 3x3 sparse matrix of type type numpy into4 with 6 stored elements in Compressed Sparse Row format gt gt gt mtx todense Metric pq xc Oye Oy 3 aie 25 O 1 11 2 Storage Schemes 221 gt gt gt mtx data array MM 2 gt gt gt MEX indices array n2 gt gt gt MCXSX acini array 0 27 Su 05 dbyvpDeernm 32 Python Scientific lecture notes Release 2013 1 op ar or A 2p 0 d ue deype inte 32 e create using data indices indptr tuple gt gt gt data csimpesrics V p 2 3 cds o po indices e mp array i
300. set 302 Python Scientific lecture notes Release 2013 1 An example of reshaping data the digits dataset SN OW BP WN KF CO 012 3 4 5 6 7 The digits dataset consists of 1797 images where each one is an 8x8 pixel image representing a hand written digit digits datasets load_digits gt gt gt digits images shape LOT See o gt gt gt import pylab as pl gt gt gt pimnenowidigsbssameoes IJ cmap ol cm gray_r lt matplotlib image AxesImage object at gt To use this dataset with the scikit we transform each 8x8 image into a vector of length 64 gt gt gt data digits images reshape digits images shape 0 1 17 1 1 Learning and Predicting Now that we ve got some data we would like to learn from it and predict on new one In scikit learn we learn from existing data by creating an estimator and calling its fit X Y method gt gt gt from sklearn import svm gt gt gt clf svm LinearsSvVvCc gt gt Cli strc aris data iris tarcrget 7 learn from the data EON 0d Once we have learned from the data we can use our model to predict the most likely outcome on unseen data gt gt gt clf predict 5 0 3 6 1 3 0 25 parra TOI di eame Note We can access the parameters of the model via its attributes ending with an underscore gt gt gt CLE COGE array peccemus b 17 2 Classification 17 2 1 k Nearest neighbors classifier The simple
301. sis sn 17 5 Putting it all together face recognition us ox mox ko xox 9o Ee 9 9 xx S SHO SHE ES 17 6 Linear model from regression to sparsity lt s oy 09 koc 9 xw 9 9 RES xm FOX ES 17 7 Model selection choosing estimators and their parameters ls 18 Interfacing with C lo Inroddu non 35x x X9 53 tte Eo9ORE Xo 3 Re Ee CREE SEE HOKE DG A X X 9s 18 2 _Python C APi wee be bebe EO the EORUM PR b AUR ROBUR NUR Je EUR EO ERE SEES L5 CIVBER song 9982 Bae bd REOR O14 OP P 9o was ee Se Gee eve POE Gre 5 d ours oA SAIG esepta keepere e aa a a a e a a a n 18 9 LVO 2 23 16x ee he eee e ESEE ISG UMNO S eee ea Re hE Oe Ee EE EOE Bes Bee ee ee ee 18 7 Further Reading and References e s s s ro x 6 eb SHS OX Goc due OE OH X Ro RE OS L5 EONO 2 20909 ee ee eee eA ee eR EAS KOR Eee EES Index 287 287 293 294 295 296 297 298 299 301 302 303 306 307 308 310 311 312 312 313 317 320 324 328 328 329 331 Python Scientific lecture notes Release 2013 1 Contents 1 Part I Getting started with Python for science 1 1 CHAPTER 1 Scientific computing with tools and workflow authors Fernando Perez Emmanuelle Gouillart Ga l Varoquaux Valentin Haenel Why Python 1 1 1 The scientists needs Get data simulation experiment control Manipulate and process data Visualize results to understand what we are doing Communicate results produ
302. sition gt gt gt samoles ALa CBETA 1 0X Ceara dq Cu qute aps ARA S708 Ara DD gt gt gt samples aren UNES AEA 2 d 250594557 CBETA S sei Ode lt 7 TAU l ADRAC Ce Eos unoque quB xu Ibm Ce DAUM a all dtype sensor code S94 position p sro sr JO em soU faa lue eere Field access works by indexing with field names gt gt gt samples sensor code Array AERA BAM FA iA Sm AP fie P que dtype S4 gt gt gt samples value casts civ One iy Ore skh Dd Ooh Hedge Qd sq gt gt gt samples 0 ATEAN GLO 3632 gt gt gt samples sensor code TAU gt gt gt samples CTAUT Multiple fields at once gt gt gt seamples lposrtion gt value array T adus o Lexus Uoc EE 3002053 Ghee Uses ieu Ohl eee VOL rs diype I position not x samet ms Fancy indexing works as usual gt gt gt samples samples sensor code ALFA array MALPA TES NO be CORREA S SO Us b deype sensor code t54 position p 1 lt f8 y value lt re Note There are a bunch of other syntaxes for constructing structured arrays see here and here 3 3 3 maskedarray dealing with propagation of missing data For floats one could use NaN s but masks work for all types po s oaonpomaessrresyV ll 22 21 gt gt gt x maskedvarray data e 1 3 mask False True False True
303. smacshow norsy lenalout emapspl somogray 56 57 denoised lena iterated wiener noisy lena 58 pl matshow denoised lena cut cmap pl cm gray 59 home esc physique cuso python 2013 scipy lecture notes advanced debugging wiener fillfering py i 38 res noisy img denoised img 39 noise rese 7 2sim tes ci eo gt 40 moise level 1 noise l var AI noise level noise level 0 0 42 denoised img noise levelxres FloatingPointError divide by zero encountered in divide Other ways of starting a debugger Raising an exception as a poor man break point If you find it tedious to note the line number to set a break point you can simply raise an exception at the point that you want to inspect and use IPython s debug Note that in this case you cannot step or continue the execution Debugging test failures using nosetests You can run nosetests pdb to drop in post mortem debugging on exceptions and nosetests pdb failure to inspect test failures using the debugger In addition you can use the IPython interface for the debugger in nose by installing the nose plugin ipdb plugin You can than pass ipdb and ipdb failure options to nosetests Calling the debugger explicitly Insert the following line where you want to drop in the debugger import pdb pdb set trace Warning When running nosetests the output is captured and thus it seems that the debugger does not work Simply run the nos
304. solution See Also 3D plotting with Mayavi page 287 4 4 12 Text 2 ECT 252 uc U alt mc HBV Myre ERE a a ay ic Tm VOM ES o U5 ta days ero EC Ny mE Oa Fo Gana dr r 1 M Mg e Fo Go l T p din X T 2 2 4 22 E TnhC y mgo C r p lt T Hpo Nac Vp HN pg ha Z2 Wn WAT d stad vz dt zc Y Ta Hint Have a look at the matplotlib logo Try to do the same from scratch Click on figure for solution 4 5 Beyond this tutorial Matplotlib benefits from extensive documentation as well as a large community of users and developpers Here are some links of interest 4 5 1 Tutorials Pyplot tutorial ntroduction Controlling line properties Working with multiple figures and axes Working with text mage tutorial e Startup commands Importing image data into Numpy arrays e Plotting numpy arrays as images 4 5 Beyond this tutorial 98 Python Scientific lecture notes Release 2013 1 e Text tutorial Text introduction Basic text commands Text properties and layout Writing mathematical expressions Text rendering With LaTeX Annotating text Artist tutorial ntroduction Customizing your objects Object containers Figure container Axes container Axis containers Tick containers e Path tutorial Introduction e B zier example Compound paths e Transforms tutorial Introduction Data coordinates e Axes coord
305. src utbs Usete cbutus Srey natos sers cburns local lib python2 5 site packages jusr local lib python2 5 site packages Library Frameworks Python framework Versions 2 5 lib python2 5 In LL6 osodgetenv PYDLIHONPATS 2 7 Standard Library 36 Python Scientific lecture notes Release 2013 1 pour Wel 7 Wears cCoirnac sre utiile lsers courns srec7nitools 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 2 7 2 shutil high level file operations The shutil provides useful file operations shutil rmtree Recursively delete a directory tree e shutil move Recursively move a file or directory to another location shutil copy Copy files or directories 2 7 3 glob Pattern matching on files The glob module provides convenient file pattern matching Find all files ending in t xt In 18 import glob In 19 Gtobglbobt stoto Durs np ody ecu pb5se vp tnewrqgbesuebpt 2 7 4 sys module system specific information System specific information related to the Python interpreter Which version of python are you running and where is it installed In 117 SvsopleticolN One ial qme verum In 118 sys version Ont ele tob q rcb2cecD0p II wea 22 0052 07a 5b Na GCC 420 1 Apple Computer lnc build S363 In 119 sSysipretix Out 119 Library Frameworks Python framework
306. st possible classifier is the nearest neighbor given a new observation take the label of the training samples closest to it in n dimensional space where n is the number of features in each sample 17 2 Classification 303 Python Scientific lecture notes Release 2013 1 Sepal width Sepal length 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 gt gt gt Create and fit a nearest neighbor classifier gt gt gt from sklearn import neighbors gt gt gt knn neighbors KNeighborsClassifier gt gt gt bon rat urasccderde sess eargek KNerxghborsClassqrTrer x s oo enn pres esu ud quem x so res array NBN Training set and testing set 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 gt gt gt perm np random permutation iris target size gt gt gt iris data iris data perm gt gt gt iris target iris target perm gt gt gt kon Freirig data 100 aree s fee incre qe dO KNeighborsClassifier soo kon C Ore irio data l0 T suawssbardgebvpJ e DESC Bonus question why did we use a random permutation 17 2 2 Support vector machines SVMs for classification Linear Supp
307. steps 0 iM input 2 steps output steps 2 8 3 Interoperability features 8 3 1 Sharing multidimensional typed data 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 3 but would not like to have Numpy as a dependency Currently 3 solutions 1 the old buffer interface 2 the array interface 3 the new buffer interface PEP 3118 8 3 2 The old buffer protocol Only 1 D buffers No data type information C level interface PyBufferProcs tp as buffer in the type object But it s integrated into Python e g strings support it Mini exercise using PIL Python Imaging Library See Also 8 3 Interoperability features 183 Python Scientific lecture notes Release 2013 1 pilbuffer py gt gt gt import Image gt gt gt data np zeros 200 200 4 dtype 2np int89 gt gt gt dabeles sl 1255 0 0 255 s Red gt gt gt In PIL RGBA images consist of 32 bit integers whose bytes are RR GG BB AA gt gt gt data data view np int32 squeeze gt gt gt img e mageecremburtcer RGBA 200 200 data gt gt gt img save test png Q Check what happens if data is now modified and img saved again 8 3 3 The old buffer protocol import numpy as np import Image Let s make a sample image RGBA format x np zeros 200 200 4 dt
308. t Finally two more technical possibilities are useful as well n 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 3 import numpy as np 4 psearch np diag diag dra tat Gon l e numpy lookfor looks for keywords inside the docstrings of specified modules in 45 mnumpy lockror convolution Search results for convolution nu mpyconmvodlwe Returns the discrete linear convolution of two one dimensional sequences wame panre ie mE Return the Bartlett window numpy correlate Discrete linear correlation of two l dimensional sequences In 46 numpy lookfor remove module os Search results for remove os remove remove path removedirs removedirs path a ENEL E rmdir patch wL Lak unlink path walk Directory tree generator f everything listed above fails and Google doesn t have the answer don t despair Write to the mailing list 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 Numpy discussion numpy discussion scipy org all about numpy arrays manipulating them in dexation questions etc 141 Python Scientific lecture notes Release 2013 1 SciPy Users List scipy user scipy org sci
309. t gt x flag leastsq residuals x0 args waveform 1 t gt gt gt print x D 42290530334 27762020742 ESAE OD dS 250505062 7 9 And visualize the solution 5 11 Summary exercises on scientific computing 132 Python Scientific lecture notes Release 2013 1 cgo meu Ware Borin die ee exe tS Ere gt gt gt plt legend waveform model gt gt gt plt show 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 don t need to define the residuals any more Going further Try with a more complex waveform for instance data waveform 2 npy that contains three signif icant peaks You must adapt the model which is now a sum of Gaussian functions instead of only one Gaussian peak Intensity bins 0 10 20 30 AQ 50 60 70 80 Time ns n some cases writing an explicit function to compute the Jacobian is faster than letting 1eastsq esti mate 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 so
310. t im ndimage rotate im 15 mode constant gt gt gt im ndimage gaussian_filter im 8 Use a gradient operator Sobel to find high intensity variations gt gt gt sx ndimage sobel im axis 0 mode constant gt gt gt Sy ndimage sobel im axis 1 mode constant gt gt gt sob np hypot sx sy square Sobel x direction Sobel filter Sobel for noisy image gt gt gt from skimage filter import canny gt gt gt im t O l1 np random random im shape gt gt gt edges gt gt gt edges Canny filter canny im 1l 02 45 0 2 mot enough smoothing canny im 3 0 3 0 2 better parameters Several parameters need to be adjusted risk of overfitting 12 5 2 Segmentation Histogram based segmentation no spatial information gt gt gt n 10 gt gt gt 1 256 gt gt gt im np zeros l 1 gt gt gt np random seed 1 gt gt gt points lanpt randoms random 2 ti Z po ami poimes 0 aastype np une posmesqwiyseescvpe npin e gt gt gt im ndimage gaussian_filter im sigma 1 4 n gt gt gt mask im gt im mean astype np float gt gt gt mask 0 1 im gt gt img mask O 24ne random randn mask shape gt gt gt hist bin_edges np histogram img bins 60 gt gt gt bin centers 0 5 bin_edges 1 bin_edges 1 gt gt gt Dinary img img DES 12 5 Feature extraction 243 Automatic t
311. t strrdes maeaxaxrts 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 gids ule jo 0052090 dg imn call runctriom Frame 0x85371ec for file home varoquau usr lib python2 6 site packages numpy core arrayprin at x bs hon cexeluc 3750 BE VPython cevalvce No such file or directory 10 2 Pvthon cewvalsc gdb up 9 PyEval EvalFrameEx f Frame 0x85371ec for file home varoquau usr lib python2 6 site packages numpy core arrayprin at ss PytChon cevale C 2412 2121115 im s Pyenon ceval ic 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 odio up 34 0x080dc97a in PyEval EvalFrameEx f Frame 0x82f064c for file segfault py line 11 in print big array small array numpy ndarra 1630 lt el Python ceval c No such tile or directory in 2 Pyvthom eeved e gdb pyframe Sec aule 12 print bDig array The corresponding code is 9 4 Debugging segmentation faults using gdb 202 Python Scientific lecture notes Release 2013 1 def make big array small array big array
312. t copy or alter the memory block only changes the dtype and adjusts array shape gt gt gt x 1 5 gt gt gt y array 2o ss dtype int2 gt gt y Dase is x True Mini exercise data re interpretation See Also view colors py You have RGBA data in an array gt gt gt x np zeros 10 10 4 dtype np int8 gt gt gt Soles es gt gt gt Sly 1 2 gt gt gt Sols is 21 3 gt gt gt x 3 4 where the last three dimensions are the R B and G and alpha channels How to make a 10 10 structured array with field names r g b a without copying data SoS CIA gt gt gt assert y r l allqt gt gt gt assert y g 2 all gt gt gt assert y b 3 all gt gt gt assert y a 4 all Solution Doc ero vsew Eu ep ro marr dE o Cup SEIT Ua ars E355 lee eM 8 1 Life of ndarray 167 Python Scientific lecture notes Release 2013 1 Warning Another array taking exactly 4 bytes of memory gt gt gt y np array 1 3 2 4 dtype np uint8 transpose gt gt gt X y copy gt gt gt X arcay iil 2l 3 4 dtype uint8 gt gt gt y EQ liye 2 3 4 dtype uint8 gt gt gt X view np intl6 arra 5 9 5 10271 Gt zoe urb 1G gt gt gt 0530207 95502505 ols 02 7 gt gt gt y view np intl6 array LI 769 1026 dts esum What happened We need to lo
313. t matploclibtext Text object at 22 gt gt gt plt ylabel memory MB matplotlib uext Text ODJECE at 2 22 11 1 2 Sparse Matrices vs Sparse Matrix Storage Schemes sparse matrix is a matrix which is almost empty storing all the zeros is wasteful gt store only nonzero items think compression pros huge memory savings 212 Python Scientific lecture notes Release 2013 1 cons depends on actual storage scheme usually does not hold 11 1 3 Typical Applications solution of partial differential equations PDEs the finite element method mechanical engineering electrotechnics physics graph theory nonzero at i jJ means that node i is connected to node j 11 1 4 Prerequisites recent versions of e numpy SCipy e matplotlib optional ipython the enhancements come handy 11 1 5 Sparsity Structure Visualization e Spy frommatplotlib example plots 11 1 Introduction 213 Python Scientific lecture notes Release 2013 1 11 2 Storage Schemes seven sparse matrix types in scipy sparse 1 csc matrix Compressed Sparse Column format csr matrix Compressed Sparse Row format bsr matrix Block Sparse Row format dok matrix Dictionary of Keys format 2 3 4 lil matrix List of Lists format 5 6 coo_matrix COOrdinate format aka IJV triplet format 7 dia matrix DIAgonal format each suitable for some tasks many empl
314. t simulation at discrete time steps signal recorded by a measurement device e g sound wave pixels of an image grey level or colour 3 D data measured at different X Y Z positions e g MRI scan Why it is useful Memory efficient container that provides fast numerical operations In 1 L range 1000 In Ale seamen 34992 zos 1 xn Lb 1000 loops best of 3 403 us per loop In 3 a np arange 1000 In 4 timeit axx2 100000 loops best of 3 12 7 ts per loop 3 1 2 Reference documentation e On the web http docs scipy org e Interactive help gt gt gt help np artay Help on built in function array 1m module numoy core multi varray array soo array object dtype None copy True order None subok False In 5 np array OUT o Form Dart in PIE Vom array DOGS eine array object dtype None copy True order None subok False ndmin 0 Looking for something gt gt gt np lookfor create array Search results for create array MUNDY array Create an e qc numpy memmap Create a memory map to an array stored in a x binary file on disk In 6 np cons No Conical eniaks ye Om np conjugate Mp convo lve 3 1 The numpy array object 43 Python Scientific lecture notes Release 2013 1 el 3 1 3 Creating arrays e 1 D gt gt gt 2 np arrayt 0 gt gt gt a array 10 1l 27 34 gt gt gt a ndim 1 gt
315. t values but now you can interactively play with the values to explore their affect see Line properties page 101 and Line styles page 102 below import pylab as pl import numpy as np 4 2 Simple plot 84 Python Scientific lecture notes Release 2013 1 Create a figure of size 8x6 points 80 dots per inch pistrgure firigsezo 97 6 dpi e0 Create a new subplot from a grid of 1x1 plosubbdcok d E i np linspace np pi np pi 256 endpoint True X cy Hp cOos X mpesecmox Plot cosine with a blue continuous line of width 1 pixels elAplor x c color blue Sew nues le Plot sine with a green continuous line of width 1 pixels plp or Or S collor Green Sedis 0 Winestyle fee oo P IIS plexdim 4 0 42 0 See x LICKS pl xticks np linspace 4 4 9 endpoint True Set y limits eles AiO 10 Set y ticks Plsvyeteks Mp lanspace 1 ly 5 8nmdpounu True Save figure using 72 dots per inch savefig exercice 2 png dpi 72 7 Show reste Om Screen pl show 4 2 3 Changing colors and line widths 0 5 Hint Documentation e 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 We ll also slightly alter the figure size to make it more horizontal pl figure figsize 10 6 dpi 80 pleplomwOe GC coleor gives Mimewweleh 7 quu Em p
316. tem Solvers 229 Python Scientific lecture notes Release 2013 1 examples pyamg with lobpcg py example by Nils Wagner examples lobpcg sakurai py output python examples lobpcg sakurai py Results by LOBPCG for n 2500 39 20 5 2 5 90 5 3 006250022 G206250007 Exact eigenvalues 918 X010 IESUS 225 007 0 06250044 Elapsed time 7 01 Eigenvalue distribution 1012 10H 1901 10 10 10 10 lt 10 10 10 10 10 10 101 E amp Bheehke 10 10 10 10 10 Number 11 4 Other Interesting Packages PyYAMG algebraic multigrid solvers http code google com p pyamg Pysparse own sparse matrix classes matrix and eigenvalue problem solvers 11 4 Other Interesting Packages 10 230 Python Scientific lecture notes Release 2013 1 http pysparse sourceforge net 11 4 Other Interesting Packages 231 CHAPTER 12 Image manipulation and processing using Numpy and Scipy authors Emmanuelle Gouillart Ga l Varoquaux Image 2 D numerical array or 3 D CT MRI 2D time 4 D Here image Numpy array np array Tools used in this tutorial numpy basic array manipulation e scipy scipy ndimage submodule dedicated to image processing n dimensional images See http docs scipy org doc scipy reference tutorial ndimage html gt gt gt from scipy import ndimage e afew examples use specialized toolkits working wit
317. ter covers the following techniques Python C Api e Ctypes e SWIG Simplified Wrapper and Interface Generator e Cython 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 s the code autogenerated 312 Python Scientific lecture notes Release 2013 1 Does it need to be compiled s there good support for interacting with Numpy arrays Does it support C Before you set out you should consider your use case When interfacing with native code there are usually two use cases that come up Existing code in C C that needs to be leveraged either because it already exists or because it is faster Python code too slow push inner loops to native code 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 dem
318. tific lecture notes Release 2013 1 Section contents More data types page 73 e Structured data types page 74 e maskedarray dealing with propagation of missing data page 75 3 3 1 More data types Casting Bigger type wins in mixed type operations gt gt gt np arcay lly eme durs qu 5 E NEU 215 Assignment never changes the type gt gt gt aA np array I 2 3 gt gt gt a dtype dtype int64 gt gt gt a 0 1 9 lt float is truncated to integer gt gt gt a arra i 2 31 Forced casts gt gt gt a mnp array lay lazy 91 gt gt gt b a astype int lt truncates to integer gt gt gt b SEGUE aun TD Rounding gt gt gt cnc mnp array da videos 5 358935 gt gt gt b np around a gt gt gt b p ali gg oLtrmng posmt array i dug Zaye Wage hy 4 4 gt gt gt c np around a astype int gt gt gt C array Ilr 2 2 2 4 pN Different data type sizes Integers signed 32 bits same as int on 32 bit platform 64 bits same as int on 64 bit platform gt gt gt np array 1 dtype int dtype dtype intoa 2o Dao OiP INE 32 Maxy 24A do e uo SE gt gt gt pyppcOTotnp rneod omg 299 3 22 9 9709 59 m SD 222631 203685477 eS Unsigned integers 3 3 More elaborate arrays 73 Python Scientific lecture notes Release 2013 1 BOO XI E qns o DICIT A Nico Ze k 42949672957 4294967295
319. timizations such as bounds checking are supported Look at the corresponding section in the Cython documentation In case you want to pass Numpy arrays as C arrays to your Cython wrapped C functions there is a section about this in the Cython wiki In the following example we will show how to wrap the familiar cos_ doubles function using Cython void cos_doubles double in array double out array int size Fine ude mee Compute the cosine of each element in in array storing the result in s out_array void cos_doubles double in array double out array int size int 1 for i Or size 07 3 1 ou ut arrayvyl i cos in arraylil This is wrapped as cos_doubles_func using the following Cython code CHR Example OL WwIJDDULDI arC rUn CI n Chat Cokes Coube arrays wes InpuL Sg che Numpy declarations Trom Cyehnom THR import both numpy and the Cython declarations for numpy import numpy as np cimport numpy as np if you want to use the Numpy C API from Cython not strictly necessary for this example Toe YOO sque HA Ah D cdefine the signature of our c function cdef extern from cos doubles h void Cos doubles double in array double out array INC size create the wrapper code with numpy type annotations def cos doubles func np ndarray double ndim 1 mode c in array not None np ndarray double ndim 1 mode c out array not None COs doubles doubler npr yrr y DATA InN array lt
320. ting the module gives access to its objects using the module object syntax Don t forget to put the module s name before the object s name otherwise Python won t recognize the instruction Introspection In 4 demo Iype module Base Class type module Seance SEATS module demo from demo py gt Namespace Interactive File home varoquau Projects Python talks scipy 2009 tutorial source demo py DOGS 7m A demo module In 5 who demo In 6 whos Variable Type Data Info 2 5 Reusing code scripts and modules 28 Python Scientific lecture notes Release 2013 1 demo module lt module demo from Clemo py In 7 dir demo Out AS Peoh ES E OCEN no Eile 2 T name_ _package_ rol ear premo Iu In 8 demo demo builtins demo init demo str demo class demo name demo ssubeldsshook demo delattr demo new demo c demos diet demo package demo d demo doc demo reduce demo print a demo file demo reduce ex demo print b demo format demo repr demo py demo getattribute demo setattr demo pyc demo hash demo sizeof Importing objects from modules into the main namespace In 9 from demo import print a print b In 10 whos Weir Ineo ike Data Info module module demos from Ceno oy ToC Te dom lt PUMet LOM print a ut Uxb 421594 function lt function print b at 0xb74214c4 In il or nt a
321. tlib pyplot as plt gt gt gt plt iimread tname png See also e Load text files numpy loadtxt numpy savetxt e Clever loading of text csv files numpy genfromtxt numpy recfromcsv e Fast and efficient but numpy specific binary format numpy save numpy load 5 2 Special functions scipy special Special functions are transcendental functions The docstring of the scipy special module is well written so we won t list all functions here Frequently used ones are 5 1 File input output scipy io 105 Python Scientific lecture notes Release 2013 1 Bessel function such as scipy special jn nth integer order Bessel function Elliptic function scipy special ellipj for the Jacobian elliptic function Gamma function scipy special gamma also note scipy special gammaln which will give the log of Gamma to a higher numerical precision Erf the area under a Gaussian curve scipy special erf 5 3 Linear algebra operations scipy linalg The scipy linalg module provides standard linear algebra operations relying on an underlying efficient implementation BLAS LAPACK 5 3 The scipy linalg det function computes the determinant of a square matrix gt gt gt from scipy import linalg aoe are e Heverray i ils 205 E o D gt gt gt linalg det arr 2 2 0 po arr npoearrtey Db3 2 Ss eo An gt gt gt linalg det arr O20 gt gt gt linalo dew np ones 3 4
322. tor doing decoration abc sso EVNET LOA L 12 inside wrapper 11 127 1 Lases runccion wis 12 4a 14 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 doesn t 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 it s enough to discuss class based decorators where arguments are given in the decorator expression and the decorator ___init__ method is used for decorator construction gt gt gt class decorator class object def init__ self arg this method is called in the decorator expression print in decorator Init p arg self arg arg def call self function this method is called to do the job Prine in decorator call selicverc ee return function gt gt gt deco instance decorator _class foo in seeCoracer inie soo gt
323. ttr fe seer _ f oS32zeof r delitem r le RR E om r delslice __ ry len re subelasshook_ be COG _ Pose lec r append r etu E Ed E a COUNT i Ora Pe Ne r extend r ge r new __ r index r getattribute r reduce r insert r getitem r reduce ex Tu pop r etslrToe r repr r remove doe cue ecu r reversed r reverse ie hasn Ex cms B c Strings Different string syntaxes simple double or triple quotes S Hello how are you S c Hi what s up Hello tripling the quotes allows the rr how are you the string to span more than one line 2 2 Basic types 14 Python Scientific lecture notes Release 2013 1 g Hi wnat s ip in I hi what s up Pile lt ipython console line 1 pay what s up VN SYVMeaxELrOr ovale ss The newline character is n and the tab character is t Strings are collections like lists Hence they can be indexed and sliced using the same syntax and rules Indexing gt gt gt a hello gt gt gt a 0 eG gt gt gt a 1 a ao ccu noy Remember that negative indices correspond to counting from the right end Slicing gt gt gt a hello world gt gt gt a 3 6 3rd to 6th excluded elements elements 3 4 5 D gt gt gt da 221022 7 Syntax a start stop step ao mee d gt gt gt a 3 every three characters from beginning to end qub etu Accents and special ch
324. ttribute offset for each diagonal is the main diagonal negative offset 2 below positive offset above fast matrix vector sparsetools fast and easy item wise operations manipulate data array directly fast NumPy machinery constructor accepts dense matrix array sparse matrix shape tuple create empty matrix data offsets tuple no slicing no individual item access 11 2 Storage Schemes 215 Python Scientific lecture notes Release 2013 1 use rather specialized solving PDEs by finite differences with an iterative solver Examples e create some DIA matrices gt gt gt data no varray b 2 3 4 l repeat 3 axis 0 gt gt gt data drray l 2 32 4 pales ee oos Vau sr y y Sy gt gt gt offsets npoeerrayti0y 1 2 gt gt gt mtx sparse dia_matrix data offsets shape 4 4 gt gt gt mtx lt 4x4 sparse matrix of type type numpy into4 with 9 stored elements 3 diagonals in DIAgonal format gt gt gt mtx todense meie pa sects le AO Ss e doe ore E A ee Dos wae ss pd LO Oy 3 41 gt gt gt data np arange 12 reshape 3 4 1 gt gt gt data curas e 2 see All i 2 T 7 8 Lr LO dia Taa gt gt gt mtx sparse dia_matrix data offsets shape 4 4 gt gt gt mtx data array P or Sy 4 esr Gv Ou Sly E o EDS Seb bos gt gt gt mtx offsets array d Sie uium o gt gt
325. tty 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 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 functools update wrapper wrapper wrapped Update a wrapper function to look like the wrapped function gt gt gt import functools gt gt gt def better replacing decorator with args arg print defining the decorator def decorator function Princ doing dgecordcromn def _wrapper xargs print inside wrapper return ftunction a args 7 2 Decorators arg xxkwargs args kwargs kwargs 152 Python Scientific lecture notes Release 2013 1 return functools update wrapper wrapper function return decorator gt gt gt d better replacing decorator with args abc def fun
326. twise func npy cdouble x inl npy cdouble xin2 npy_cdoublex out e Only elementwise func needs to be supplied e except when your elementwise function is not in one of the above forms 8 2 Universal functions 175 Python Scientific lecture notes Release 2013 1 8 2 2 Exercise building an ufunc from scratch The Mandelbrot fractal is defined by the iteration ze z5 4c where c x ty 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 e Make ufunc called mandel z0 c that computes z z0 for k in range iterations LZ Ae r C say 100 iterations or until z real 2 z imag 2 gt 1000 Use it to determine which c are in the Mandelbrot set e Our function is a simple one so make use of the PyUFunc x helpers Write it in Cython See Also mandel pyx mandelplot py Fix the parts marked by TODO Compile this tile by Cython 0 12 required because or the complex vars cython mandel pyx o hon Setup p Pull e c 7 eel try IE Ole viti an thls eia DOO o gt gt gt import mandel gt gt gt mandel mandel 0 1 2j The elementwise function cdef void mandel single point double complex sz in double complex xc in double complex 2 cout nogi The Mandelbrot iteration Some points of note tp Ss NOU allowed to call any FPython functio
327. u if you have installed one of these scientific Python suites If you don t 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 gt gt gt print Hello world Hello world 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 gt gt gt a 3 gt gt gt b 2a gt gt gt type b type int gt gt gt print b 6 gt gt gt axb 18 gt gt gt b hello gt gt gt type bd lt Ly De Str gt Dom w 35 hellohello gt gt gt 2xb hellohello 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 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 he 110 Operations on integers b 2 xa are coded nativel
328. uce the graphic on the right taking care of marker size color and transparency n 1024 xX Hoe rancdomsnormal 0 tm Y npr tandem normal 0 1 pl scatter X Y n Click on figure for solution 4 4 Other Types of Plots examples and exercises 93 Python Scientific lecture notes Release 2013 1 4 4 3 Bar Plots 0 51 0 49 0 44 Hint You need to take care of text alignment Starting from the code below try to reproduce the graphic on the right by adding labels for red bars n 12 np arange n arc LEE c Seas c o e TRI I COP RIED 21 OX Oy l x 7 ftloat m Se orte cler Uni orm O D 1 0 pl bar X Yl cacecolor i49999tff edgecolor white pl bar X Y2 tfacecolor ttf9999 edgecolor white Lor o y i z2zIip X e pliztextq x qub ve 0205 ha center va bottom aly nmi 7e a ees Click on figure for solution 4 4 4 Contour Plots Hint You need to use the clabel command Starting from the code below try to reproduce the graphic on the right taking care of the colormap see Colormaps page 102 below def f x y return 0 2 c ue me exp ucc c 256 np linspace 3 Nps Linspace 3 Y np meshgrid x 4 4 Other Types of Plots examples and exercises 94 Python Scientific lecture notes Release 2013 1 pl contouri x Y E x XU Sv dlpha l3 cmap Jec C plocontourtXxe My Pe Vj 8 Golors black Tineaewrdth
329. uedo pc ccena cines lcd are M 4 2 Simple plot 85 Python Scientific lecture notes Release 2013 1 4 2 4 Setting limits Hint Documentation e 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 One clic emat oo ee ID ep EXT XQ puts voeem e comas bacis NER 4 2 5 Setting ticks 3 142 1 571 0 000 1 571 3 142 Hint Documentation e xticks command e yticks command e Tick container e Tick locating and formatting Current ticks are not ideal because they do not show the interesting values 7 7 2 for sine and cosine We ll change them such that they show only these values ied cuc these cci ee Woomera On Om a OR TN picos sin Python Scientific lecture notes Release 2013 1 4 2 6 Setting tick labels Hint Documentation Working with text e xticks command yticks command e set xticklabels e set yticklabels Ticks are now properly placed but their label is not very explicit We could guess that 3 142 is 7 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 we ll use latex to allow for nice rendering of the label cles seme cedo Oils Sion Oly O Fino jo Zoom io BI ee te ee Ico xdg DI u c UD pulos des desee 0 Sy x 5 l18t BUS
330. ugh the error message is not quite as helpful since it does not tell us what the type should be ArgumentError Traceback most recent call last ipython input 7 11bee483665d in module zo cod COs Module cos unc 7 too 18 3 Ctypes 318 Python Scientific lecture notes Release 2013 1 home esc git working scipy lecture notes advanced interfacing with c ctypes cos module py in cos 12 der cos rune auo Lo eS Wrapper ror COs Crom mating he lt 14 return libm cos arg ArgumentError argument 1 type exceptions TypeError wrong type 18 3 2 Numpy Support Numpy contains some support for interfacing with ctypes In particular there is support for exporting certain attributes of a Numpy array as ctypes data types and there are functions to convert from C arrays to Numpy arrays and back 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 let s 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 The function implementation resides in the following C source file Fine ma
331. uired in the exit phase it is released and the exception if thrown is propagated As with files there s 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 all file like objects file automatically closed fileinput tempfile py gt 3 2 bz2 BZ2File gzip GzipFile tarfile TarFile zipfile ZipFile ftplib nntplib close connection py gt 3 2 or 3 3 e locks multiprocessing RLock lock and unlock multiprocessing Semaphore memoryview automatically release py gt 3 2 and 2 7 decimal localcontext modify precision of computations temporarily e winreg PyHKEY open and close hive key e warnings catch warnings kill warnings temporarily e contextlib closing the same as the example above call close parallel programming concurrent futures ThreadPoolExecutor invoke in parallel then kill thread pool py gt 3 2 concurrent futures ProcessPoolExecutor invoke in parallel then kill process pool py gt 3 2 nogil solve the GIL problem temporarily cython only 7 3 1 Catching exceptions When an exception is thrown in the with block it is passed as arguments to__ ex it__ 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 T
332. ut 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
333. ver 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 1s 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 gt gt gt f open etc fstab gt gt gt f is fL _iter_ True The file is an iterator itself and it s iter method doesn t create a separate object only a single thread of sequential access is allowed 7 1 Iterators generator expressions and generators 145 Python Scientific lecture notes Release 2013 1 7 1 2 Generator expressions A second way in which iterator objects are created is through generator expressions the basis for list compre hensions 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 geta list gt gt gt i for i in nums lt generator object lt genexpr gt at 0x gt gt gt gt 1 for i in nums Duos 2a gt gt gt list 1 for 3 ain nums dey 2 X In Python 2 7 and 3 x the list comprehension syntax was extended to dictionary and set
334. voiding bugs 9 1 1 Coding best practices to avoid getting in trouble 193 Python Scientific lecture notes Release 2013 1 Brian Kernighan Everyone knows that debugging is twice as hard as writing a program in the first place So if you re as clever as you can be when you write it how will you ever debug it We all write buggy code Accept it Deal with it Write your code with testing and debugging in mind Keep It Simple Stupid KISS What is the simplest thing that could possibly work Don t Repeat Yourself DRY Every piece of knowledge must have a single unambiguous authoritative representation within a system Constants algorithms etc Try to limit interdependencies of your code Loose Coupling Give your variables functions and modules meaningful names not mathematics names 9 1 2 pyflakes fast static analysis They are several static analysis tools in Python to name a few pylint pychecker pyflakes peps e flake8 Here we focus on pyflakes which is the simplest tool Fast simple Detects syntax errors missing imports typos on names Another good recommendation is the f 1ake8 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 PEPS style guide Integrating pyflakes or flake8 in your editor or IDE is highly recommended it does yield productivity
335. when there s nothing to return raises the StopIteration exception An iterator object allows to loop just once It holds the state position of a single iteration or from the other side each loop over a sequence requires a single iterator object This means that we can iterate over the same sequence more than once concurrently Separating the iteration logic from the sequence allows us to have more than one way of iteration Calling the iter __ method on a container to create an iterator object is the most straightforward way to get hold of an iterator The iter function does that for us saving a few keystrokes gt gt gt nums 1 2 3 note that varies these are different objects gt gt gt iter nums lt IvStaterator obqect aC ssa 2 numse iter lt listit erator Object at mes gt gt gt nums _ reversed_ lt listreverseiterator object at gt gt gt gt it iter nums gt gt gt next it next obj simply calls obj next 1 gt gt gt it next z gt NeXT 10 2 gt gt gt next it Traceback most recent call last EeLle lt sedin mue 1 in mocule gt Stoplteration When used in a loop St op Iteration 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 o
336. xes are tuples of integers gt gt gt a np diag np arange 3 gt gt gt a array 7o 0 01 gu dis Oth Dis Or al oec scr DIEI I gt gt gt alZ ll 10 7 third line second column gt gt gt a arbay 0 OF Ol or e Ol BOG dO 2A gt gt gt all array 10 1 307 Note that n 2D the first dimension corresponds to rows the second to columns e for multidimensional a a O is interpreted by taking all elements in the unspecified dimensions Slicing Arrays like other Python sequences can also be sliced gt gt gt a np arange 10 oo SS dup don en oo SH dou TO dee Sp gt gt gt a 2 9 3 start end step xm D el Note that the last index is not included gt gt gt a 4 annar D 1 27 31 All three slice components are not required by default start is 0 end is the last and step is 1 gt gt gt rds n E Z gt gt gt als 2 a Zp E UO SO gt gt gt cse arra Le 42 OS secus S 3 1 The numpy array object 49 Python Scientific lecture notes Release 2013 1 A small illustrated summary of Numpy indexing and slicing gt gt gt a 0 3 5 array 3 4 gt gt gt a 4 4 array 44 45 54 55 gt gt gt a 2 array 2 12 22 32 42 52 gt gt gt a 2 2 2 array 20 22 24 40 42 44 3 1 7 Copies and views A slicing operation creates a view on the original array which is just a way of accessing array data Thus th
337. xpython org or PyQt http www riverbankcomputing co uk software pyqt tro Numpy and Scipy http www scipy org Enthought Tool Suite 3 x or higher http code enthought com projects Al required software can be obtained by installing the EPD http www enthought com products epd php Tutorial content e Introduction page 269 Example page 269 e What are Traits page 270 nitialisation page 271 Validation page 271 Documentation page 272 Visualisation page 273 Deferral page 274 Notification page 279 Some more advanced traits page 282 References page 285 268 Python Scientific lecture notes Release 2013 1 14 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 The main packages are e Traits component based approach to build our applications Kiva 2D primitives supporting path based rendering affine transforms alpha blending and more Enable object based 2D drawing canvas Chaco plotting toolkit for building complex interactive 2D plots Mayavi 3D visualization of scientific data based on VTK Envisage application plugin framework for building scriptable and extensible applications Mayavi TVTK VTK Traits Chaco Enable Kiva La aes ri ird
338. y gt gt gt DN gt gt gt a arra 99 ale 2 oe 4 9s 6 p on Ou du d dS Ana jae We 1 MV 2G Loy me xls 22 2a 247 25 267 Alr 28 29 30 Sl 32 33 34r 351 Beware reshape may also return a copy MO wae bea Cs 2 a T reshape 3 2 To understand see the section on the memory layout of an array below Dimension shuffling a np arange 4 3 2 reshape 4 a shape Sy AD eu p yr za a transpose 1 2 O0 b shape 2 4 iz Bs sO Also creates a view Resizing Size of an array can be changed with ndarray resize gt gt gt a np arange 4 gt gt gt a resize 8 gt gt gt a array LO However it must not be referred to somewhere else gt gt gt b a gt gt gt a resize 4 Traceback most recent call last pages cu line 1 La lt mocule gt ValueError cannot resize an array that has been referenced or is referencing another array in this way Use the resize function Some examples of real world use cases 3 2 Numerical operations on arrays 63 Python Scientific lecture notes Release 2013 1 Case 2 a Calling legacy Fortran code Shape preserving functions with elementwise non Python routines For instance Fortran I o 2 a fortran module rf90 subroutine some function n a b integer n double precision dimension n intent in double precision dimension n intent out a 1 end subroutine some_function We can use
339. y 2 60l dc yoe ine SZ as strided x 1l2 0 sheape 4 lyp strides 3 x 1Cemsize J array 4 8 dtype int32 Note gt gt gt y np diag x k 1 gt gt gt y array l2 6l cry pe intr 37 However gt gt gt Vy flags owndatla True It makes a copy See Also stride diagonals py Challenge 8 1 Compute the tensor trace gt gt gt x np arange 5 5 5 5 reshape 5 5 5 5 gt gt gt s 0 gt gt gt for i in xrange 5 for j in xrange 5 S peer caesus by striding and using sum on the result Life of ndarray 172 Python Scientific lecture notes Release 2013 1 as strided x shape 5 5 strides TODO TODO assert s s2 Solution y as strided x shape 5 5 strides 5 5 5 5 x itemsize 5 5 1 x itemsize s2 y sum CPU cache effects Memory layout can affect performance In I x np zeros t200005 In 2 v npexebos c20000 67 9 25 67 In 3 x shape y shape 02100100 05 20000 In 4 timeit x sum 100000 loops best of 5 0 180 ms per Loop In 5 timeit y sum 100000 Loops best of 3 2 354 ms per loop In Gls x lt sst rides vast rudes Cord 53077 Smaller strides are faster cache block size CPU pulls data from main memory to its cache in blocks f many array items consecutively operated on fit in a single block small stride gt fewer transfers needed gt faster See Also
340. y docs modules index Click on any image to see full size image and source code 4 lam m 1 Go T T EL i gt l Ap E Enter search terms or a module j i class or function name TIT TIT WENN ji amp matplotlib te wn co some other Mayavi s website http code enthought com projects mayavi docs development html mayavi also has a very nice gallery of examples http code enthought com projects mayavi docs development html mayavi auto examples html in which one can browse for different visualization solutions 140 Python Scientific lecture notes Release 2013 1 Mayavi v3 3 1 documentation previous next index Fy Example gallery Mlab functions gallery These are the examples of the mlab plotting functions They are copied out here for convenience Please refer to the corresponding section of the user guide for more information 3D Plotting functions for numpy arrays Table Of Contents plot3d points3d imshow Example gallery a Mlab functions gallery S Advanced mlab examples Interactive examples Advanced visualization Previous topic surf contour surf mesh examples Misc examples Miscellaneous n s fig M Next topic 2 n Boy example X X EET This Page B ES Show Source Quick search barchart triangular_mesh contour3d Enter search terms or a module e class or function name g
341. y e Miscellaneous routines scipy misc S Find help Previous Next Highlight all Match case 9 Reached end of page continued from top 139 Python Scientific lecture notes Release 2013 1 e Numpy s and Scipy s documentation is enriched and updated on a regular basis by users on a wiki http docs scipy org numpy As a result some docstrings are clearer or more detailed on the wiki 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 documentation editor Back to Numpy Scipy documentation Numpy documentation editor scipy org editor Wiki Docstrings Changes Milestones Search Stats Patch Login scipy ndimage morphology binary dilation View Log DifftoSVN Discussion Source Review status Being written SciPy Multi dimensional image processing mod scipy ndimage binary_dilation input structure None iterations 1 mask None output None border_value 0 origin 0 brute_force False Multi dimensional binary dilation with the given structuring element Parameters input array_like Binary array_like to be dilated Non zero True elements form the subset to be dilated structure array_like optional Structuring element used for the dilation Non zero elem
342. y address of the data a Xa iray aneertrace data JO 64803824 The whole array interface gt gt gt x array interface io ceste 395828920 IBcitb eU Passer Jefe quy shape 4 strides None typesur s 4 Version s Reminder two ndarrays may share the same memory 250 x Mp verray lle 2 Scu gt gt gt y x 1 8 1 Life of ndarray 162 Python Scientific lecture notes Release 2013 1 gt gt gt x 0 9 gt gt gt y array pes oi Memory does not need to be owned by an ndarray gt gt gt x 71234 gt gt gt y np frombuffer x dtype np int8 gt gt gt v data lt read only bunrer for eor Size 4 Ofret O atu wea gt gt gt y base is x True mos yai AGS C CONTIGUOUS X True PlCONTIGUOUS s Truc OWNDATAT alae WRITEABLE False ALIGNED gt True UPDATE ITV COPY EE The owndata and writeable flags indicate status of the memory block See also array interface 8 1 3 Data types The descriptor dt ype describes a single item in the array type scalar type of the data one of int8 int16 float64 et al fixed size str unicode void flexible size gt gt gt np dtype int type type numpy int64 gt gt gt np dtype int itemsize 8 gt gt gt np dtype int byteorder KT Example reading wav files The wav file header 8 1 Life of ndarray 163 Python Scientific lecture notes Release 2013 1 4 byte unsigned litt
343. y in Python and so are some operations on strings such as additions and multiplications which amount respectively to concatenation and repetition 2 2 Basic types 2 2 1 Numerical types Python supports the following numerical scalar types Integer mos dq nau 2 gt gt gt a 4 gt gt gt type a type antt 2 1 First steps 10 Python Scientific lecture notes Release 2013 1 Floats poc E gt gt gt Lye Cc Sue UI gt Complex Doc dis gs uw 5 gt gt gt a real deer gt gt gt a imag G25 gt gt gt Lype l 07 type complex gt Booleans gt gt gt 3 gt 4 False gt gt gt test 3 gt 4 gt gt gt test False gt gt gt type test lt type bool gt A Python shell can therefore replace your pocket calculator with the basic arithmetic operations modulo natively implemented gt gt gt pe 3 21 0 gt gt gt 2xx10 1024 gt gt gt 0 3 Z Type conversion casting 2 Elica O 2 2 Basic types 11 Python Scientific lecture notes Release 2013 1 Warning Integer division gt gt gt UL 32 1 Trick use floats Soe 3 2 1 5 D ES gt gt gt h 2 gt gt gt wow il gt gt gt a Elloat b EES If you explicitly want integer division use gt gt gt 3 0 a2 1 0 Note The behaviour of the division operator has changed in Python 3 Please look at the python3po
344. ype dtype floato4 The default data type is floating point gt gt gt a np ones 3 3 gt gt gt a dtype dtype floato4 There are also other types Complex 2o d Mp ereay 1 2 214 Spas gt gt gt d dtype dtvpe complexl29 Bool gt gt gt e np array True False False True gt gt gt e dtype dtype l bool Strings gt gt gt i mp array UP BonJour r Helio aallon gt gt gt dtype lt SEriIngds COnNnLaining max 7 letters diype TS Much more int32 int64 3 1 5 Basic visualization Now that we have our first data arrays we are going to visualize them Start by launching IPython in pylab mode ipython pylab Matplotlib is a 2D plotting package We can import its functions as below gt gt gt import matplotlib pyplot as plt 7 the tidy way 1D plotting 3 1 The numpy array object 46 gt gt gt x np linspace 0 gt gt gt y np linspace 0 Poe Olt Olot x Yy gt gt gt plt show 3 0 0 5 2D arrays such as images gt gt gt image np random rand 30 gt gt gt plt imshow image poc pltocoborbart line plot lt matplotlib lines Line2D object at Po gt ES poti yp e lt matplotlib lines Line2D object at dot plot emap plt em gray matplotlib image AxesImage object at Python Scientific lecture notes Release 2013 1 I lt shows the plot not needed with Ipython 1 5 2 0 2 5 3 0
345. ype np int8 Zlieri 0 254 red x 3 255 opaque data x view np int32 Check that you understand why this is OK img Image frombuffer RGBA 200 200 data ImgsSsave test png Modify the original data and save again P IS turns OUL that Pity which knows next CTO Morning eDOoNt Nompy happily shares the same data scc 4 img save test2 png 8 3 Interoperability features 184 Python Scientific lecture notes Release 2013 1 8 3 4 Array interface protocol Multidimensional buffers e Data type information present e Numpy specific approach slowly deprecated but not going away Not integrated in Python otherwise See Also Documentation http docs scipy org doc numpy reference arrays interface html gt gt gt x np array l 21 137 411 gt gt gt x array interface data 1716094552 False Pdea raa pue veda TLypestr s Txx4t strides None Reape 2p wine lane som t memory address of data is readonly data type descriptor same in another form Se SF cHe ck Strides or None at zn C order gt gt gt import Image gt gt gt img Image open data test png gt gt gt img array interface data me shapbe s 200 200 4 Mey pester aly gt gt gt X np asarray img gt gt gt x shape 200 200 4 gt gt gt x dtype dtype uint8 Note A more C friendly variant of the array interface is a

Download Pdf Manuals

image

Related Search

Related Contents

Bedienungsanleitung Ultraschall-Reinigungsgerät - GT  USER'S GUIDE - Personal Web Space  OLYMPUS VR 360 Vos rêves deviennent réalité  Tandberg Data Cartridge SLR5, 4GB  Overview  X-CLARITY™  F5D7230-4_sp  user manual - solidThinking  Descargar documento  c:\Data\Output\20100329-155853-6426_exchange_out\WN56609  

Copyright © All rights reserved.
Failed to retrieve file