PariSAGE SciPy template (Orsay - 16 feb 2012) (v2.0)
system:python


<h1 style="text-align: center;"><span style="color: #339966;">Tutorial on the scientific use of Python</span></h1>
<p>My name is Fabio Grazioso, and here is my picture: <img src="me_Stromboli-effect.jpg" alt="" width="192" height="215" /></p>
<p>To insert a "Text cell" shift-click the blue inserting line</p>
<p>To insert an image file (from local hard drive) in a "text cell":</p>
<p>1) upload the file on SAGE server using the "Data" menu</p>
<p>2) use the "edit/insert image" button in the toolbar of the "text cell"</p>
<p>python has some built-in functions, such as:&nbsp;</p>

{{{id=20|
N(log(12))  # N() asks for the numerical value
///
<html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}2.48490664978800</span></html>
}}}

{{{id=21|
N(log(e)) #let's check the base
///
<html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}1.00000000000000</span></html>
}}}

<p><span style="font-size: large;">to have the logarithm in base 2 we have to convert</span></p>

{{{id=26|
N(log(12) / log(2) )
///
<html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3.58496250072116</span></html>
}}}

<h2 style="text-align: center;"><span style="color: #ff0000;">loading SciPy</span></h2>

<p><span style="font-size: large;">if we want something more sophisticated, we have to load "SciPy", the scientific library:</span></p>

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

<p><span style="font-size: large;">now we can use dirctly <span style="font-family: 'courier new', courier;"><strong><span style="font-family: 'courier new', courier;">log2()</span></strong></span>, which is defined in SciPy and returns logarithm in base 2:</span></p>

{{{id=24|
sp.log2(12)
///
<html><span class="math">\newcommand{\Bold}[1]{\mathbf{#1}}3.58496250072</span></html>
}}}

<p>in general, to find help on SciPy visit the official website:</p>
<p><a href="http://www.scipy.org" target="_blank">www.scipy.org</a></p>
<p>I also use google to search within that: typing "log2 site:www.scipy.org" into google</p>

<h2 style="text-align: center;"><strong><span style="font-size: large;"><span style="color: #ff0000;">Arrays in SciPy</span></span></strong></h2>

<p style="text-align: left;"><span style="font-size: medium;">Python has a "basic" object which is the <em>list</em>, denoted by square brackets:</span></p>

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

<p>and it is possible to do nice things with lists:</p>

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

<p>but to do more sophisticated things we use scipy arrays:</p>

{{{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]]
}}}

<p>at this link there is a nice page with a summary about SciPy arrays:</p>
<p><a title="SciPy array tip sheet" href="http://pages.physics.cornell.edu/~myers/teaching/ComputationalMethods/python/arrays.html" target="_blank">http://pages.physics.cornell.edu/~myers/teaching/ComputationalMethods/python/arrays.html</a></p>

<h2 style="font-size: 1.5em; text-align: center;"><strong style="font-weight: bold;"><span style="font-size: large;"><span style="color: #ff0000;">control structures: for cycle syntax</span></span></strong></h2>

{{{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
}}}

<p style="text-align: center;"><strong><span style="font-size: large;"><span style="color: #ff0000;">Linear algebra, solving system of linear equations</span></span></strong></p>

<p>to do some linear algebra, another library is needed, so we load it:</p>

{{{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.]
}}}

<h2 style="text-align: center;"><strong><span style="color: #ff0000;">plotting</span></strong></h2>

{{{id=76|
def f(x):
    return x**2


plot(f, (x,0,5))
///
<html><font color='black'><img src='cell://sage0.png'></font></html>
}}}

<h2 style="text-align: center;"><span style="color: #ff0000;">3D plotting</span></h2>

{{{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()
///
}}}

<div style="color: #000000; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: #ffffff; background-position: initial initial; background-repeat: initial initial; margin: 8px;">
<h2 style="font-size: 1.5em; text-align: center;"><strong style="font-weight: bold;"><span style="color: #ff0000;">minimization: finding local minima for functions of multiple variables</span></strong></h2>
</div>

{{{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
}}}

<h2 style="text-align: center;"><strong><span style="color: #ff0000;">minimization: finding local minima for functions of multiple variables</span></strong></h2>

{{{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 <module>
    
  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 <module>
    
  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.
}}}

<p>here is the documentation for the minimization function:</p>
<p><a title="scipy fmin_slsqp documentation page" href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fmin_slsqp.html" target="_blank">http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fmin_slsqp.html</a></p>