Numerical Python Hans Petter Langtangen Intro to Python programming Simula Research Laboratory Dept. of Informatics, Univ. of Oslo February 2008 Numerical Python – p. 1 Make sure you have the software Intro to Python programming – p. 2 Material associated with these slides You will need Python version 2.5 Gnuplot, gcc, g++, g77 These slides have a companion book: Scripting in Computational Science, 3rd edition, Texts in Computational Science and Engineering, Springer, 2008 Tcl/Tk (for G
of 66
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
Related Documents
  Numerical Python Hans Petter LangtangenSimula Research LaboratoryDept. of Informatics, Univ. of OsloFebruary 2008 Numerical Python – p. 1 Intro to Python programming Intro to Python programming – p. 2 Make sure you have the software You will need Python version 2.5Numerical Python ( numpy )Gnuplot, gcc, g++, g77Tcl/Tk (for GUI programming)Some Python modules are needed: IPython, epydoc, Pmw, ... Intro to Python programming – p. 3 Material associated with these slides These slides have a companion book: Scripting in Computational Science  , 3rd edition,Texts in Computational Science and Engineering,Springer, 2008All examples can be downloaded as a tarfile Software associated with the book and slides: SciTools Intro to Python programming – p. 4 Installing TCSE3-3rd-examples.tar.gz Pack  TCSE3-3rd-examples.tar.gz  out in a directory and let scripting  be an environment variable pointing to the top directory: tar xvzf TCSE3-3rd-examples.tar.gzexport scripting=‘pwd‘ All paths in these slides are given relative to  scripting , e.g., src/py/intro/  is reached as $scripting/src/py/intro/ Intro to Python programming – p. 5 Scientific Hello World script All computer languages intros start with a program that prints Hello,World! to the screenScientific computing extension: read a number, compute its sinevalue, and print outThe script, called, should be run like this: python 3.4 or just (Unix) ./ 3.4 Output: Hello, World! sin(3.4)=-0.255541102027 Intro to Python programming – p. 6 Purpose of this script Demonstratehow to read a command-line argumenthow to call a math (sine) functionhow to work with variableshow to print text and numbers Intro to Python programming – p. 7 The code File #!/usr/bin/env python# load system and math module:import sys, math# extract the 1st command-line argument:r = float(sys.argv[1])s = math.sin(r)print Hello, World! sin( + str(r) + )= + str(s) Make the file executable (on Unix): chmod a+rx Intro to Python programming – p. 8  Comments The first line specifies the interpreter of the script(here the first python program in your path) python 1.4 # first line is not treated as comment./ 1.4 # first line is used to specify an interpreter Even simple scripts must load modules: import sys, math Numbers and strings are two different types: r = sys.argv[1] # r is strings = math.sin(float(r))# sin expects number, not string r# s becomes a floating-point number Intro to Python programming – p. 9 Alternative print statements Desired output: Hello, World! sin(3.4)=-0.255541102027 String concatenation: print Hello, World! sin( + str(r) + )= + str(s) printf-like statement: print Hello, World! sin(%g)=%g % (r,s) Variable interpolation: print Hello, World! sin(%(r)g)=%(s)g % vars() Intro to Python programming – p. 10 printf format strings %d : integer%5d : integer in a field of width 5 chars%-5d : integer in a field of width 5 chars,but adjusted to the left%05d : integer in a field of width 5 chars,padded with zeroes from the left%g : float variable in %f or %g notation%e : float variable in scientific notation%11.3e : float variable in scientific notation,with 3 decimals, field of width 11 chars%5.1f : float variable in fixed decimal notation,with one decimal, field of width 5 chars%.3f : float variable in fixed decimal form,with three decimals, field of min. width%s : string%-20s : string in a field of width 20 chars,and adjusted to the left Intro to Python programming – p. 11 Strings in Python Single- and double-quoted strings work in the same way s1 = some string with a number %g % rs2 = ’some string with a number %g’ % r # = s1 Triple-quoted strings can be multi line with embedded newlines: text = large portions of a textcan be conveniently placedinside triple-quoted strings(newlines are preserved) Raw strings, where backslash is backslash: s3 = r’\(\s+\.\d+\)’# with ordinary string (must quote backslash):s3 = ’\\(\\s+\\.\\d+\\)’ Intro to Python programming – p. 12 Where to find Python info Make a bookmark for  $scripting/doc.html Follow link to  Index to Python Library Reference  (complete on-line Python reference)Click on Python keywords, modules etc.Online alternative:  pydoc , e.g.,  pydoc mathpydoc  lists all classes and functions in a moduleAlternative: Python in a Nutshell (or Beazley’s textbook)Recommendation: use these slides and associated book togetherwith the Python Library Reference, and learn by doing exercises Intro to Python programming – p. 13 New example: reading/writing data files Tasks:Read (x,y) data from a two-column fileTransform y values to f(y)Write (x,f(y)) to a new fileWhat to learn:How to open, read, write and close filesHow to write and call a functionHow to work with arrays (lists)File:  src/py/intro/ Intro to Python programming – p. 14 Reading input/output filenames Usage: ./ infilename outfilename Read the two command-line arguments:input and output filenames infilename = sys.argv[1]outfilename = sys.argv[2] Command-line arguments are in  sys.argv[1:]sys.argv[0]  is the name of the script Intro to Python programming – p. 15 Exception handling What if the user fails to provide two command-line arguments?Python aborts execution with an informative error messageA good alternative is to handle the error manually inside the programcode: try:infilename = sys.argv[1]outfilename = sys.argv[2]except:# try block failed,# we miss two command-line argumentsprint ’Usage:’, sys.argv[0], ’infile outfile’sys.exit(1) This is the common way of dealing with errors in Python, called exception handling  Intro to Python programming – p. 16  Open file and read line by line Open files: ifile = open( infilename, ’r’) # r for readingofile = open(outfilename, ’w’) # w for writingafile = open(appfilename, ’a’) # a for appending Read line by line: for line in ifile:# process line Observe: blocks are indented; no braces! Intro to Python programming – p. 17 Defining a function import mathdef myfunc(y):if y >= 0.0:return y**5*math.exp(-y)else:return 0.0# alternative way of calling module functions# (gives more math-like syntax in this example):from math import *def myfunc(y):if y >= 0.0:return y**5*exp(-y)else:return 0.0 Intro to Python programming – p. 18 Data transformation loop Input file format: two columns with numbers 0.1 1.43970.2 4.3250.5 9.0 Read (x,y), transform y, write (x,f(y)): for line in ifile:pair = line.split()x = float(pair[0 y = float(pair[1])fy = myfunc(y) # transform y valueofile.write(’%g %12.5e\n’ % (x,fy)) Intro to Python programming – p. 19 Alternative file reading This construction is more flexible and traditional in Python (and a bitstrange...): while 1:line = ifile.readline() # read a lineif not line: break # end of file: jump out of loop# process line i.e., an ’infinite’ loop with the termination criterion inside the loop Intro to Python programming – p. 20 Loading data into lists Read input file into list of lines: lines = ifile.readlines() Now the 1st line is  lines[0] , the 2nd is  lines[1] , etc.Store x and y data in lists: # go through each line,# split line into x and y columnsx = []; y = [] # store data pairs in lists x and yfor line in lines:xval, yval = line.split()x.append(float(xval))y.append(float(yval)) See  src/py/intro/  for this version Intro to Python programming – p. 21 Loop over list entries For-loop in Python: for i in range(start,stop,inc):...for j in range(stop):... generates i = start, start+inc, start+2*inc, ..., stop-1j = 0, 1, 2, ..., stop-1 Loop over (x,y) values: ofile = open(outfilename, ’w’) # open for writingfor i in range(len(x)):fy = myfunc(y[i]) # transform y valueofile.write(’%g %12.5e\n’ % (x[i], fy))ofile.close() Intro to Python programming – p. 22 Running the script Method 1: write just the name of the scriptfile: ./ infile outfile# infile outfile if . (current working directory) or the directory is in the pathMethod 2: run an interpreter explicitly: python infile outfile Use the first python program found in the pathThis works on Windows too (method 1 requires the right assoc/ftype  bindings for  .py  files) Intro to Python programming – p. 23 More about headers In method 1, the interpreter to be used is specified in the first lineExplicit path to the interpreter: #!/usr/local/bin/python or perhaps your own Python interpreter: #!/home/hpl/projects/scripting/Linux/bin/python Using env to find the first Python interpreter in the path: #!/usr/bin/env python Intro to Python programming – p. 24  Are scripts compiled? Yes and no, depending on how you see itPython first compiles the script into bytecodeThe bytecode is then interpretedNo linking with libraries; libraries are imported dynamically whenneededIt appears as there is no compilationQuick development: just edit the script and run!(no time-consuming compilation and linking)Extensive error checking at run time Intro to Python programming – p. 25 Python and error checking Easy to introduce intricate bugs?no declaration of variablesfunctions can eat anything No, extensive consistency checks at run time replace the need forstrong typing and compile-time checksExample: sending a string to the sine function,  math.sin(’t’) ,triggers a run-time error (type incompatibility)Example: try to open a non-existing file ./ qqq someoutfileTraceback (most recent call last):File ./ , line 12, in ?ifile = open( infilename, ’r’)IOError:[Errno 2] No such file or directory:’qqq’ Intro to Python programming – p. 26 Computing with arrays x  and  y  in  are  lists  We can compute with lists element by element (as shown)However: using Numerical Python (NumPy)  arrays   instead of lists ismuch more efficient and convenientNumerical Python is an extension of Python: a new fixed-size arraytype and lots of functions operating on such arrays Intro to Python programming – p. 27 A first glimpse of NumPy Import (more on this later...): from numpy import *x = linspace(0, 1, 1001) # 1001 values between 0 and 1x = sin(x) # computes sin(x[0]), sin(x[1]) etc. x=sin(x)  is 13 times faster than an explicit loop: for i in range(len(x)):x[i] = sin(x[i]) because  sin(x)  invokes an efficient loop in C Intro to Python programming – p. 28 Loading file data into NumPy arrays A special module loads tabular file data into NumPy arrays: import scitools.filetablef = open(infilename, ’r’)x, y = scitools.filetable.read_columns(f)f.close() Now we can compute with the NumPy arrays  x  and  y : x = 10*xy = 2*y + 0.1*sin(x) We can easily write  x  and  y  back to a file: f = open(outfilename, ’w’)scitools.filetable.write_columns(f, x, y)f.close() Intro to Python programming – p. 29 More on computing with NumPy arrays Multi-dimensional arrays can be constructed: x = zeros(n) # array with indices 0,1,...,n-1x = zeros((m,n)) # two-dimensional arrayx[i,j] = 1.0 # indexingx = zeros((p,q,r)) # three-dimensional arrayx[i,j,k] = -2.1x = sin(x)*cos(x) We can plot one-dimensional arrays: from scitools.easyviz import * # plottingx = linspace(0, 2, 21)y = x + sin(10*x)plot(x, y) NumPy has lots of math functions and operationsSciPy is a comprehensive extension of NumPyNumPy + SciPy is a kind of Matlab replacement for many people Intro to Python programming – p. 30 Interactive Python Python statements can be run interactively in a  Python shell  The “best” shell is called IPythonSample session with IPython: Unix/DOS> ipython...In [1]:3*4-1Out[1]:11In [2]:from math import *In [3]:x = 1.2In [4]:y = sin(x)In [5]:xOut[5]:1.2In [6]:yOut[6]:0.93203908596722629 Intro to Python programming – p. 31 Editing capabilities in IPython Up- and down-arrays: go through command historyEmacs key bindings for editing previous commandsThe underscore variable holds the last output In [6]:yOut[6]:0.93203908596722629In [7]:_ + 1Out[7]:1.93203908596722629 Intro to Python programming – p. 32
We Need Your Support
Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

Thanks to everyone for your continued support.

No, Thanks