Python Tutorial 1

From Advanced Labs Wiki
Jump to navigation Jump to search

# coding: utf-8

## Python Tutorial 1

# This document is supposed to give the tools one needs for analyzing the <b>Brownian Motion</b> experiment data.

### 1. Setup Modules and Inline Plotting

# Python <b>modules</b> package together useful tools. These include <b>functions</b> and new useful <b>data types</b> often defined as <b>objects</b>. 

# In[40]:

#This is a comment. Anything following a '#' is not interpretted as code

import pylab as plt  # python plotting module; rename plt for short
import numpy as np   # python numerical computing module; rename np for short
import scipy as sp   # python scientific computing module; rename sp for short

# Make plots appear in the notebook
get_ipython().magic(u'matplotlib inline')


### 2. Variables and Data Types

# <b>Variables</b> hold values and have an associated <b>type</b>. Here are some useful examples.

# In[48]:

a_int   = 2  # an integer number
a_float = 2. # a floating point or decimal number
a_list = [1.,2.,3.] #a list
a_array = np.array(a_list) #convert a list into a numpy array
a_string = 'words' #a string

print 'my variables:', a_int, a_float, a_list, a_array, a_string
print 'my variable types:', type(a_int), type(a_float), type(a_list), type(a_array), type(a_string)

#Array indexing: for an array of length N, indices are 0,...,N-1
print "Use len to get the length of an array. len(a_array) =", len(a_array)
print "The value of an array can be accessed with an index:", a_array[0], a_array[1], a_array[2]
a_array[0] = 3. # Assigning a value to the first element 
print "Reassigned a_array[0]:",a_array
a_array[0] = 1. # Change back
print a_array, "as before"
# you can also select a sequence of elements from an array using a list (or array) of indices
print a_array[[0,1,2,1,0]]

#String formatting
print "A string can contain formatting characters: %d, %.2f, %s" % (a_int, a_float, a_string)


### 3. Operators 1: Arithmetic Operators

# Python <b>arithmetic operators</b> enable arithmetic with <b>variables</b> and <b>literals</b> (values not associated with a variable).

# In[42]:

print ".5*a_float^2+6 (here 0.5,2, and 6 are 'literals') =", 0.5*a_float**2+6
print "Integer division drops the remainder (a common bug). 6/7 =", 6/7
print "Floating point division is usually what you want. 6./7 =", 6./7
print "You can do arithmetic with numpy arrays. 2*a_array+0.5 =", 2*a_array+0.5
print "You can also add or multiply arrays. a_array**2 =", a_array**2
print "But you can't do regular arithmetic with a list. a_list+2 =", a_list+2


### 4. Control Structures 1: The for loop

# Python <b>control structures</b> can determine whether and how many times lines of code are executed. The python <b>for loop</b> allows you to repeat code for each element in a list or array. At each repetition a <b>loop variable</b> is sequentially assigned values from the list or array.

# In[ ]:

#loop through the elemets in a list
i = 0
for a in a_array:
    print i, a      # The instructions in the loop are all indented
    i= i+1          # The loop body can have as many instructions as you want
    
#Another way
print range(len(a_array)) # range creates a list of indices with the length given as the argument
for i in range(len(a_array)):
    print i, a_array[i]


### 4. Functions

# Python <b>functions</b> package code in a simplified, reusable form. A <b>function</b> can take <b>arguments<b> and <b>returns</b> a value.

# In[ ]:

def line(a,x,b): #a,x,b are arguments to the function
    y = a*x+b #note the indent indicates you are in the function
    return y

print "Arguments can be literals or variables. line(a_float,1.,1.) =", line(a_float,1.,3.)
print "Numerical arguments can be numpy arrays. line(a_float,a_array,1.)=", line(a_float,a_array,1.)


#### 4.1 Some useful functions

# In[45]:

#Generating Arrays
print 'np.arange(0,10,2) =', np.arange(0,10,2)  #generate an array from 0 to (but not including) 10 in increments of 2
print 'np.zeros(10) =', np.zeros(10) #generates an array of 0s with length given by the argument
print 'np.random.random_integers(0,10,5)', np.random.random_integers(0,10,5) #useful for bootstrap
print a_array[np.random.random_integers(0,len(a_array)-1,len(a_array))]

#Reading data
a = np.random.normal(0,1,60)
b = np.random.normal(0,1,60)
np.savetxt('data.txt',np.transpose([a,b]))
x,y = np.loadtxt('data.txt', unpack=True) #unpack=True is needed for reading columns

#plotting data
plt.hist(x,bins=5)
plt.xlabel(r'x ($\mu$m)', fontsize=14)
plt.ylabel('frequency', fontsize=14)
plt.savefig('hist.png')
plt.show()


# In[ ]: