Home

Introduction to Python for Science Contents

image

Contents

1. CUASI In 86 double_it 3 Out 86 6 Keyword arguments allow you to specify default values In 124 bigx 10 In 125 def double_it x bigx iene ts E return x x 2 In 126 bigx le9 No big In 128 double_it Our 126 20 More involved example implementing python s slicing 2 3 Defining functions 13 Introduction to Python for Science Release 1 In 98 def slicer seg start None stop None step None OS implement baste pyehon Saca saarn return seg start stop stepl In 101 seuss one fish two fish red fish blue fish split In 102 seuss Oui AO Monen as a o Bush Vo red ashe ue asa In 103 slicer seuss Out MOS one AS Os e as a o Ue asia In 104 slicer seuss step 2 Que Lo Fone EWS e ae In 105 slicer seuss 1 step 2 CUA AA Ss IIn In 106 slicer seuss start 1 stop 4 step 2 Ou LLO06 s tica E Ciela E Introduction to Python for Science Release 1 2 3 5 Global variables Variables declared outside the function can be referenced within the function In 114 x 5 In 115 def adax y SN return x y In 116 addx 10 Ou MLE 15 But these global variables cannot be modified within the function unless declared global in the function This doesn t work 2 3 4 Passed by value Parameters to functions are passed by value When you pass a variable t
2. Number of labels 0 Shadow Use default name Y T Data name scala Edit bar Title Edit bar Text Edit bar Actor Edit bar widget 5 3 3 Decorations Click on the red button and it generates lines of code In 9 mlab colorbar Out 7 orientation vertical Out 9 lt tvtk_classes scalar_bar_actor ScalarBarActor object at 0xd897f8c gt In 10 mlab title polar mesh Out 10 lt enthought mayavi modules text Text object at Oxd8ed38c gt In 11 mlab outline Out 7 Out 11 lt enthought mayavi modules outline Outline object at Oxdd21b6c gt In 12 mlab axes Out 7 Out 12 lt enthought mayavi modules axes Axes object at Oxd2e4bcc gt 60 5 4 Interaction 5 3 Figures and decorations CHAPTER 6 Debugging The python debugger pdb http docs python org library pdb html 6 1 Coding best practices to avoid getting in trouble 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 e We all write buggy code Accept it Deal with it e Write your code with testing and debugging in mind e Keep It Simple Stupid KISS What is the simplest thing that could possibly work e Don t Repeat Yourself DRY Every piece of knowledge must have a single unambiguous authorita
3. e Capturing and reraising an exception In 15 def filter_name name TE try ere name name encode ascii ees except UnicodeError e ES if name Ga l adk print OK Ga l AS else ss raise e ae return name In 16 filter _name Ga l OK Ga l Out 16 Ga xec3 xabl In 17 filter_name St fan UnicodeDecodeError ascii codec can t decode byte 0xc3 in position 2 ordinal not Please enter a number a Thank you oie your aap wit Important for resource management e g closing a file Easier to ask for forgiveness than for permission Don t enforce contracts before hand ValueError invalid literal for int with base 10 a In 11 def print_sorted collection ES try Bese Collectiom sorte 0 Peas except AttributeError ERS pass E print collection ta 12 print sorted Il 3 21 Ily 2 3 In 13 print sortedlset d 3 2 see ll 2 2 2 4 Exceptions handling in Python 18 e Exceptions to pass messages between parts of the code In 17 def achilles_arrow x e sisz alos gt I lt le 3e iS raise Stoplteration ee x l Cl 2 RE return x In 18 x 0 In 19 while True ARTE try PE E x achilles_arrow x AS except Stoplteration os eae break In 20 x Outs ZONE Oro S202 S4si5 Use exceptions to notify certain conditions are met e g StopIteration or not
4. Hello world Hello world Getting help In 2 print Type bulk mntranet TONT Or Met lee Base Class lt type builtin_function_or_method gt String Horm lt Joual ic 140 Etica jorcslinie gt Namespace Escala ova Wie sia Doctrina print value sep end n file sys stdout Prints the values to a stream or to sys stdout by default Optional keyword arguments file a file 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 2 1 2 Elaboration of the algorithm in an editor 3 Introduction to Python for Science Release 1 CHAPTER 2 Warning Integer division In 7 372 Ouelyis i In 8 from _ future _ import division TTS Que ele SS Introduction to the Python language Trick Use oats in 10 3 7 2 OWE lAs ts e Type conversion a In 11 float 1 Note Reference document for this section o Python tutorial http docs python org tutorial Exercise 2 1 Basic types Compare two approximations of pi 22 7 and 355 113 pi 3 14159265 2 1 1 Numbers e Python as a calculator 2 1 2 Collections In 1 d al Collections list dictionaries and strings tuples sets QUA AA 2 In 2 2x x 10 Lists Out lA 1024 In 3 1 1j 1 1j wA aae S E y a Our 31 2407 eds e Indexing sc
5. Out ilal eee Wiser s counnsy locali Users cbhurns local lib python2 5 site packages gqrin l l py2 5 egg Users cburns local l1ib python2 5 site packages argparse 0 8 0 py2 5 egg Users cburmns local lib pythonZ 5 site packages urwid 0 9 7 1 py2 5 e099 7 Users cburns local lib python2 5 site packages yolk 0 4 1 py2 5 egg Users cburns local lib python2 5 site packages virtualenv 1 2 py2 5 e9g 2 7 5 pickle easy persistence Useful to store arbritrary objects to a file Not safe or fast In 1 import pickle In 2 1 1 None Stan In 3 pickle dump 1 file test pkl w In 4 pickle load file test pkl Ouralek Nene 4 Stan Exercise Write a program to search your PYTHONPATH for the module site py The PYTHONPATH Search Solution 2 7 Standard Library 30 CHAPTER 3 Core scientific modules Context e Numerical algorithms are not a special case of computing the need for them arises simultaneously with the need for other tools e Exploratory coding easy reading e Visualization don t play with numbers without plotting or you probably won t understand what you are doing Core scientific libraries numpy http www scipy org Download ipython http Apython scipy org matplotlib http matplotlib sourceforge net scipy http www scipy org Download mayavi http code enthought com projects mayavi
6. Use distributions e Python x y http www pythonxy com EPD http www enthought com products epd php Ressources e http docs scipy org e numpy lookfor e Python Les fondamentaux du langage La programmation pour Les scientifiques Matthieu BRUCHER editions ENI e Python Scripting for Computational Science Hans Petter Langtangen Springer e Beginning Python visualization Shai Vaingast Apress 3 1 Numpy array computing 31 Introduction to Python for Science Release 1 Conventions gt gt gt import numpy as np gt gt gt import scipy as sp gt gt gt import pylab as pl 3 1 1 Array computing Python numpy List a 1 2 3 Array a np array 1 2 3 Doing operations on many numbers e Standard numerical computing loops def square data for i in range len data data i datal i x x 2 return data 1000 loops best of 3 314 us per loop In 1 Stimeit data range 1000 square data Introduction to Python for Science Release 1 gt gt gt np ones 2 ama I Lo Ii dep ie Arrays contain typed entries gt gt gt np ones 3 dtype np int arrays le O Creating a grid gt gt gt Xx y Mo indices 27 20 gt gt gt X array 0 0 Lig T gt gt gt y array MOP 1s Pore 111 gt gt gt x 13xy array GIROARI Ocal all AROSA lel Views and copies d
7. while abs z lt 100 ARS if z imag ances break pe TZ 1 Rmk continue the next iteration of a loop 2 2 4 Conditional Expressions e if object Evaluates to True any non zero value any sequence with a length gt 0 Evaluates to False any zero value any empty sequence e q Tests equality with logics In 19 1 1 cuti rol True e aisb Tests identity both objects are the same In 20 1 is 1 Out 20 False In 21 a 1 In 22 b 1 In 23 a is b Out 23 True 2 2 Control Flow 10 Introduction to Python for Science Release 1 eainb For any collection b b contains a If bis a dictionary this tests that a is a key of b 2 2 5 Advanced iteration Iterate over any sequence e You can iterate over any sequence string list dictioary file In 11 vowels aeiouy In 12 for i in powerful ee Ss if i in vowels Ae Suse print i Warning Not safe to modify the sequence you are iterating over Keeping track of enumeration number Common task is to iterate over a sequence while keeping track of the item number e Could use while loop with a counter as above Or a for loop 1 powerful 2 readable e But Python provides enumerate for this In 13 for i in range 0 len words EL print i words i 0 coo 1 powerful 2 readable Looping over a dictionary Use iteritems In 14 f
8. 5 z npesin r r 5 3 Figures and decorations 58 5 3 Figures and decorations 59 Introduction to Python for Science Release 1 Introduction to Python for Science Release 1 1 60e 16 In 6 from enthought mayavi import mlab a a u r mesh In 7 mlab mesh x y z Colormap gist earth extent I0 A 0 n 0 T 1 00 E Out 7 lt enthought mayavi modules surface Surface object at 0Oxde6f08c gt _ 0 546 In 8 mlab mesh x y z extent 10 ly 0 L 0 A 1 representation wireframe line_width 1 color 0 5 0 5 0 5 0 399 Out 8 lt enthought mayavi modules surface Surface object at Oxdd6a71c gt Z 0 251 f 0 103 A 0 0442 1 988 1 gt i 0 192 Warning extent If we specified extents for a plotting object mlab outline and mlab axes don t get them by default 5 4 Interaction Click on the Mayavi button in the scene and you can control properties of objects with dialogs Mayavi pipeline CEE T OO BD Mayavi Scel Er Pipeline Scalar LUT Vector LUT ModuleManager rPIHR MHA S A 4 Y E Mayavi Scene 1 LUT Look Up Table Manager 1 600 16 v GridSource Y PolyDataNormals Lut mode gist_earth Y amp Colors and legends IM Surface Number of colors 256 T Outline Reverse lut C T Axes Edit LUT properties Y GridSource Launch LUT editor Y PolyDataNormals gt Show legend
9. gt 115 fp close 16 return parse_data data_string ipdb gt next gt Users cburns sre selpy2009 sctpy_ 2009 tutorial source deb g_tile py l6 load data T5 fp close gt 16 return parse_data data_string 17 Step into parse_data function with s tep command ipdb gt step Call gt Users cburns src scipy2009 scipy_2009 tutorial source debug_file py 6 parse_data 5 gt gt 0 cer arse eleawra datario 7 data aci igt 1 Script to read in a column of numbers and calculate the min max and sum 2 il Deans Sit OFS Ce ino ata Woe wy 3 4 5 6 def parse_data data_string 7 data 8 oe x aim Clica Sic realine Sjollakic 4 E g data append x 0 1 1 return data I Continue stepping through code and print out values with the p rint command 6 2 The debugger 65 Introduction to Python for Science Release 1 Introduction to Python for Science Release 1 ipdb gt step gt Users cburnis src scipy2009 scipy_2009_tutorial source debug_ file py 9 parse data 8 Sa 8 10 ipdb gt p Os ipdb gt s x iO 5 alin a as rMo Sp aE data append x return data gt Users cburns src scipy2009 scipy_2009_tutorial source debug_file py 8 parse_data 7 eee 9 ipdb gt s data TOR x iin care sermo solie lt data append x gt Users cburns src scipy2009 scipy_2009_tutorial source debug_file py 9 parse_da
10. gt al nask 2 array 2 22 52 ae ES EN EB _N ATA BE ES ES Ea A mece ls is aimeces 2 Ls imegel2s es MAZA image ls 23 20 25 In 3 import pylab as pl In 4 In 5 pl imshow 1 cmap pl cm gray In 6 A E a Lisl lt 2 Lfissi 28 In 7 cmap pl cm gray 3 1 2 Advanced indexing With integers or masks Execution time Pur Python 1s 100ms 10ms lms 100us 10us 50 100 500 Timing ratio 3 1 Numpy array computing 34 o With integer arrays e Example sorting a vector with another one gt gt gt a b np random random_integers 10 size 2 4 gt gt gt a array IS 6 2 91 gt gt gt b array 8 9 SON gt gt gt a order np argsort a gt gt gt a_ order array 27 lp De 3 gt gt gt bla_ oon arre 1 S oF Sa LO Using masks Zeroing out all the even elements of a table gt gt gt a np arange 10 gt gt gt a array 10 Wy 27 37 A S G Tp Se SL gt gt gt alla 2 1 0 gt gt gt a amran il E y Ye DM Applying a mask to a grid to select the center of an image In 8 n m 1 shape In 9 x y np indices la m In ate checas ma sepas a 0 3 m2 5 Y Ohne Ter in 11 l distances gt 2001 255 In 12 pl imshow l cmap pl cm gray 3 1 Numpy array computing 35 Introduction to Python for Science Release 1
11. 1 Figure management Function signatures mesh x Vo Do 553 ota PONEI x y Z are 2D arrays all of the same shape giving the positions of the vertices of the surface The connectivity between these points is implied by the connectivity on the arrays ee L e arent Meu mab N For simple structures such as orthogonal grids prefer the surf function as it will create more efficient data Set the current figure mlab figure 1 bgcolor 1 1 1 fecolor 0 5 0 5 0 5 peepee Save figure to image file mlab savefig foo png size 300 300 sarc ae imeni Change the view mlab view azimuth 45 elevation 54 distance 1 y 8 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 9 3 2 Changing plot properties extent xmin xmax ymin ymax zmin zmax Default is the x y z arrays extents Use this to change the extent of the object created figure Figure to populate line_width The with of the lines if any used Must be a float Default 2 0 mask boolean mask array to suppress some data points mask_points If supplied only one out of mask_points data point is displayed This option is usefull to reduce the number of points displayed on large datasets Must be an integer or None mode the mode of the glyphs Must be 2darrow or 2dcircle or 2dcross or 2ddas
12. 200 200 Soe ot Mp Sae A yeas ARA These three lines take 2 3s the creation of x y z takes 0 5s and the calculation of r takes 1 8s The total memory used is 64Mb per array There are 4 named arrays x y z and at least 2 temporary arrays are created Thus around 400Mb are used Squaring each array take 20043 operations as well as the two additions and the call to np sqrt Thus a total of 48 million operations y l be With broadcasting gt gt gt X Yo 2 gt ma ogridi NO Oe OOF 0 08 1 010 008 100 gt gt gt print x shape y shape z shape 200 I 1 ll 200 1 il i 200 gt gt gt E Mo Saa Ken eee oe These lines take 1 1s second with only 6ms to create the arrays The three input arrays take only 1 6Kb The output array 64Mb and there is not more than a 64Mb and a 320kb temporary array created Around 120Mb are used Squaring each array takes 200 operations the first addition is 200 2 40 thousands operations and the second as well as the call to np sqrt is 200 3 8 million operations Thus around 16 million operations are performed Looking at the relative timings between non broadcasted and broadcasted versions we can see that they do not scale proportionally to the number of operations Broadcasting does take some time Monte Carlo density evaluation Density evaluation of f A sin kl X B sin k2 Y using the probability distribution of A B
13. 3 1 3 Broadcasting Multidimensional operations You can add a numer to an array gt gt gt a np ones 3 gt gt gt d sucia UL do ley sll gt gt gt a ll arayin ae 2h And what if we add two arrays of different shapes gt gt gt b Zenp omes 2 1 gt gt gt b arkay I 25 ll De a gt gt gt a FD array Sa Sher Seale ese ees Sel Dimensions are matched 3 1 Numpy array computing 36 Introduction to Python for Science Release 1 Using broadcasting for performance e Creating a 3D grid MO SONG E sp Waeee ap ZA 3 1 Numpy array computing 37 Introduction to Python for Science Release 1 X Without broadcasting e y Ny LL gt a Nee OON LOO 1 010 8 11010 34 01 0 8 OW gt gt gt print x shape y shape z shape 2007 2007 2000 200 2007 200 200 2007 200 A A r A e Timing 2 3s creating x y z 0 5s calculation of r 1 8s e Memory 64Mo per array 6 arrays x y z r and 2 temporary arrays gt 400Mb e 20013 floating point operations per array 48 million operations 3 1 Numpy array computing 38 Introduction to Python for Science Release 1 With broadcasting 22 gt y Nip LE ma OC ane 1003100 1003 1 00 010 3 101017 gt gt gt print x shape y shape z shape 200 i 1 AO 1 i 1 200 gt gt gt ES Np sq sexo E YA fF ZAR e Timing 1 1s creating
14. 3 print Yes print statements do work as a debugging tool 6 4 Debugging strategies 1 Make it fail reliably Find a test case that makes the code fail every time 2 Divide and Conquer Once you have a failing test case isolate the failing code e Which module e Which function e Which line of code Change one thing at a time and re run the failing test case Take notes It may take a while Be patient It may take a while E 1 p in IPython Purposely raise an exception where you believe the problem is to inspect the code via the debuger eg debug 6 3 print 67 Introduction to Python for Science Release 1 CHAPTER def test data np random random 5000 100 u Ss v linalg svd data pea np clar iS OF ly elemen results fastica pca T whiten False test TE AAN demo py Profiling Python code IPython CPU timings estimated User ISS System 0 256016 5 im 21 erun p demo py Sito tine tone MSN ITSS IMEE Seconds Ordered by internal time No optimization without measuring ncalls tottime percall cumtime percall filename lineno function iL 14 457 14 457 14 479 14 479 decomp py 849 svd e Measure profiling timing e Premature optimization is the root of all evil iL 0 054 0 054 0 054 0 054 method random_sample of mtrand RandomState objects il OO Oc O17 oroz 0 02
15. Blocks are delimited by indentation More collection types e Sets non ordered unique items Tn 39 lt s seta Eb Ue a In 40 s ouelo ser ar Mat ell In 41 s ditterence a b Ste 4s ser Gee lp Sets cannot be indexed In 2 a 10 In 3 if a print 1 elif a print 2 else print A lot A lot 2 2 2 for range Iterating with an index In 42 s 1 INPSeE nor massa MO sis cone Als 0 TypeError set object does not support indexing In 4 for i in range 4 print i Co ky amp e Tuples non mutable lists In 43 t 1 2 In 44 t Owe 4413 Cle In 45 t 1 Que 45 2 In 46 t 1 2 UOC Er RON tracelacs most cecene Call last TypeError tuple object does not support item assignment 2 1 Basic types 8 But most often it is more readable to iterate over values In 5 for word in cool powerful readable o print Python is s word Python 1s cool Python is powerful Python is readable 2 2 3 while break continue Typical C style while loop Mandelbrot problem 2 2 Control Flow 9 Introduction to Python for Science Release 1 In 6 z 1 13 In 7 while abs z lt 100 Z Zxx2 1 In 8 z Oui ss TIB S235 break out of enclosing for while loop In 9 z 1 1j In 10
16. Directory Listing Solution dde 1 Amr In 78 all_lines 0 out rS GUARD LANNO daf who is n fy English kaniggets and Monsieur Arthur King 2 5 Reusing code 22 2 6 File I O in Python 23 Introduction to Python for Science Release 1 2 6 2 lterate over a file Files are sequences we can iterate over them In 81 fp open holy_grail txt in 82 for line in fp sanes print line GUARD Allo daffy English kaniggets and Monsieur Arthur King who is afraid of a duck you know So we French fellows out wit you a second time 2 6 3 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 e Binary mode b Note Use for binary files especially on Windows 2 6 4 Writing to a file Use the write method In 83 fp open newfile txt w In 84 fp write I am not a tiny brained wiper of other people s bottoms In 85 fp close In 86 fp open newfile txt In 87 fp read Out 87 I am not a tiny brained wiper of other people s bottoms Update a file In 104 fp open newfile txt rt In 105 line fp read an 111 Line CHRIS line Na In 112 line Out 112 CHRIS I am not a tiny brained wiper of other people s bottoms n 2 6 File I O in Python 24 Introduction to
17. General te A sessions Stride Shape Stride Shape CVS Log for Current Document a of Kat Documents Label pyflakes Script dialog title pyflakes filenamje msgbox S pyflakes filename Filesystem Browser amp Executable kdialog Mime types A Save Current Document v Command line name pyflakes OK Cancel Help OK Cancel 7 Overlapping dimensions Easy now all we have to do is sum along the axis 0 gt gt gt b sum axis 0 9 2 In vim amenan i oF e T om ID In your vimrc binds F5 to pyflakes o autocmd FileType python let amp mp echo xxx running x pyflakes autocmd FileType tex mp rst python imap lt Esc gt 15 lt C O gt make M autocmd FileType tex mp rst python map lt Esc gt 15 make M autocmd FileType tex mp rst python set autowrite 8 4 Robert Kern s nasty stride trick 82 83 Introduction to Python for Science Release 1 9 3 In emacs In your emacs binds F5 to pyflakes 9 3 In emacs 84
18. Python for Science Release 1 In 113 In 114 In 115 out MAS In 116 In 117 Owe 1471 E In 132 In 136 In 137 Que ST IE CHRISS GAEL I ve met your children dear sir yes you are n fp seek 0 LE fp write line fp tell 64L fp seek 0 fp read CHRIS I am not a tiny brained wiper of other people s bottoms fp write GAEL I ve met your children dear sir yes you are n fp seek 0 LE fp readlines I am not a tiny brained wiper of other people s bottoms n 2 6 5 File processing Often want to open the file grab the data then close the file In 54 In 60 GUARD Allo daffy English kaniggets and Monsieur Arthur King who is afraid of a duck you know So we French fellows out wit you a second time fp open holy grail txt try for line in fp print line finally fp close With Python 2 5 use the with statement In 65 In 66 GUARD Allo daffy English kaniggets and Monsieur Arthur King who is See cule on El duck Yau knows So we French fellows out wit you a second time from _ future import with_statement with open holy grail txt as fp for line in fp print line This has the advantage that it closed the file properly even if an exception is raised and is more concise than the try finally 2 6 File I O in Python
19. X and Y Strategy sample f with huge arrays of the random variables and build an histogram of the results Introduction to Python for Science Release 1 With broadcasting sample n values for each A B X and Y along a different direction each time n 4 samples for f Warning Unwanted correlations are introduced between the random variables 8 2 Views and strides 8 2 1 Views and copies Views Two arrays can point to the same data 8 1 Broadcasting 74 gt gt gt import numpy as np gt gt gt a np arange 10 gt El array Ton de 2 Sp Ue Do Do Te Se 2 gt gt gt b al 3 7 gt gt gt b array l2 4 S9 SI gt gt gt b 0 0 gt gt gt b array 10 4 Bp 11 gt gt gt a array I0 1 2 0 4 op SSA a was also modified No memory duplication How to tell inspecting the data buffer gt gt gt np may_share_memory a b E e e The base attribute of the array gt gt gt b base is a rue e Look at the base pointer of the data buffer and the extent a ctypes data 140052096 o len a data 140052136 b ctypes data 140052108 b ctypes data len b data 140052124 e Look at the OWNDATA flag to tell if the array owns its data 8 2 Views and strides 75 Introduction to Python for Science Release 1 Introduction to Python for Science Release 1 gt gt gt bags import numpy as np
20. doing the same thing more than once kernprof py 1 v demo py 3 memory number of operations minimization and trade off Wrote profile results to demo py lprof Timer unit le 06 s Avoiding loops File demo py e Fancy indexing Function test at line 5 e Know the numpy library well Total time 14 2793 s e Reshaping striding Line Hits Time Per Hit Time Line Contents e Think different 5 profile Algorithmic optimisation 6 def test 7 1 19015 19015 0 Goal data np random random 5000 100 e See the forest not the trees 8 1 14242163 14242163 0 IN u S v linalg svd data E a Think before you code 9 i 10282 10282 0 Oa pea np dot u 10 data y 10 il TUDES TIJ O 0 dl results fastica pca T whiten False Refactor The SVD is taking all the time We need to optimise this ligne Know the standard scientific library scipy http docs scipy org In 3 Stimeit np linalg svd data il loops best or 3 1455 sper Loop numpy lookfor E e Know your math In 4 from scipy import linalg wrong In 5 Stimeit linalg svd data i loops best of 3 452s per loop import numpy as np _ singular_values _ np linalg svd np dot X T X In 6 Stimeit linalg svd data full_matrices False 1 loops best of 3 295 ms per loop harder better faster stronger In 7 Stimeit np linalg svd data full_matrices False f i i lina i loops best or 39 293 ms per loop POM ECT EY Garo es s
21. first line e You can do unusual operations on arrays along certain strides 8 2 Views and strides 76 8 2 Views and strides 77 Introduction to Python for Science Release 1 gt gt gt ON array I Orr cll 2er 2er Yar Sern Ger Ver Ser QD gt gt gt r 0 reshape 5 2 array ITP Os Lol eee Bely DA Sady o l Sop 2D gt gt gt r O reshape 5 2 sum axis 1 array Ll Lo A OF IRES Lal Reshaping is when possible just a matter of changing the stride and shape for a flat array gt gt gt r np arange 8 gt gt gt r strides 4 gt gt gt r shape 8 Stride 4 4 4 4 4 4 4 4 Shape x8 After reshape gt gt gt r2 r reshape 4 2 gt gt gt r2 strides 8 4 gt gt gt r2 shape 4 2 Stride Shape Stride Snape And when slicing backwards gt gt gt r3 r 1 gt gt gt r3 strides 4 Introduction to Python for Science Release 1 8 2 Views and strides 78 Take home message You can apply operations with a certain regularity on an array by finding the view that gives you the right striding and shape 8 2 3 In place operations e Inplace operators e All ufuncs take an out arguments Without inplace operations ree x np linspace 100 100 le6 eee yy mp la spare 1007 e007 ec gt gt gt r Np sSsqrt xx Z Y ez Time of the calculation of r 2s Using inplace operations All ufunc
22. from scipy import optimize x np linspace 0 10 100 y np sin x 0 5b np random normal size 100 Ol jOILOE x Yo n def test func x a E phi return axnp sin fx x phi a f phi _ optimize curve_fit test_func x y pi jolla 6 test ame E a f phi gt Iinewidth s 3 3 Scipy numerical and scientific toolbox 43 Introduction to Python for Science Release 1 3 3 3 Statistics and random numbers gt gt gt a np random normal size 1000 gt gt gt bins np arange 4 5 gt gt gt bins array li 2 gt Ue dea Sy a gt gt gt histogram np histogram a bins bins gt gt gt Dins 0 5 Dins t binsi 11 gt gt gt bins array ls aio Lea AS es dl gt gt gt from scipy import stats gt gt gt b stats norm pdf bins no 2 y AE In 1 pl plot bins histogram ma zas ja ole bins 19 0 40 0 35 0 30 0 25 0 20 0 15 3 3 Scipy numerical and scientific toolbox 44 Introduction to Python for Science Release 1 3 3 4 Image processing from scipy import ndimage 1 sp lena pl imshow ndimage gaussian_filter l 5 cmap pl cm gray pl imshow ndimage gaussian_gradient_magnitude l 3 cmap pl cm gray 3 3 5 Interpolation x np arange 10 y np sin x Pipo ae markersize 10 from scipy import interpolate f interpolate interpld x y X np linspace 0 9 100 j
23. scipy2009 scipy 2009 _ tutorial source de List the code with 1 ist ocios ise 1 Script to read in a column of numbers and calculate the min max and sum 2 il 53 Dara ls sucre in cecel CE gt 4 ww 5 6 def parse_data data_string 7 data 8 Om im Celica Situado Sole 1 4 E 9 data append x 10 return data LA ocios lis 2 12 def load_data filename LS fp open filename 14 data_string fp read 15 fp closed 16 return parse data data String 6 2 The debugger 64 Introduction to Python for Science Release 1 7 18 if _ name _ _ main 19 data load data exercises data txt 20 print min SE min data 10 20 2l prine max sf 5 max data 6L 30 Continue execution to next breakpoint with c ont inue ipdb gt continue gt Users cburns sre scipy2009 scipy 2009 _tutorial source debug_file py 13 load_data 2 12 def load_data filename gt 13 fp open filename 14 data_string fp read I don t want to debug python s open function so use the n ext command to continue execution on the next line ipdb gt next gt Users cburns src scipy2009 scipy_2009_tutorial source debug_file py 14 load_data dls fp open filename gt 14 data_string fp read T5 fp close ipdb gt next gt Users cburns sre scipy2009 scipy 2009 tutorial source debug file py 15 load data 14 data_string fp read
24. take an out argument xx 2 gt gt gt gt gt gt y X gt gt gt y xx 2 X r np sgrt x x gt gt gt Total time 1 4s Memory consumption twice as small In conclusion views eventually strided avoid memory consumption and open the door to interesting array manipula tions 8 3 Fancy indexing 8 3 1 Rules Indexing with integer arrays gt gt gt import numpy as np gt gt gt a np arange 30 reshape 3 1 gt gt gt a kacca Op ip 27 93 a Sp 10 Tr Se Si LO il 12 is 14 19 16 17 18 19 20 215 22 2357 24 25 26 Zi 2387 29 I fs alt Gl 31 larray 1 Sule Ea Ss e CA e 8 3 Fancy indexing 79 Introduction to Python for Science Release 1 Introduction to Python for Science Release 1 Shape is given by shape of indexing array slices gt gt gt indices np random randint a shapel 1 size 3 10 gt gt gt al 17 3 2 4 l shape gt gt gt indices Ora 22 array IIs C S Le Se 9 Le Me De Gly ESA A e LOLA S jo If multiple integer arrays for indexing they are broadcasted together len 2 Tp 07 27 0 3 2 37 1D gt gt gt bootstrap a indices Seale 2 e Soe lees Hae array iil 21 array 3 6 De 4 8 oF 17 Te oF 6 U2 221l L8 0 S w 9 Or 27 O 6p 227 PS aT o SGS eee OS SS g AA lt BLANKLINE gt Indexing with boolean arrays Mis ler le lar ler 19 td i o Wel er 107
25. 1 function_base py 645 asarray_chkfinite 54 O 041 0 000 omonmi 0 000 numpy core _dotblas dot 2 0005 0 002 0 005 0 002 method any of numpy ndarray objects 6 0001 0 000 0 001 OOO Lea py 21a tgp rime z 6 0 001 0 000 0 001 C2000 iea 192 a 7 1 Timeit 14 0 001 0 000 0 001 0 000 numpy linalg lapack_lite dsyevd 19 oomoo 0 000 0 001 0 000 twodim_base py 204 diag In IPython to time elementatry operations Sone ee ee a ee ae ore LON 0 000 0 000 oroo OPO OOM cle maripo array amalize ne In 1 import numpy as np 7 0 000 0 000 0 004 0 001 ica py 58 _sym_decorrelation 7 0 000 02000 0 002 0 000 linalg py 841 eigh O o 172 0 000 0 000 0 000 0 000 isinstance i OOOO 0m 000 are Sol 14 551 demo py 1 lt module gt E O a 29 0 000 0 000 0 000 0 000 numeric py 180 asarray 10000 Loos beet Cece sole e psc loge 35 0 000 0 000 0 000 0 000 defmatrix py 193 __new_ Els 0 000 O OO 0 00 0 000 defmatrix py 43 asmatrix aa meto aa I 21 0 000 0 000 0 001 0 000 defmatrix py 287 _mul_ LU Loca loser On SS Poe US pez boo 41 0 000 0 000 0 000 0 000 numpy core multiarray zeros 28 0 000 0 000 0 000 0 000 method transpose of numpy ndarray objects A O 1 0 000 0 000 0 008 0 008 ica py 97 fastica IO OVOO Moos best Of 9 5 56 s per loop 25 0 000 0 000 0 000 0 000 labs ig 0 000 0 000 0 000 0 000 numpy core multiarray arange Zil 0000 0000 0 000 0 000 defmatrix py 527 getT 7 0000 0 000 0 000 0 000 linalg py 64 _commonType 7 2 Pr
26. 15 10 19 16 127 10 15 121z He 15 17 10 19 10 13 12 13 11111 arcay 10 2 47 167 8 U0 IZ 1 O LS 20 22 24 26 2p o Now we can do vectorized computations easily on the bootstraped sample Flat shape Slicing not used p y p p ale laez 201 Extracting a cut of volume along a horizon array O 27 4 AS r0 12 14 l6 187 207 227 247 267 281 We have an image volumetric data 8 3 2 Applications gt gt gt image np random randimt 10 Size 5 5 gt gt gt image Rearranging vectors ac O Oe or la We a 07 Se ly 5 LS 9m 9p 4 0 We have a vector family e Gr Byte 27 SD gt gt gt vectors np random randint 10 size 4 5 gt gt gt vectors And a horizon the coordinates of a curve in the image array M2r 8 2 PT 7 gt gt gt horizon np array 3 2 1 3 21 1 i 6 i 111 lt lf We can extract the value on the horizon We want to rearrange them by variance gt gt gt image horizon np arange 5 arte 19 Y 07 67 01 gt gt gt variance np var vectors axis 0 gt gt gt variance arrayi 9 n TZ y 4 7 32 375 508 75 gt gt gt rearranged vectors np argsort variance Local average along a horizon gt gt gt np var rearranged axis 0 array 32875 seo 4 j 5 6875 1 25 I This time we want to extract the voxels in the 3 voxels wide region around the horizon gt gt gt image ho
27. 25 Introduction to Python for Science Release 1 Note The from __future__ line isn t required in Python 2 6 Exercise Write a function that will load the column of numbers in data txt and calculate the min max and sum values The Data File I O Solution 2 7 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 7 1 os module operating system functionality A portable way of using operating system dependent functionality Directory and file manipulation Current directory Introduction to Python for Science Release 1 In 36 os rename qunkdir foo0dix Ine isi 2 jumkcine ane os lacsitecine OSs Curdi rE Out 37 False seat 4 merece sn OS Mal siecle Os CURIE QUES sili True In 41 os rmdir foodir in 421 Good ain os llistdir os curdir Out 42 False Delete a file In 44 fp open junk txt w In 45 fp close tn 46 Junk kzt Iin os listdir Os CUECA Out 46 True In 47 os remove junk txt tn 48 Junk tzt ain os lusico e Os Cu UrdiT Out 48 False In 17 Ome iiri os getcwd eers eburns sre sceipy2009 seip 009 tutorial Source List a directory os path path manipulations os path provides commo
28. 5 Introduction to Python for Science Release 1 5 2 4 Arbitrary regular mesh In 13 mlab clf in 14 gt phi theta mp mqrida 0 pi 117 052 pi 117 In 15 x sin phi cos theta In 16 y sin phi xsin theta In 17 z cos phi In 18 mlab mesh x y 2 In 19 mlab mesh x y z representation wireframe color 0 0 0 Out 19 lt enthought mayavi modules surface Surface object at Oxcel017c gt Note A surface is defined by points connected to form triangles or polygones In mlab func 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 5 2 3D plotting functions 56 Introduction to Python for Science Release 1 5 2 5 Volumetric data In 20 In 21 In 22 In 231 Owne 24 3 mlela s CILE 2 Yo a mo ael aS S 043 3828041 3239204 31 values X x 0 5 yey Z z 2 0 mlab contour3d values lt enthought mayavi modules iso_surface IsoSurface object at Oxcfe392c gt This function works with a regular orthogonal grid 5 2 3D plotting functions 57 Introduction to Python for Science Release 1 Introduction to Python for Science Release 1 5 3 Figures and decorations Example docstring mlab mesh Plots a surface using grid spaced data supplied as 2D arrays 5 3
29. C_CONTIGUOUS True import pylab as pl F_CONTIGUOUS True OWNDATA False X YY m9 Cpanel 103110 03911017 WRITEABLE True ie info Soper 2 ZN ALIGNED True pl matshow r UPDATEIFCOPY False r_binned r reshape 5 2 5 2 sum axis 1 sum axis 1 But this does not mean another array shares the data pl mat show r_binned gt gt gt del a gt gt gt b flags C_CONTIGUOUS True F_CONTIGUOUS True OWNDATA False WRITEABLE True ALIGNED True UPDATEIFCOPY False The base data container is not cleared as long as there are views opened on it Applications With a mask gt gt gt a np arange 10 gt gt gt al array Tor 17 27 Sp LL Sp Ge Te Se 9 gt gt gt alla 2 0 0 gt gt gt a array 10 Lo 0 3 0 S O To Op 91 A view was created an array of shape 5 and all the elements were set to zero through Broadcasting of O to a 5 shaped array e In loops gt gt gt a np arange 30 reshape 3 10 gt gt gt a array II 07 Ty De oy Al 57 Gr Ty Bp S lO di 2254 13 4 i e Ly is 19 WO ee Aar 2a 29r al 2er AN gt gt gt from scipy signal import detrend gt gt gt for line in a line detrend line gt gt gt a array 0 0 0 0 0 0 0 0 O OJ 8 2 2 Reshaping striding Reshaping can be a special case of views ai p To understand this better let us consider what happens to the
30. Introduction to Python for Science Release 1 Gael Varoquaux April 28 2010 The workflow IPython and a text editor 1 1 Command line interaction 3 6 5 boy rd 1 2 Elaboration of the algorithm in an editor Introduction to the Python language 2L Basictyp s sse cp souge RRA A PERS 22 Control FloW ss se ae GR le he RE a eo A 2 3 Defining functions aa ds 24 Exceptions handling in Python 4 44 404 6 6 eGo Geos 2 9 Reusing code ss erae aak KEY AA 260 Mle imn Pyton escorial EIA e a E 2 Standard Library AA Core scientific modules 3 1 Num y array computing aooaa 6 o 54 44 Ho 3 2 Matplotlib scientific 2D plotting 3 3 Scipy numerical and scientific toolbox 2 Y Python patterns in neuro image 4 1 Images and Mask naana Gee ae RH GEE Pwo 4 2 Memory management pi RA 4 3 Masked arrays yo ewe AS OO 44 Dealing with labels sos a scs aos owe aeae ERS a i ao 3D plotting with Mayavi Dl Asmpleexample sss eosa ea ARA RA A 5 2 3D plotting functions A 5 3 Figures and decorations arriero SA TCG sies aa a 4 a ds se eS ee Debugging 6 1 Coding best practices to avoid getting in trouble A CeDUR Cr s soe dae Bek wog fe BE Be eh aE a ey O PINE sare he bade a e es a E ee Contents Introduction to Python for Science Release 1 6 4 Debugging sate ses ie AA a 67 7 Profiling Python code 68 t h O B Te meit a ie o o e o A Oe e da ok ie o e oO 68 Wier o c
31. Science Release 1 CHAPTER 1 1 2 Elaboration of the algorithm in an editor Create a file my_file py in a text editor Under EPD you can use Scite available from the start menu Under Ubuntu if you don t already have your favorite editor I would advise installing Stani s Python editor In the file add the following lines ls Misllo mole print s T h e WO r kf I OW I Pyt h O Nn a n d a text ed ito r Now you can run it in ipython and explore the resulting variables Tna 3 srun my file py Hello word In 4 s ue l4 sio wora In 5 Swhos Interactive work to test and understand algorithm Variable Type Data Info Python is a general purpose language As such there is not one blessed environement to work into and not only one way of using it Although this makes it harder for beginners to find there way in the beginning it makes it possible for age Hone word Python to be used to write programs in web servers or embedded devices In this introductory chapter we describe an interactive workflow with Python that is handy to explore and understand algorithms Note Reference document for this section From a script to functions IPython user manual http ipython scipy org doc manual html e A script is not reusable functions are e Thinking in terms of functions helps breaking the problem in small blocks 1 1 Command line interaction Start ipython In 1 print
32. alar types int float complex in 13 L2 In 4 type 1 Que Ss 3 QUEME ctype inte l Counting from the end in 517 Espert QUA Ss lt type ees gt In 14 1154 Outer ss In 6 type 1 0j Out 6 lt type complex gt Slicing in 15 iss in 1161 11 3 Ome Mei Tir 27 5 4 2 1 Basic types 5 Introduction to Python for Science Release 1 DO EA QUA MS S In iei 113 Sue MSI 13 A Syntax start stop stride e Operations on lists Reverse wm SA S In 20 r Omi 203 Sp 42 8 27 1 Append an item to r ine 21 r appends In 22 r AA I5 Ae 2 2 1l 2 5 Extend a list with another list in place In 23 l extend 6 7 In 24 1 Que Als EZ gt r lz 5 67 L Concatenate two lists A e el Quelle a A lly Sey Sey Sort r In 26 r sort In 27 Y OU AS BO 4 sS Note Methods r sort sort is a method of r a special function to is applied to r Warning Mutables Lists are mutable types rsort modifies in place r Note Discovering methods In IPython tab completion press tab 2 1 Basic types Introduction to Python for Science Release 1 In 28 r 2 add ro iaol r elass i AL re Contains Pe anoe paella Po iter ss r __delitem__ Pea hes Ge _ delslice t Fen ws Choe Ta T pee re eg Zo aL OMA NI r ge__ r new r getattribute__ r __reduce__ r getitem__ r reduce ex r getslice P
33. alue le 20 What s the mean across time not counting bad data masked_array data IT 0 1 0 1 0 Oh Oe TC SO e ndimage mean ndimage maximum ndimage maximum_position PERO 1 0 1 0 1 0171 mask means ndimage mean l labels label_im index range labels False True False False False False False False False False False False fill_value 1e 20 Clean up small connect components labels np arange labels i size ndimage sum blacks labels label_im index labels Note Much better than NaNs the above would not be possible for s dode in zp oe ae a Note Also good for thresholding maps if s lt 40 label_im label_im index O 4 3 Masked arrays 50 4 4 Dealing with labels 51 Introduction to Python for Science Release 1 CHAPTER 5 e Reassign labels np searchsorted labels np unique label_im 3D plotting with Mayavi e ndimage center_of_mass Maya gt gt gt ndimage center_of_mass label_im astype np float label_im astype np float index labels nan nan 4 3032 128391409622 8 642570 2611244989 6 035 1142831142836 24 910 apse y142 35 SA OS SL ISS Si SS 598492462 Sika 55 nan nan nan nan e ndimage find_objects slice_x slice y ndimage find_objects label_im 4 0 eye l slice_x slice_y pl imshow eye cmap pl cm gray 5 1 A simple example Warning St
34. art ipython wthread 4 4 Dealing with labels 52 53 Introduction to Python for Science Release 1 Mayavi Scene 1 riER MMOH Introduction to Python for Science Release 1 import numpy as np yp Y ma mepcle 21 03 103 1005 LOS 10S1005 1 r np sgrt x 2 yx x 2 2 Mpesin E from enthought mayavi import mlab mltab suert Zz weno seale smeo mlab outline mlab axes np mgrid 10 10 100 10 10 100j Create an x y grid going from 10 to 10 with 100 steps in each directions 5 2 3D plotting functions 5 2 1 Points In 1i In 2 In 3 cua As In 4 import numpy as np from enthought mayavi import mlab X Y Z value np random random 4 40 mlab points3d x y Z value lt enthought mayavi modules glyph Glyph object at Oxc3c7 95c gt 5 2 3D plotting functions 54 5 2 2 Lines In 5 mlab clf In 6 np linspace 0 20r 200 ma as mab lor Sc mo sta 1 mo cos 15 Out 7 lt enthought mayavi modules surface Surface object at Oxcc3eldc gt OEA 5 2 3 Elevation surface In 8 mlab clf ive EE Sp Y np monad oe 1011005 in L10 np sgre x12 y 4Z in il 2 nessin r e In 12 mlab surf z warp_scale auto Out 12 lt enthought mayavi modules surface Surface object at Oxcdb98fc gt 103 102110051 5 2 3D plotting functions 5
35. dex_error py 5 index _error 4 lst list foobar gt 5 prine kst lea sec 6 abs o U Smed Snipper to raise san Indexhrror 7 2 3 def index_error 4 lsr AS EEE oO aa 9 prisa ker sic 6 7 if _ name _ main 8 index error ipdb gt len lst ocio prine niist kenst M 6 2 The debugger 63 Introduction to Python for Science Release 1 Holo julie iim SIE 6 2 2 Debugger launch Situation You believe a bug exists in a module but are not sure where Launch the module with the debugger and step through the code in the debugger In 38 run d debug_file py xxx Blank or comment xxx Blank or comment Breakpoint 1 at Users cburns src scipy2009 scipy_2009_tutorial source debug_file py 3 NOTE Enter e vat tche moles pPpronpt LS start your scripte gt lt string gt 1 lt module gt Step into code with s tep ipdb gt step Call gt Users cburns src scipy2009 scipy_2009 tutorial source debug_file py 4 lt module gt i S D emwea sm Suomzescl da lema Le gt 4 We wy 5 Set a breakpoint at the load_data function ipdb gt break load_data Breakpoint 2 at Users cburns src scipy2009 scipy_2009_tutorial source debug_file py 12 ipdb gt break Num Type Disp Enb Where il breakpoint keep yes at Users cburns src scipy2009 scipy 2009 tuterial source debug_ 2 breakpoint keep yes at Users cburns src
36. e 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 In 10 reload demo 2 5 3 _ main__ and module loading A whole set of new functionnality File demo2 py In 6 from _ future import braces def print_a brian a T 2 5 2 Creating modules print a File demo py print Start if name _ main __ print_a 2 5 Reusing code 20 2 5 Reusing code 21 Introduction to Python for Science Release 1 Introduction to Python for Science Release 1 Importing it 2 6 File I O in Python In 11 import demo2 E b 2 6 1 Reading from a file In 12 import demo 00 eee Open a file with the open function Running it In 1671 Gp pen holy gral exe In 13 Srun demo2 In 68 fp b Out 68 lt open file holy_grail txt mode r at Oxealec0 gt a in 69 tp mo Class fp new fp fileno fp readline 2 5 4 Standalone scripts fp delactr fp _ _reduce__ SIA fp readlines o COG fp _ reduce ex__ Ep US aieiby fp seek if E 0 fp mod piso mite e Runni
37. e g custom error raising Warning Capturing and not raising exception can lead to difficult debuging 2 4 Exceptions handling in Python 19 in range 12 Introduction to Python for Science Release 1 Introduction to Python for Science Release 1 2 5 Reusing code o demo module Y 2 5 1 Importing objects P y print b In 1 import os A def print_al bras a T In 2 os print a Out 2 lt module os from lus Lin ppython2 6 los pyc gt In 3 os listdirt n Quel a E come y y asie t eet et acie Ee ype nms Importing it in IPython Acont rco Mt iow rst Y HUMIC LOOMS LS y python_language rst RSS ina si rales loss ty In 6 import demo In 7 demol MeExCepEmOms Est Type module OE low cSt Base Class lt type module gt index est SELLING Porm module demo from demo pPy Namespace Interactive And also File home varoquau Projects Python_talks scipy_2009_tutorial source demo py Doestring A demo module In 4 from os import listdir Importing shorthands In 8 demo print_a a In 5 import numpy as np Tn 9 demo print pP Warning b 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 from os import x Do not do it e Makes th
38. ef square data return dataxx2 Vector computing loops are replaced by vector operations on arrays In 2 Stimeit data np arange 1000 square data IOOVOO oops best Of 3 10 6 us per loop gt gt gt x np zeros 10 array TOn ss OE Ore D One gt gt gt x 0 1 gt gt gt X array ils OR One 0 OR Oey gt gt y xcopy gt gt gt y 0 2 gt gt gt X Or Oe Oor 0 OO Multidimensional arrays gt gt gt a np arange 10 gt gt gt a array LOr Sa OA a S Sp gt gt gt b np reshape a 2 5 gt gt gt b amray LLO Il 2 3 Al ES 7 ep Sl gt gt gt ble 1 amray PIP EN Creating arrays e With constants 3 1 Numpy array computing 32 Slicing Multidimensional traversing of arrays gt gt gt al 0 3 5 array 3 4 gt gt gt al 4 4 array 44 45 54 55 gt gt gt a 2 array 2 22 52 gt gt gt a 2 2 2 array 20 22 24 40 42 44 3 1 Numpy array computing 33 Introduction to Python for Science Release 1 An example calculating the laplacian Introduction to Python for Science Release 1 gt gt gt al 0 1 2 3 4 1 2 3 4 5 array 1 12 23 34 45 gt gt gt a 3 10 2 5 array 30 32 35 40 42 45 50 52 55 gt gt gt nask array 1 O 1 O O 1 dt ype bool gt gt
39. eries time_serie gives an in place operation memmapping np load np save time_series npy time_series time_series np load time_series npy mmap_mode r 49 Introduction to Python for Science Release 1 Introduction to Python for Science Release 1 i a e ndimage labels 4 3 Masked arrays 1 sp lena 200 300 2502 560 pl imshow l cmap pl cm gray Data with many dimensions parameters subject session ROI time data np ones 3 4 10 subject ROI time But missing data crapy data babies anyone bad_data np zeros data shape dtype np bool For subject 0 ROI 1 is outside of brain pad aatal I AS True Subject 1 moved between time 3 and 5 blacks 1 lt 80 bad_data 1 3 6 True pl imshow blacks cmap pl cm gray Mask the bad data masked arrays np ma good_data np ma masked_array data mask bad_data How many useful ROIs gt gt gt good _data sum axis 1 masked_array data MESA S20 3 0 3 0 38 0 3 0 3 0 3 0 3 0 3 0 4 0 4 0 4 0 4 0 4 0 4 0 4 0 from scipy import ndimage 250 AAG O Ao ag 40 0 A A label_im labels ndimage label blacks mask imshow label_im cmap pl cm spectral False False False False False False False False False False False False False True True True False False False False False False False False False False False False False False fill v
40. esna a a NA 68 To MMBC MOM 22 a a as e a Sak 70 8 Advanced numpy 71 Sl Broadcasting Ea nk Rk a A AN A a A A e ek a 72 Why Python 8 2 Vi DESTE de e Ro ke ORES OER EADEE SEP e ARKH EEK OS 75 8 3 a a 79 e Efficient coding what is the point of very fast simulations if it takes longer to write them than to run PAM AINE RING o a ae EAS AAA Asa gt 8 4 RobertbiKeta s nasty stide trick a da petpae ee eed Re aw Pade ee he ee AA 82 irin a e Full fledge non specialized programming language 9 pyflakes fast static analysis 83 e Communication code should read like a book A We hee ne oe cece nc Be ee ee ee eh mn ds ho eh tes oh a hes GP tes cds teed 83 e Code that we understand developing an intuition an understanding of the algorithms through exploratory 927 AE 83 coding and interaction oo EMACS oe ep a A E A A AR ss Ee E 84 Installing with distributions EPD http www enthought com products epd php e Python x y http www pythonxy com Resources Simple e In French Python for Science http dakarlug org pat scientifique html index html e Videos http www archive org search php query SciPy 202009 20tutorial e The Python tutorial excellent http docs python org tutorial Advanced e http docs scipy org e Python Scripting for Computational Science Hans Petter Langtangen Springer e Python Cookbook David Ascher Matt Margolin Alex Martelli O Reilly ii Contents 1 Introduction to Python for
41. h 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 wire frame or points or mesh or fancymesh Default surface resolution The resolution of the glyph created For spheres for instance this is the number of divisions along theta and phi Must be an integer Default 8 scalars optional scalar data scale_factor scale factor of the glyphs used to represent the vertices in fancy_mesh mode Must be a float Default 0 05 scale_mode the scaling mode for the glyphs vector scalar or none transparent make the opacity of the actor depend on the scalar tube_radius radius of the tubes used to represent the lines in mesh mode If None simple lines are used tube_sides number of sides of the tubes used to represent the lines Must be an integer Default 6 vmax vmax is used to scale the colormap If None the max of the data will be used vmin vmin is used to scale the colormap If None the min of the data will be used Example In 1 import numpy as np ma As ie taste m9 mejo 03110 9 91 310199 s 1051 In 3 x rx np cos theta In 4 y rxnp sin theta In
42. ingular_values sp linalg eigvalsh np dot X T X Minimize memory number of operations 7 3 Line profiler 70 71 Introduction to Python for Science Release 1 e Views and copies e Broadcasting e Fancy indexing Table of Contents 8 1 Broadcasting 8 1 1 Broadcasting definition Applying operators on arrays of different shapes e Adding a scalar and an array of course works gt gt gt import numpy as np gt gt gt a np ones 3 gt gt gt a avia ils ice ESO gt gt gt a a d arcay I 2a PAA Peale Introduction to Python for Science Release 1 gt gt gt a b Bye r Zey 1 array IIL Sa 5 lt Biss 3 Broadcasting rules e Element wize operations on arrays e Compare dimensions starting from last e Dimension of size 1 are extrapolated 8 1 2 Applications e Yet another way of avoiding loops e Decreases memory consumption Creating a 3D grid of size n MP SJrE ie ap y2 ap AZ e What about adding or multiplying two arrays of different shape gt gt gt b 2xnp ones 2 1 gt gt gt b arca TAIF ie zee hl 8 1 Broadcasting 72 8 1 Broadcasting 73 Introduction to Python for Science Release 1 Without broadcasting x yZ gt gt gt x y Z np mgrid 100 100 100 100 100 100 gt gt gt print x shape y shape z shape 2007 2007 200 2007 2007 200 2007
43. n 8 os system ls n Sony debug_file py demo2 py demo py demo pyc my_file py con E demo2 py demo2 pyc demo py my_file py pi_wallis_image py Walking a directory os path walk generates a list of filenames in a directory tree In 10 for dirpath dirnames filenames in os walk os curdir TEE for fp in filenames E print os path abspath fp Users cbhurns sre scipy2009 scipy 2009 tutorial scurce index rst swo Users cburns src scipy2009 scipy_2009_tutorial source view_array py swp Users cbhurns src scipyzZ009 scipy 2000 _twutorial scurce basie types rst J USers courns sre scipyZ0097 scipy 2009 tutorial source cont spy jUsers cbhurns sre scipy2009 scipy 2009 tuterial source control Flow rot Introduction to Python for Science Release 1 In 12 os environ PYTHONPATH quelda Users churns ere le lls Users churns src mito Ls Users cbhurns local lib python2 5 site packages usr local lib python2 5 site packages Library Frameworks Python framework Versions 2 5 lib python2 5 In 16 os getenv PYTHONPATH out reik 2s Users cburnis Ssrejurils 7 Users courns src nitoole 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 shut i 1 provides useful file operations e shutil rmtree Recursively dele
44. n operations on pathnames In 31 os listeli OS acu cata in 70 tp open Junk txt w Cumi omk a index rst 39w python_language rst swp view_array py swp OE Site eee _ templates MSasaLe des es y CEIM JD y SOmertol clon ise y fiSbuagqing CSE Make a directory rn 321 os mkdir C Junkar In 33 J nkdir in os listir osm curdi Out 2 gt True Rename the directory 2 7 Standard Library 26 In 71 fp close In 72 a os path abspath junk txt In 73 a Cue Slk 77Users courns src scipy200Sy7 scipy 2000 _ Lutcerial source junk Ext In 74 os path split a QuE A Users churns sre scipy2009 scipy 2009 tutorial sourcen Junk exte In 78 os path dirname a Que 18 Users cburas sre se1py2009 801py_ 2009 tutorials source In 79 os path basenanme a Ome SEE In 80 os path splitext os path basename a Out Som June EEE YO In 84 os path exists junk txt Out 84 True 2 7 Standard Library 27 Introduction to Python for Science Release 1 In 86 os path 1SftiLle J nk EtxE Out 86 True ranei osipati cies A is Out 87 False In 88 os path expanduser local Out 88 Users ebuens local In 9212 oc path Jonos path expandusen o SO Qut 9218 Users churns localspin Running an external command I
45. ng a script from the command line e EE A a ae a ae Pg erat iour e rp Mistri fp newlines fp truncate python demo2 py fos hash fp close fp next fp write b tpe imie fp closed fp read fp writelines a fpe iter fp encoding fp readinto fp xreadlines e On Unix make the file executable Close a file with the close method chmod uog x demo2 py In 73 fp close add at the top of the file In 74 fp closed usr bin env python Out 74 True e Command line arguments Can read one line at a time import sys In 69 first_line fp readline print sys argv In 70 first line Cue lro GUARD Allo daffy English kaniggets and Monsieur Arthur king who is n python file py test arguments file py test arguments Or we can read the entire file into a list Note Don t implement option parsing yourself Use modules such as optparse l In 75 fp open holy_grail txt In 76 all lines fp readlines Exercise In 77 all_ lines Implement a script that takes a directory name as argument and returns the list of py files sorted by name Out 77 length GUARD Allo daffy English kaniggets and Monsieur Arthur King who is n Hint try to understand the docstring of list sort i afraid of a duck you know So we French fellows out wit you a n second time n END The
46. o Teepe gt Po noge ESAS SCI NS io erm Dictionaries Dictionaries are a mapping between keys and values In 22d Mara Mo ies Ve in 130 be QUA SON M2 In 31 dai a a In 32 d Qu E EA O e In 33 d keys QUES Si fat ee wal Waal In 34 d values Out Sa Ae ee ada SIS att setitem__ setslice_ _ Ssizeof__ SER subclasshook_ append SOU E extend index insert Pop remove reverse 5 SOME lO 13 Ue ON Warning Keys are not ordered Note Dictionnaries are an essential data structure For instance to store precomputed values Strings e Different string syntaxes a Mine a MENS st a Mine and not hia a Mine and Chris stu 2 1 Basic types Introduction to Python for Science Release 1 e Strings are collections too in 35 s eython as ool Ins soi SA Owe lse la AE e And they have many useful methods Introduction to Python for Science Release 1 2 2 Control Flow Controls the order in which the code is executed 2 2 1 if else In 37 s replace cool powerful QUES 397 Python soy Stadt Warning Strings are not mutable e String substitution o Ta 38 An integer sl a oO ia another string S gt OS inci ouesse An integer lila theat Of TOCCO Another String esting In 1 if 2 2 print Totology RO Oko
47. o a function python passes 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 modifies the caller s variable In 117 def setx y TETI x y a elas print x is 3d x In 118 setx 10 x IS 110 In 120 x Oise LAO e 5 This works In 1 def foo x y x 23 y append 42 print x is print y is o o K A alo ap Sr In 2 a II S immutable variable In 3 b 99 mutable variable In 4 foo a b x Gls 2S y as 19 422 In 5 print a TT In 6 print b mutable variable b was modified D997 A2 Functions have a local variable table Called a local namespace The variable x only exists within the function foo 2 3 Defining functions 14 In 121 def setx y ORGA global x sine Ries x y e prine 7s ais Sd ox In 122 setx 10 x is LO In 123 Owe ls ein x 2 3 6 Variable number of parameters Special forms of parameters e args any number of positional arguments packed into a tuple e kwargs any number of keyword arguments packed into a dictionary In 35 def variable_args args x kwargs Beene preine args io aes ee print kwargs is kwargs 2 3 Defining functions 15 Introduction to Python for Science Release 1 Int
48. ofiler 41 0 000 0 000 0 000 0000 len 13 0 000 0 000 0 000 0000 max Useful when you have a large program to profile 9 0 000 0 000 0 000 0 000 method view of numpy ndarray objects 28 0 000 0 000 0 000 OOO metano get oft dilet objects 14 0 000 0 000 0 000 0 000 linalg py 36 isComplexType a N 23 0 000 0 000 0 000 0 000 issubclass from ica import fastica Y 0 000 0 000 0 000 0 000 linalg py 92 _fastCopyAndTranspose 14 0 000 0 000 OOOO 0 000 method Mast ype of numpy ndarray objects EE de 14 OOOO 0 000 0 000 0 000 linalg py 49 _realType 68 7 2 Profiler 69 Introduction to Python for Science Release 1 CHAPTER 8 7 0 000 0 000 0000 0 000 numpy core multiarray _fastCopyAndTranspose 7 0 000 0 000 07000 0 000 linalg py 31 _makearray 7 0 000 0 000 0 000 0 000 linalg py 110 _assertSquareness 1 0 000 0 000 0 000 0 000 lapack py 63 get_lapack_funcs iL OOOO OOOO 0 000 0 000 lapack py 48 find_best_lapack_type 7 0 000 0 000 0 000 0 000 linalg py 104 _assertRank2 15 0 000 0 000 0 000 0 000 min 7 0 000 0 000 0 000 0 000 method __array_wrap__ of numpy ndarray objects 6 0 000 0 000 0 000 0 000 defmatrix py 521 getA Advanced numpy 7 3 Line profiler profile def test data np random random 5000 100 u S v linalg svd data pea np dot u 10 data Optimising numpy code results fastica pca T whiten False 1 avoiding loops 2 algorithmic optimisation eg not
49. oll lo OS E f interpolate interpld x y kind cubic X np linspace 0 9 100 jo alot OX GECK 3 3 Scipy numerical and scientific toolbox 45 Introduction to Python for Science Release 1 3 3 6 Interlude import scipy as sp import numpy as np import pylab as pl 1 sp lena iL 11239239 2058 1627 205 t pl imread tarek jpg ES ites Se eas eae esi t t sum axis 1 pi figure pl imshow t Cmap pl cm gray plikasis Conran pl figure pl imshow 1 cmap pl cm gray Eras oz t t astype np float t max ct a 1 l astype np float 1 l max pl figure pl imshow t 1 cmap pl cm gray llaxars Conr 3 3 Lineaire Algebra whitening Lena rows weight columns np linalg svd 1 full_matrices False 1_ np dot rows columns Lena np dot rows columns Laplacien Lena 3 3 Scipy numerical and scientific toolbox 46 Introduction to Python for Science Release 1 3 3 8 FFT Low pass filtering import numpy as np import pylab as pl from scipy import fftpack t np arange 0 10 0 1 n m9 Sila MO JOE 37 np ecos 10 aja Dalia Onley DO E E freq fftpack fftfreq len s d 1 IIE repack 5 ak ee 8 fft np abs freq gt 1 0 s fiteack rte kt pl plot t s_ linewidth 3 3 3 9 Signal processing Detrend import nump
50. or index item in enumerate words RS print index item 2 2 Control Flow 11 Introduction to Python for Science Release 1 aa ias cta ato FL e In 15 for key val in d iteritems ns print Key s has value s key val Key a has value 1 Key c has value 1j Key b has value 1 2 2 2 6 List Comprehensions In 16 i 2 for i in range 4 QUA lels TO it 4 S Exercise Compute the decimals of Pi using the Wallis formula The Pi Wallis Solution 2 3 Defining functions 2 3 1 Function definition In 56 def foo Meee prine 21m Boer unto In 57 foo En feo bunct Lon 2 3 2 Return statement Functions can optionally return values In 6 def area radius return 3 14 a radius radius 2 3 Defining functions 12 Introduction to Python for Science Release 1 In 8 area 1 5 Owie Se 7 06249999999999995 Note By default functions return None 2 3 3 Parameters Mandatory parameters positional arguments In 81 def double_it x se eat return x x 2 In 82 double_it 3 Quise In 83 double_it TypeError Mraceback mosti recent ea Ala ste Users cburns src scipy2009 scipy_2009_ tutorial source lt ipython console gt in 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 a return x x 2 In 85 double_it
51. rizon np arange 1 2 np newaxis np arange 5 Bootstrapping arras ay 47 3 lt 17 Op 9 07 6 Oley Key Sr Fp 2 8115 We have a vector a Two broadcastings one in x coordinates horizon np arange 1 2 np newaxis and the second one between the x gt gt gt a np arange 20 reshape 2 10 and the y coordinates gt gt gt a array oO iy 2 Sr Al Siy 6 ie er 9 LO il 12 13 12 15 16 17 La TaT Drawback of these techniques costly in memory We want to drawn three times 10 vectors out of a 8 3 Fancy indexing 80 8 3 Fancy indexing 81 Introduction to Python for Science Release 1 3 4 Robert Kern s nasty stride trick Warning Parents guidance not for underaged children Problem Sliding average but we don t want copies We want to take a sliding average of a on a window of size 2 CHAPTER 9 AE pyflakes fast static analysis gt gt gt a np arange 8 gt gt gt a array CIOT a a a Fi Ss a strides ap We are going to create improbable strides and shapes numpy 1 2 gt gt gt from numpy lib import stride_tricks e Fast simple gt gt gt b stride tricks as_strided a shape 2 7 strides 4 4 gt gt gt b ama 0 1 e Detects syntax errors missing imports typos on names 9 1 In kate Menu settings gt configure kate gt External Tools add pyflakes Application External Tools s E 4
52. roduction to Python for Science Release 1 In 36 variable_args one two x 1 y 2 z 3 ango is one two Exercise Kwargs is y 2 x 1 z 3 Implement the quicksort algorithm as defined by wikipedia function quicksort array a var list less greater 2 3 7 Docstrings eee al return array Documention about what the function does and it s parameters General convention select and remove a pivot value pivot from array i l for each x in array In 67 def funcname params if x pivot then append x to less SI Concise one line sentence describing the function else append x to greater id return concatenate quicksort less pivot quicksort greater ES Extended summary which can contain multiple paragraphs wo cube 7 function body The Quicksort Solution pdas pass 2 4 Exceptions handling in Python In 68 funcname Type UMC Eom Basie Glass lt rype funcklon 24 1 Exceptions Serin ROLM lt function funcname at 0xeaa0f0 gt Namespace Interactive File sers Cburns sxc scupy 2009 2227 lt ipyehon console gt a ae eyo O Definition funcname params Docstring are PL 100 Concise one line sentence describing the function ZeroDivisionError integer division or modulo by zero Extended summary which can contain multiple paragraphs TA 2I et er TypeError unsupported operand
53. ta 8 gt 9 10 ipdb gt p rannad X Fa as nos aE data append x return data ipdb gt down gt Users cburns src scipy2009 scipy_2009_tutorial source debug_file py 9 parse_data 8 oe X ala Cea Sicrslinc js 4 e gt 9 data append x 10 return data Wolo list 4 www 5 6 def parse data data string 7 data 8 Lor 2 alm data sering sli C gt 9 data append x 10 return data 11 2 12 def load_data filename LS fp open filename 14 data_string fp read ipdb gt You can also walk up and down the call stack with u p and d own Hodes lu 4 5 6 7 8 gt 9 10 11 2 12 1S 14 ipdb gt up SE def def parse_data data_string data Ove e aa data Sitio olle Y 2 amp data append x return data load_data filename fp open filename data_string fp read gt Users cburns src scipy2009 scipy_2009_tutorial source debug_file py 16 load_data 15 vite 17 anodised 11 2 12 13 14 15 gt 16 7 18 19 20 Bil SE def LE Om Close return parse_data data_string load_data filename fp open filename data_string fp read fp close return parse_data data_string _ name _ _ main _ data load_data exercises data txt print eee min data 10 20 o ie o T o maa Prime max sh max data 61 30 6 2 The debugger 66 6
54. te a directory tree e shutil move Recursively move a file or directory to another location e shutil copy Copy files or directories 2 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 ma r9 cule col 16 suce Cut listo qe nk ee igen yams Ie eae Environment variables In 9 import os In 11 os environ keys Out aid ee FSLDIR TERM PROGRAM VERSION FSLREMOTECALL USER HOME PATH IBS ALY ASHELLE EDITOR WORKON_HOME PYTHONPATH 2 7 Standard Library 28 2 7 4 sys module system specific information System specific information related to the Python interpreter e Which version of python are you running and where is it installed Ia 117 sys Pplatrorm cuci a cera In 118 sys version cue risik ara ae Pep 22 20089 Oe n GCG 4502 Apple Computer Ine buildi sssr In 119 sys prefix Out 119 Library Frameworks Python framework Versions 2 5 List of command line arguments passed to a Python script In 100 sys argv out Mook 1 Uscrs ebueas local bln ipython 2 7 Standard Library 29 Introduction to Python for Science Release 1 sys path is a list of strings that specifies the search path for modules Initialized from PYTHONPATH In 121 sys path
55. tive representation within a system Constants algorithms etc e Try to limit interdependencies of your code Loose Coupling e Give your variables functions and modules meaningful names 6 2 The debugger A debugger allows you to inspect your code interactively Specifically it allows you to e View the source code e Walk up and down the call stack e Inspect values of variables Introduction to Python for Science Release 1 e Modify values of variables e Set breakpoints Ways to launch the debugger 1 Postmortem launch debugger after module errors 2 Enable debugger in ipython and automatically drop into debug mode on error 3 Launch the module with the debugger 6 2 1 Postmortem Situation You re working in ipython and you get a traceback Type debug and drop into the debugger 62 In 6 run index_error py IndexError Traceback most recent Call last Users cburns src scipy2009 scipy_2009 tutorial source index_error py in lt module gt 6 7 if _ name _ main gt index_error 9 10 Users cburns src scipy2009 scipy_2009 tutorial source index_error py in index error 3 def index _error 4 se lise V ooloanay y gt 5 prine se lea Use 6 7 if _ name _ main IndexError list index out of range WARNING Failure executing file lt index_error py gt In 7 debug gt fUsers cburns sre scipy2009 scipy_2009_tutorial scurce in
56. type s for int and str 2 3 8 Functions are objects me A 2 0 Functions are first class objects which means they can be In 4 d 3 e assigned to a variable e an item in a list or any collection KeyError 3 e passed as an argument to another function Tie A a In 38 va variable_args In 6 1 4 In 39 va three x 1 y 2 IndexError list index out of range args is V rhres kvaropo y 8 2 3 1 In 7 l1 foobar Ateributekrror ibt obect has no attribute Foobar 2 3 9 Methods Different types of exceptions for different errors Methods are functions attached to objects You ve seen these in our examples on lists dictionaries strings etc 2 3 Defining functions 16 2 4 Exceptions handling in Python 17 Introduction to Python for Science Release 1 2 4 2 Catching exceptions try except Introduction to Python for Science Release 1 In 8 while True id PA enews break Seine except ValueError Please enter a number a That was no valid number Try again Please enter a number 1 In 9 x Owe Oa 1 try finally E x int raw_input Please enter a number X seeni printi ihat vas me vello aude May again o Ee SEC x int raw_input Please enter a number Be Gag anales lle setae fOicalione 7 Winewi lt yo gue you inputa DD In 14 LBZ print sorted AS 279 2 4 3 Raising exceptions
57. uction to Python for Science Release 1 O Dl quien E 25 4 3 2 1 3 3 Scipy numerical and scientific toolbox scipy is mainly composed of task specific sub modules cluster Vector quantization Kmeans fftpack Fourier transform integrate Integration routines interpolate Interpolation 10 Data input and output linalg Linear algebra routines maxentropy Routines for fitting maximum entropy models ndimage n dimensional image package odr Orthogonal distance regression optimize Optimization signal Signal processing sparse Sparse matrices spatial Spatial data structures and algorithms special Any special mathematical functions stats Statistics 3 3 1 IO Load and save matlab files gt gt gt from scipy import io gt gt gt struct io loadmat file mat struct_as_record True gt gt gt jo savemat file mat struct See also Load text files 3 3 Scipy numerical and scientific toolbox 42 Introduction to Python for Science Release 1 np loadtxt np savetxt e Clever loading of text csv files np genfromtxt np recfromcsv e Fast an efficient binary format np save np load 3 3 2 Optimization e Finding zeros of a function gt gt gt def f x eee return lt 4 55 O gt gt gt from scipy import optimize gt gt gt optimize fsolve f 1 2 SAAS ESAS AS CAES e Curve fitting import numpy as np import pylab as pl
58. x y z 6ms e Memory x y z 1 6Kb r 64Mo and one 64Mo temporary array gt 120Mb e 16 million operations numpy a structured view on memory with associated operations e identical data type dtype e fast indexing e views and copies e costless reshape e shape aware operations broadcasting 3 2 Matplotlib scientific 2D plotting Matplotlib provides a matlab like plotting interface pylab Note Reference the documentation is excellent http matplotlib sourceforge net 3 2 Matplotlib scientific 2D plotting 39 Introduction to Python for Science Release 1 Introduction to Python for Science Release 1 3 2 1 Lines import numpy as np import pylab as pl from scipy special import jn x np linspace 5 15 100 for i in range 10 Y Jali x plsplot x y label 7_5157 3 1 pl title Fonctions de Bessel pl legend Fonctions de Bessel 3 2 3 Points import numpy as np import pylab as pl X Y value np random normal size 3 50 pl scatter x y np abs 50 value c value 5 4 3 3 2 2 2D arrays 2 import scipy as sp import pylab as pl 0 l sp lena pl imshow l cmap pl cm gray l Eras Orr 0 15 10 05 00 05 1 0 15 2 0 2 5 3 2 4 Vectors import numpy as np import pylab as pl x Y mo moridii Skor S a 3 2 Matplotlib scientific 2D plotting 40 3 2 Matplotlib scientific 2D plotting 41 Introd
59. y as np import pylab as pl from scipy import signal t np linspace 0 5 100 x t np random normal size 100 pl plot t x linewidth 3 pl plot t signal detrend x linewidth 3 3 3 Scipy numerical and scientific toolbox 47 Introduction to Python for Science Release 1 e Filtering Ground truth Noisy observation l sp lena 200 100 150 150 1 float 1 max l g 1 1l np random normal size l1 shape Ground truth Noisy observation Gaussian filter Median filter Wiener filter Gaussian filter ndimage gaussian_filter g 1 6 Signal medfilt2d g 5 Signal wiener g 5 5 3 3 Scipy numerical and scientific toolbox 48 CHAPTER 4 Python patterns in neuro image 4 1 Images and Mask An fMRI dataset 4D array x y Zz t im np random random er 9r 40 111 A mask ROL or brain 3D array x y Z mask np random random 8 9 10 gt 5 Corresponding time series 2D array voxel t time _ series im mask 4 2 Memory management In place operations time series time _series mean axis 1 np newaxis time _series time _series std axis 1 np newaxis For loops rather than axis from scipy import signal for time _serie in time series time _seriel signal detrend time_serie Note time_serie is a view on time_s

Download Pdf Manuals

image

Related Search

Related Contents

MANUAL DEL USUARIO  1 防耐火実験棟柱用加熱試験炉外4件(10)保守点検  HF180 - Koenig  nVision NVO2002 battery charger  Sistema de transmisión trasero    SUN ODYSSEY 45 C - Chantier Naval JEANNEAU  Human HSP27 ELISA Kit  

Copyright © All rights reserved.
Failed to retrieve file