Tutorial on the scientific use of Python

My name is Fabio Grazioso, and here is my picture:

To insert a "Text cell" shift-click the blue inserting line

To insert an image file (from local hard drive) in a "text cell":

1) upload the file on SAGE server using the "Data" menu

2) use the "edit/insert image" button in the toolbar of the "text cell"

python has some built-in functions, such as: 

{{{id=20| N(log(12)) # N() asks for the numerical value /// \newcommand{\Bold}[1]{\mathbf{#1}}2.48490664978800 }}} {{{id=21| N(log(e)) #let's check the base /// \newcommand{\Bold}[1]{\mathbf{#1}}1.00000000000000 }}}

to have the logarithm in base 2 we have to convert

{{{id=26| N(log(12) / log(2) ) /// \newcommand{\Bold}[1]{\mathbf{#1}}3.58496250072116 }}}

loading SciPy

if we want something more sophisticated, we have to load "SciPy", the scientific library:

{{{id=22| import scipy as sp /// }}}

now we can use dirctly log2(), which is defined in SciPy and returns logarithm in base 2:

{{{id=24| sp.log2(12) /// \newcommand{\Bold}[1]{\mathbf{#1}}3.58496250072 }}}

in general, to find help on SciPy visit the official website:

www.scipy.org

I also use google to search within that: typing "log2 site:www.scipy.org" into google

Arrays in SciPy

Python has a "basic" object which is the list, denoted by square brackets:

{{{id=28| myList = [1,2,3,4,5] /// }}}

and it is possible to do nice things with lists:

{{{id=59| mySecondList = [ 3+x for x in myList] print(mySecondList) /// [4, 5, 6, 7, 8] }}}

but to do more sophisticated things we use scipy arrays:

{{{id=34| myArray = sp.array([1,2,3,4,5]) print(myArray) /// [1 2 3 4 5] }}} {{{id=61| my2DArray = sp.array([[0,1,2,3,4,5,6,7,8,9,10],[0,10,20,30,40,50,60,70,80,90,100],[0,11,22,33,44,55,66,77,88,99,111]]) print(my2DArray) /// [[ 0 1 2 3 4 5 6 7 8 9 10] [ 0 10 20 30 40 50 60 70 80 90 100] [ 0 11 22 33 44 55 66 77 88 99 111]] }}} {{{id=69| print(sp.transpose(my2DArray)) /// [[ 0 0 0] [ 1 10 11] [ 2 20 22] [ 3 30 33] [ 4 40 44] [ 5 50 55] [ 6 60 66] [ 7 70 77] [ 8 80 88] [ 9 90 99] [ 10 100 111]] }}} {{{id=70| mySlice = my2DArray[0:2, 1:6] # NB first included, last excluded! print(mySlice) /// [[ 1 2 3 4 5] [10 20 30 40 50]] }}}

at this link there is a nice page with a summary about SciPy arrays:

http://pages.physics.cornell.edu/~myers/teaching/ComputationalMethods/python/arrays.html

control structures: for cycle syntax

{{{id=51| for i in mySecondList: print i /// 4 5 6 7 8 }}} {{{id=52| for i in range(2, 10): # remember: first included, last excluded print i /// 2 3 4 5 6 7 8 9 }}} {{{id=73| for i in range(20, 0, -2): print i /// 20 18 16 14 12 10 8 6 4 2 }}}

Linear algebra, solving system of linear equations

to do some linear algebra, another library is needed, so we load it:

{{{id=74| coefficients = sp.array([[2,3,6], [3,4,0], [2,4,6]]) knowns = sp.array([-1,7,0]) print(coefficients) print(knowns) /// [[2 3 6] [3 4 0] [2 4 6]] [-1 7 0] }}} {{{id=48| from scipy import linalg #for some reason linalg has to be imported explicitly x = sp.linalg.solve(coefficients, knowns) print(x) /// [ 1. 1. -1.] }}}

plotting

{{{id=76| def f(x): return x**2 plot(f, (x,0,5)) /// }}}

3D plotting

{{{id=79| def f(x,y): return sp.sin(y*y+x*x)/sp.sqrt(x*x+y*y+.0001) P = plot3d(f,(-3,3),(-3,3), adaptive=True, color=rainbow(60, 'rgbtuple')) P.show() /// }}} {{{id=81| def f(x,y): return sp.sin(x) * sp.sin(y) P = plot3d(f,(-10,10),(-10,10), adaptive=True, color=rainbow(60, 'rgbtuple')) P.show() /// }}}

minimization: finding local minima for functions of multiple variables

{{{id=82| from scipy import integrate #again, first import the object explicitly from def f(x, a, b): return a * x**2 + b args = (2, 1.5) result = sp.integrate.quad(f, 0, 5, args) print 'integral=',result[0],' with error', result[1] /// integral= 90.8333333333 with error 1.0084525807e-12 }}}

minimization: finding local minima for functions of multiple variables

{{{id=42| def func(x,y, *args): return sp.sin(x) * sp.sin(y) def constrains(x,y, *args): return x*y < 100 P = plot3d(func,(-3,3),(-3,3), adaptive=True, color=rainbow(60, 'rgbtuple')) P.show() startArray = sp.array([1, -1]) extraArg = sp.array([0,0]) from scipy import optimize results = sp.optimize.fmin_slsqp(func, startArray, args=extraArg, f_eqcons = constrains) /// Traceback (most recent call last): P = plot3d(func,(-3,3),(-3,3), adaptive=True, color=rainbow(60, 'rgbtuple')) File "", line 1, in File "/Applications/Sage/Sage-4.7.2-OSX-64bit-10.6.app/Contents/Resources/sage/devel/sagenb/sagenb/misc/support.py", line 481, in syseval return system.eval(cmd, sage_globals, locals = sage_globals) File "/Applications/Sage/Sage-4.7.2-OSX-64bit-10.6.app/Contents/Resources/sage/local/lib/python2.6/site-packages/sage/misc/python.py", line 56, in eval eval(z, globals) File "", line 1, in File "/Applications/Sage/Sage-4.7.2-OSX-64bit-10.6.app/Contents/Resources/sage/local/lib/python2.6/site-packages/scipy/optimize/slsqp.py", line 318, in fmin_slsqp g = append(fprime(x),0.0) File "/Applications/Sage/Sage-4.7.2-OSX-64bit-10.6.app/Contents/Resources/sage/local/lib/python2.6/site-packages/scipy/optimize/optimize.py", line 176, in function_wrapper return function(x, *args) File "/Applications/Sage/Sage-4.7.2-OSX-64bit-10.6.app/Contents/Resources/sage/local/lib/python2.6/site-packages/scipy/optimize/optimize.py", line 377, in approx_fprime grad[k] = (f(*((xk+ei,)+args)) - f0)/epsilon ValueError: setting an array element with a sequence. }}}

here is the documentation for the minimization function:

http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fmin_slsqp.html