A few python, SciPy, and matplotlib examples¶

Cells¶

This is a "markdown" cell. Markdown cells are for for formatted comments. See the Markdown Cheat-Sheet for more information.

If you single-click on a cell you can get a box around the cell, and you can see what kind of cell it is in the menu bar above (Markdown, code, etc.), and you can change it.

Double click on this cell, and we'll make some changes.

Shift+Enter to execute cells.

Importing modules¶

Functions from modules imported in this manner must be preceded by the "name" given to the module (sp, plt), e.g., sp.zeros() below.

In [50]:
import scipy as sp
import matplotlib.pyplot as plt
%matplotlib notebook


Simple loops¶

In [33]:
for i in range(5):
print(i)

0
1
2
3
4

In [34]:
for i in range(4,10):
print(i)

4
5
6
7
8
9

In [35]:
for i in range(4,10,2):
print(i)

4
6
8

In [40]:
i = -2
while i < 5:
print(i)
i += 1

-2
-1
0
1
2
3
4


Conditionals¶

In [86]:
i = 5

if i<4:
print("ok")

elif i == 4:
print("better")

else:
print('not ok')

not ok


Constructing arrays¶

SciPy/Numpy arrays are easy-to-use "containers" for data that are computationally efficient.

Constructing 1-D arrays "by hand"¶

In [16]:
a = sp.array([10, 20, 30, 4.e1])
print(a)

[ 10.  20.  30.  40.]


Constructing arrays using scipy "built-ins" (see the scipy array tip sheet)¶

In [56]:
b = sp.zeros(10)
print(b)

[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]

In [57]:
b = sp.zeros((10,10))
print(b)

[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]

In [27]:
c = sp.eye(4,4)
print(c)

[[ 1.  0.  0.  0.]
[ 0.  1.  0.  0.]
[ 0.  0.  1.  0.]
[ 0.  0.  0.  1.]]


Constructing arrays using scipy looping features (similar to Mathematica Table command)¶

In [58]:
d = sp.array([i*i for i in range(100) if i%2==1])
print(d)

[   1    9   25   49   81  121  169  225  289  361  441  529  625  729  841
961 1089 1225 1369 1521 1681 1849 2025 2209 2401 2601 2809 3025 3249 3481
3721 3969 4225 4489 4761 5041 5329 5625 5929 6241 6561 6889 7225 7569 7921
8281 8649 9025 9409 9801]


Constructing arrays using the scipy linspace function¶

Especially useful in making points along independent axis in graphs.

In [37]:
sp.linspace(4,6,11)

Out[37]:
array([ 4. ,  4.2,  4.4,  4.6,  4.8,  5. ,  5.2,  5.4,  5.6,  5.8,  6. ])

Manipulating arrays¶

In [61]:
a = sp.array([1,2,3,4])
b = sp.array([5,6,7,8])


Notice the element-wise behaviour of operators -- No need for loops¶

In [62]:
a**2

Out[62]:
array([ 1,  4,  9, 16])

* gives element-by-element multiplication¶

In [63]:
a*b

Out[63]:
array([ 5, 12, 21, 32])

@ gives matrix multiplication (here, the dot product)¶

In [64]:
a@b

Out[64]:
70

array indexing starts at 0; negative indices wrap around "to the left"¶

In [68]:
a[0], a[-1]

Out[68]:
(1, 4)

"Slice" arrays using colons (:)¶

In [89]:
a[1:], a[:3]

Out[89]:
(array([2, 3, 4]), array([1, 2, 3]))

Combine arrays into higher-dimensional arrays¶

In [90]:
c = sp.array([a,b])
print(c)

[[1 2 3 4]
[5 6 7 8]]


Extract the second column of the 2-d array c (Take the transpose of c and extract 2nd element)¶

In [72]:
sp.transpose(c)[1]

Out[72]:
array([2, 6])

Defining functions¶

Simple function of two variables¶

In [43]:
def f(x,y):
return x*y

In [44]:
f(3,4)

Out[44]:
12

Function can act on arrays too!¶

In [47]:
a = sp.linspace(1,10,10)
f(a,.5)

Out[47]:
array([ 0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5,  5. ])

Making simple graphs¶

In [76]:
plt.figure()
x = sp.linspace(0,5,201)  # Make a pseudo-continuous set of x-values
y = x**2                  # y values for smooth function
plt.plot(x,y)
xdata = sp.array([1,2,3,4,5])  # Discrete x-values
ydata = xdata**2               # y-values for discrete data set
plt.scatter(xdata,ydata)

Out[76]:
<matplotlib.collections.PathCollection at 0x7f6ec7dbc4a8>

Adding features to graphs¶

In [82]:
plt.figure()
plt.axhline(0, color='magenta')
plt.axvline(0, color='magenta')
plt.title("My theory")
plt.xlabel('$x$')
plt.ylabel('$\sigma$')
plt.grid()
x = sp.linspace(0,5,201)
y = x**2
plt.plot(x,y, label="theory")
xdata = sp.array([1,2,3,4,5])
ydata = xdata**2
plt.scatter(xdata,ydata)
plt.legend()
plt.xlim(-2,7)

Out[82]:
(-2, 7)

Writing arrays to a data file; reading in a data file as an array¶

In [4]:
a = sp.loadtxt('sample.dat')
print(a)

[[  1.   1.]
[  2.   4.]
[  3.   9.]
[  4.  16.]
[  5.  25.]]

In [10]:
b  = a**2
print(b)

[[   1.    1.]
[   4.   16.]
[   9.   81.]
[  16.  256.]
[  25.  625.]]

In [11]:
sp.savetxt('output.dat',b)


Getting help¶

In [87]:
sp.linspace?


Version Information¶

version_information is from J.R. Johansson (jrjohansson at gmail.com) See Introduction to scientific computing with Python for more information and instructions for package installation.

If version_information has been installed system wide (as it has been on Bucknell linux computers with shared file systems), continue with next cell as written. If not, comment out top line in next cell and uncomment the second line.

In [41]:
%load_ext version_information

#%install_ext http://raw.github.com/jrjohansson/version_information/master/version_information.py

Loading extensions from ~/.ipython/extensions is deprecated. We recommend managing extensions like any other Python packages, in site-packages.

In [42]:
version_information scipy, matplotlib

Out[42]:
SoftwareVersion
Python3.6.1 64bit [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
IPython6.1.0
OSLinux 3.10.0 327.36.3.el7.x86_64 x86_64 with redhat 7.2 Maipo
scipy0.19.1
matplotlib2.0.2
Wed Jan 10 16:22:52 2018 EST
In [ ]: