Python Scientific

所需积分/C币:38 2018-07-24 10:13:22 9.63MB PDF
收藏 收藏 1

Python Scientific lecture notes Release 2012.2 Getting started with Python for science Contents Python Scientific lecture notes, Release 2012.2 CHAPTER 1 Compiled languages: C, C++, Fortran, etc. Advantage Very fast. Very optimized compilers. For heavy computations. it's difficult to outperform these Stme very oplimizetl scienlific libraries have been wril len for these languages. Ex: blas (veclor/malrix Scientific computing with tools and Painful usage: no interactivity during development, mandatory compilation steps, verbose syntax(& 11,; ctc ) manual memory management(tricky in C). These arc difficult languages for non com workflow puter scicntists Scripting languages: Matlab y rich collection of libraries with numerous algorithms. for many different domains. Fast execution ausc these libraries are often written in a compiled language Pleasant dlevelopment environrnent: comprehensive and well organized help, inlegralecl editor, elc. authors Fcrnando Perez, Emmanuclle gouillart, Gacl Varoquaux Commercial support is available 1.1 Why Python? Base language is quite poor and can become restrictive for advanced users Not frcc 1.1.1 The scientist's needs Other se ript languages: Scilab, Octave, Igor, R,I, etc Get data(simulation, experiment control) adval · Manipu Open-source,frcc,or at least cheaper than Matlab. Visualize results. to understand what we are doing Some features can be very advanced (statistics in R, figures in Igor, etc.) Communicate on results: produce figures for reports or publications, write presentations fewer available algorithms than in Matlab, and the language is not more advanced 1.1.2 Specifications 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 Rich collection of already existing bricks corresponding to classical numerical methods or basic actions: we What about python? don't want to re-program the plotting of a curve, a Fourier transform or a fitting algorithm. Dont reinvent he wheel Atlvanlayes Easy to learn: computer scicncc neither is our job nor our cducation. We want to be ablc to draw a curvc, Very rich scientific computing libraries(a bit less than Matlab, though) smooth a signal, do a Fourier transform in a few minutes Well-thought language, allowing to write very readable and well structured code: we"code what we Easy communication with collaborators, students, customers, to make the code live within a labo or a company: the code should be as readable as a book. Thus, the language should contain as few syntax Many libraries for (other tasks than scienlific ctrmpuliny(weh server managerment, seri symbols or unneeded routines that would divert the reader from the mathematical or scientific understandin Free and open-source software, widely spread, with a vibrant community. 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 Drawback A single environment/language for everything, if possible, to avoid learning a new software for each new less pleasant development environment than, for example, Matlab. (More geek-oriented) Not all the algorithms that can be found in morc specialized software or toolboxcs 1.1.3 Existing solutions Which solutions do the scientists usc to work? 1.1. Why Python? Python Scientific lecture notes Release 2012.2 Python Scientific lecture notes, Release 2012.2 1.2 Scientific Python building blocks 1.3 The interactive workflow: IPython and a text editor Lnlikc Matlab, scilab or R, Python does not come with a prc-bundled sct of modules for scicntific computing Interactive work to test and understand algorithm: In this section we describe an interactive workflow with Bclow arc the basic building blocks that can be combined to optain a scientific-computing environment Python that is handy to explore and understand algorithms Python, a generic and Modern computing language Python is a general-purpse language. As such there is not une blessed env irunenment Lo work into, and not unly Python language: data types(string, in=), flow control, data collections (lists, dictionaries), pat- 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 terns. etc Modules of the standard library Note: Rcfcrencc document for this scction A larye number of speciali/edl m(lules (r applicalions willen in Pylhon: web protocols, web franne: IPythun user manual: htlp: /ipython. org/ipython-doc /lev/inlex. html t∴.… and scientific conputing Development tools(automatic tests, documentation generation 1.3.1 Command line interaction Start -cython In [1I: print('He' lo wcrId'h Gelling he IpYthon,anadvancedPythonshell In [2]: print: I provides powerful numerical arrays objects, and routines to manipulate them. builtin function or methed Base Class <=ype 'builtin_functicn_cr_method'> tEng上oxm: <built-in function print> Scipy high-levcl data processing routines. Optimization, regression, interpolation, ctc a∈ Espace Python builtin Docstring nt(va⊥u sep=’',end=n’,ti⊥e=sys. stdout) Prints the vales to a stream, or to ays stdout by default optional keyword arguments C file: a file--ike cbject (stream:: defaults to the current sys. stdout sep: string inserted between values, default a space enc: string appended after the⊥ ast value; defau⊥ t a new⊥ine 0.036 1.3.2 Elaboration of the algorithm in an editor Matplotlib:2-dvisualization"publication-ready"plotshttpi/ Create a file my_ file. py in a text editor. Under EPD. you can use Scite. available from the start menu. Under thon(x, y). you can use Spyder. Under Ubuntu, if you don t alrcady have your favorite editor, we would ady ng Stani's Python editor. In the file, add the following rint(s) Now, you can ruin it in ipython and explore the resulting variables f:le 工n[4]:s u-[4]:′He11 o word Daza/ info Mayavi:3-dvisualization 1.2. Scientific Python building blocks 1. 3. The interactive workflow: IPython and a text editor Python Scientific lecture notes Release 2012.2 CHAPTER 2 From a script to functions While it is tempting to work only with scripts, that is a file full of instructions following cach 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 The Python language authors Chris Burns, Christophe Combelles, Emmanuelle Goullart, Gael Varoquaux Python for scienTific compuLing ye introduce here the Python language. Only the bare minimum necessary for getting started with Numpy nd scipy is addressed here. To learn more about the language, consider going through the excellent tutorial http://docs.pythonorg/tutorial.Dedicatedbooksarealsoavailablesuchas p python Python is a programming language, as are C, Fortran, BASIC, PHP, etc. Some specific features of Python are as follows an interpreted(as opposed to compiled) language. Contrary to e. g. C or Fortran, one does not compile Python code before executing it. In addition, Python can be used interactively: many Python interpreters 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 vcry readable language with clcar non-vcrbosc syntax a language for which a large variety of high-quality packages are available for various applications, from a language very easy to interface with other languages, in particular C and C++ Some other features of the language are illustrated just below. For example, Python is an object-oriente language, with dynamic typing(the same variable can contain objects of different types during e course of a Seehllp://www.python.ory/ahout/forImore:informationabtuldistinguishingfealuresofPython 1. 3. The interactive workflow: IPython and a text editor Python Scientific lecture notes Release 2012.2 Python Scientific lecture notes, Release 2012.2 2.1 First steps 22 Start the Ipython shell (an enl ve Python shell CoMplex y typing"ipython"from a Linux/Mac terminal, or from the windows cmd shell, >>> a. real or by starting the program from a menu, e.g. in the Python(x, y)or EPD menu if you have installed one of If you don' t have Ipython installed on your computer, other Python shells are available, such as the plain python shell started by typing""in a terminal or the Idle intcrprctcr. However, we advise to use the Ipython shell Booleans becausc of its enhanced fcaturcs, especially for interactive scicntific computing Once you liave: Slarlexl Ihe: interpreter, lype alse >>>test=(3>4) >> print "Fello, world! >> test He⊥⊥c,wor⊥a >> type(test h The mcssagc"Hello, world! is then displayed. You just executed your first Python instruction, congratulations! oco1'> Tu gel yourself slarlecl, lype the following slack of instructions A Python shell can therefore replace your pocket calculator, with the basic arithmetic operations +,-,*,/, >>>a (modulo) natively implemented >>> ype(b) >> print b 1024 >>>ab > 上 >> type (b) Scalar types: int, float, complex, boo 七 >>>type(1) >>>b+b <type he11ohe11。′ >>>type(1.) >>2+b type′f1oa he11ohe110′ >>>type(1.+0 <type complex> Two variables a and o 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 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 cerlain lype, anI a secondi poinl in line, il can he equal Io a value: tif a differenl lype. b was firsI etual 1o) an Iype conversion: leyer, but it he came eual io a string when il was assigned the value 'hello. Operatitris (n integers(C=2*a) >>>10at( are coded natively in Python, and so are some operations on strings such as additions and multiplications, which amount respectively to concatenation and repetition 2.2.2 Containers 2.2 Basic types ython provides many efficient types of containers, in which collections of objects can be stored 2.2.1 Numerical types Lists Integer A list is an ordered collection of objects, that may have different types. For example >>>1+1 >>1=[1,2,3,4,5 >>a三 >>>type(1) type′1ist> Floats Indexing: accessing individual objects contained in the list 2.1. First steps 2.2. Basic types Python Scientific lecture notes Release 2012.2 Python Scientific lecture notes, Release 2012.2 >>>1|21 ,2,3,4,5,6 >>>1.pop() Counting from the end with negative indices [-,2,3,4,5 >>>1[-1 >>>1.extend([b, 71)# exte.d l, in-place >>1 >>>1[-2 ,2,3,4,5:6,7 >>>11[:-2] >>>1 Warning: Inlexing staris at o(as in C), TIOI al. 1(as in Fortran or Mallah) Slicing: ol g sublists of regularly-spaced elements Reverse 1 >>>1 >>r=1[::-11 [1,2,3,45] >>>1[2:4 Concatenate anl repeal list Warning: Note that l [start: stop] contains the elements with indices- such as starz<= i stor >>> (i ranging frim st art lo stop-1). Therefore, 1 [st art: stor] has st op-start )eleMents 「5,4,3,2,1,1 All slicing parameters are optional Sort r(in-placc) 1「3:1 >>>1[:3 >>1[::2 [1,3,5] Note: Methods and Object-Oriented Programming Lists are mutable objects and can be modified The notation r. method()(r sort(), r append(3),L pcp())is our first example of object-oriented programming(OOP). Being a list, the object r owns the method fur. ct ion that is called using the notation >>>1[0]=78 No further knowledge of ooP than understanding the notation. is necessary for going through this tutorial 28,2,3,,51 >>>1[2:41= >>>1 Note: Discovering methods [28,2,3,8,5 In IPython: tab-completion(press tab) Note: The elements of a list may have different types r,. iadd r. setattr r. setter >>>1=[3,2,he1lc r. contains r. init r. setline >>>⊥ r. delattr iter sized [3,2,"he11o’] delitem >>>1[1],1[2 r. deslime r. subc ashok r, mul count For collections of numerical data that all have the same type, it is often more efficient to use the array typ r. format r extend provided by the numpy module. A NumPy array is a chunk of memory containing fixed-sized items. with ne v r,index opcrations arc pcrfomcd through specialized C functions instcador. nts are regularly spaced in memory and mor NumPy arr r.getattribute r.reduce hon loops r.getter r. reduce ex r.poE getsiice rEpr r. reove reversed Python offers a large panel of functions to modify lists, or query them. Here are a few examples: for more details, reve r, hash rr:u⊥ r. sort seehttp:/docs.pythonorg/tutorial/datastructures.html#more-on-lists Add Strings >>>1,aped(5) >>>1 Different string syntaxes(simple, double or triple quotes) 2.2. Basic 2.2. Basic types Python Scientific lecture notes Release 2012.2 Python Scientific lecture notes, Release 2012.2 s-′He11o, how are you? Note: Python offers advanced possibilities for manipulating strings, looking for pattens or format s-"Hi, waat'e up ting. Due to lack of time this topic is not addressed here but the interested reader is referred to s=/He_lo -ripling the quotes allcws the http:/docs.pythonorg/library/stdtypes.html#string-methodsandhttp:/idocs.pythonorg/library/string.html#new f the string to span more than cne ii:ze string-formatting what's tn? · String substitution: In [11: 'Hi, wha='s up? >>>'An ir: tege: i; a floa: 8f, another string: ss,(1,0.1,'string') An integer: 1; a float: C. IC00C0: anoth File <ipy=hon console>, line 1 Hi,wha=′sup?′ >>>⊥=1 >> filename proce3s-nc_of dat aset_$03d. txt 2 SyntaxErIOI valid syntax processing_of_dataset__02.-xt The newline character is \n, and the tab character is \ t Strings are collections like lists. llence they can be indexed and sliced using the same syntax and rules Dictionaries Indexing A dictionary is basically an cfficicnt table that maps keys to values. It is an unordered containcr >>>a="he1。" >>>a[0 >>te1「’ francis-591J >>>a [ sebastian francis:5915,emmanuel >>>a[-1 >>tel’ sebastian’ 578 remember that negative indices correspond to counting from the right end ∈ bastian fra:c em.anuelle'I >> tel values( L518,5915;5/52. >>>a-whel-o, wor la! >>>′ francis′inte1 >>>al3:6 f 3rd to eth excluded) elements: eiements 3, 4 True >>>a[2: 10: 2.f Syntax: alstart: stop: skepI It can be used to conveniently store and retrieve values associated with a name( a string for a date. a name, etc.) Seehttp://docs.pythonorg/tutorial/datastructures.htmltdictionariesformoreinformation >>>a[:: 5. f every rhree characters, from heginning to end hl A dictionary can have keys(resp. values)with different types >>>d={a:1;b:2,3:"he11o) Accents and special characters can alst he handled in Unic xle strings (se'e http://docs.pythonorg/tutorialintroduction.html#unicode-strings) 1,3:"he11o’,'b A string is an immutable object and it is not possible to modify its contents. One may however create new strings More container types In [53]: a="hello, world. In[54l:al.=’z tuples TypeError Traceback (most recent call Tuples are basically immutable lists. The elements of a tuple are written between parentheses, or just separated as七 by >>>t=12345,54321,"he⊥⊥o! /hone/gou-llar/travail sg=/2009/alks/dakar pythor /ccurs/gael/essai/source/< thon console> _n<mcdule>( >>>t[C 12345 >>七 TypeError:S bject does not support item In[55l:a. replace:'1′,"z′,1 >>>u=(0 ut[55l:e2⊥c,or1d In [56]: areplace:'1,'z) Out [56: c220, worzd! dered, unique items Strings have many useful methods, such as a. replace as seen above. Remember the a. object-oriented >>>s notation and use tab completion or help(str) to search for new methods .difference(( 2.2. Basic 2.2. Basic types Python Scientific lecture notes Release 2012.2 Python Scientific lecture notes, Release 2012.2 In [6]: id(a A bag of Ipython tricks out[6]:138641675 Several Linux shell commands work in Ipython, such as Is In [7]: a[:]=[l, 2, 31# Modifles ch ject in place In [8]: a out[8]:[1,2,3 To get help about objects, functions, etc., type hc lp ob jcct. Just type helpo to get started In[9]:a(a) Use tab-completion as much as possible: while typing the beginning of an objects name(variable Out [9]: 138641616* Same as _:7 Out i57, yours will differ function, module), press the Tab key and Ipython will complete the expression to match available names.If many names are possible, a list of names is displayed the key concept here is mutable vs immutable History: press the up(resp. dow arrow to go through all previons (resp. next) instructions starting ih the expression on lhe lent of the cursor (pul the cursor at the beginning of the line to go through mutable objects can be changed in place previ(llIs cOIITlanIds) immutable objects cannot be modified once created You may log your session by using the Ipython"magic command"%ologstart. Your instructions will be saved in a file, that you can execute as a script in a different session A very good and detailed explanation of the above issues can be found in David M. Beazley's article ' types and Objects in Pytho In [1]: -ocs=ar- commands.log Activating auzc-logging. Currert session state plus future input 2.4 Control Flow saved Filename commands. Ing Made Controls the order in which the code is executed Output logging Fals Raw input1cg:上alse False 2.4.1 if/elif/else ac⊥e 1]:if2*2 print ' Obvious 2.3 Assignment operator Obvious y relerence says Blocks are delimited by indentation Assignment statements are used to (re )bind names to values and to modify attributes or items of Type: the following lines in your Python inlerpreleT, and be careful Io respec L the: indentation depth. The Ipythi mutable objects shell automatically increases the indentation depth after a column: sign; to decrease the indentation depth, go In short, it works as follows(simple ass four spaces to the left with the Backspace key. Press the enter key twice to leave the logical block In [2:a 1. an expression on the: righi hantl side is evalualed, the correspunliny objecl is trealed/obtain 2. a name on the left hand side is assigned, or bound, to the r.h.S. object 工n[3l:ifa--1 a single object can have several names bound to it print(2) e⊥se 工n[1l:a=[1 print("A1ct’) In [2]: b=a In [3]:a Cu=[3]:[1,2,3] In [4]: b Indentation is compulsory in scripts as well. As an excrcise, re-type the previous lines with the same indentation in a script candi-ior. py, and cxccute the script with run condit:an py in Ipython In [5 a 1 s [51: True In[6:b[⊥]=hi! 2.4.2 for/range n [71 u=[7]:[1,"hi!;3 Iterating with an index hange a list in plac e, use indexing/slices >> for print( i) :a=1 In [3]:a In [4]: a-['a,'b,'c'] f Creates another ob ject ou-[5l:「a',"b’,c’ Bul Inns oflen il is umre readable io ilerale over values 2.3. Assignment operator 2 4. Control Flow

试读 127P Python Scientific
立即下载 低至0.43元/次 身份认证VIP会员低至7折
    • 签到新秀

    • 分享宗师

    关注 私信 TA的资源
    Python Scientific 38积分/C币 立即下载
    Python Scientific第1页
    Python Scientific第2页
    Python Scientific第3页
    Python Scientific第4页
    Python Scientific第5页
    Python Scientific第6页
    Python Scientific第7页
    Python Scientific第8页
    Python Scientific第9页
    Python Scientific第10页
    Python Scientific第11页
    Python Scientific第12页
    Python Scientific第13页
    Python Scientific第14页
    Python Scientific第15页
    Python Scientific第16页
    Python Scientific第17页
    Python Scientific第18页
    Python Scientific第19页
    Python Scientific第20页


    38积分/C币 立即下载 >