Upload
others
View
11
Download
0
Embed Size (px)
Citation preview
Tutorial 2 PHY409 Anadi Canepa
[email protected] Office, TRIUMF MOB 92B (1-‐604-‐222-‐7330)
Alan Manning [email protected]
Mohammad Samani [email protected]
During the 1st tutorial
We learnt • What Python is • How to import packages • How to produce a 1D plots, scaUer plots, histograms We used • matplotlib • numpy
13/9/2013 Python TutoWal 2
HW #1 (due today)
1. Install python 2. Install matplotlib, numpy, scipy (the order maUers!) 3. (Install Spyder -‐ opWonal) 4. Write a script to plot sin(x):
1. Range [0:2π] 2. Add labels to the axis, Wtle, legend
5. Save the plot in pdf format
13/9/2013 Python TutoWal 3
The goal of today is to learn to fit
13/9/2013 4 Python TutoWal
1. Example #1: Polynomial order 0 1. Read in text file 2. Store data 3. Fit them and compute uncertainWes on the fit parameter
2. Example #2: ExponenFal (hands-‐on) 1. Modify the model 2. Compute uncertainWes on the fit parameters
3. Example #3: Gaussian (hands-‐on) 1. Handling histograms
Example #1
13/9/2013 5 Python TutoWal
1. Read in a text file containing data points 2. Handle the data 3. Fit the data
Module courtesy of Prof. C. Gay
Input file and script
hLp://trshare.triumf.ca/~canepa/PYTHON/Tutorial2/ • input_p0.txt • fiUest_p0.py
13/9/2013 Python TutoWal 6
Important Concepts
1. Objects 2. Module 3. Package
13/9/2013 Python TutoWal 7
(1) Objects
Everything in Python is an object • Strings, funcWons, classes • The name is used to access the object • The “dot” operator is used to access the object aUributes
13/9/2013 Python TutoWal 8
str . index (‘e’)
Variable Delimiter AUribute Argument name
(2) Modules
• A module is a file containing Python funcWons definiWons and executable statements – The file name is the module name with the suffix .py appended
– Modules can be imported in scripts and in modules
• Whenever you run a simple Python script, the interpreter treats it as a module called __main__, which gets its own namespace
13/9/2013 Python TutoWal 9
(3) Packages
• Packages are a way of structuring Python’s module namespace
• For example, the module name A.B designates a sub-‐module named B in a package named A
13/9/2013 Python TutoWal 10
Modules: import statement
13/9/2013 Python TutoWal 11
import pylab as plb import scypy as sy import numpy as np
import matplotlib.pyplot as plt
from math import sqrt
from scipy.opWmize import leastsq
Import module (pylab) with a given alias
Access the funcWons using this alias
Import sub-‐module (pyplot)
from package (matplotlib)
Import name (sqrt)
from module (math)
How to read in a text file
FuncWon loadtxt of numpy to read in the text file Returns an ndarray
(mulWdimensional container of items of the same type)
13/9/2013 12
data = np.loadtxt(‘mydata.txt’, skiprows=2)
Working with the N-‐dimensional array
• ndarray can be indexed: – print data[1,2]
• ndarray can be sliced:
13
x = data[:,0] y = data[:,1] sigma = data[,:2]
x y σ
X
x y σ
X X X X
13/9/2013 Python TutoWal
Least-‐square fi]ng
• MinimizaWon of:
• Where f(x) is the model we want to use to fit the data
13/9/2013 Python TutoWal 14
Define the model funcFon
• keyword def followed by the funcWon name and parentheses
• input parameters or arguments should be placed within these parentheses
• code block within every funcWon starts with a colon (:) and is indented
• statement return [expression] exits a funcWon, opWonally passing back an expression to the caller
13/9/2013 Python TutoWal 15
def func(x, a): return a*pow(x,0)
x0 x1 x2 … xn
1 1 1 … 1 a *
Fit the data (I)
• Define the residual funcWon
• Call the leastsq funcWon imported from scipy.opWmize
13/9/2013 Python TutoWal 16
def residual (coeff, x, y, sigma): return (y-‐func(x, coeff[0]))/sigma
p = leastsq (residuals, coeff, args=(x, y, sigma))
Fit the data (II)
• Leastsq returns the value of the fiUed parameter
• It can also return the uncertainty if we request the full
output
13/9/2013 Python TutoWal 17
print "Fit value: ", p[0]
p, cov, infodict, mesg, ier = leastsq (residuals, coeff, args=(x, y, sigma), full_output=True) print "Fit value: ", p[0] s_sq = (infodict['fvec']**2).sum()/(len(y)-‐1) cov_scaled = cov*s_sq print “Uncertainty", sqrt(cov_scaled[0])
Plo]ng the results
• Some formarng …. (see script) • Plot the data with error bars and overlay the fit result
13/9/2013 Python TutoWal 18
plt.errorbar(x, y, sigma, linestyle='', marker='o’) plt.plot(x,func(x, p[0])) plt.show()
Example #1: Result
13/9/2013 Python TutoWal 19
Example #2
• Download the input file input_exp.txt from: hLp://trshare.triumf.ca/~canepa/PYTHON/Tutorial2/
• Fit the data to the exponenWal:
13/9/2013 Python TutoWal 20
Example #2 (I)
• Replace the polynomial fit with the exponenWal fit • Warning: number of free parameter changes from 1 to 2
13/9/2013 Python TutoWal 21
coeff = [0,0] def func(x, a, b): return a * np.exp(-‐b * x) def residuals (coeff, x, y, sigma): return (y-‐func(x, coeff[0],coeff[1]))/sigma
Example #2 (II)
• Replace the polynomial fit with a n exponenWal fit • Warning: number of free parameter changes from 1 to 2
13/9/2013 Python TutoWal 22
p = leastsq (residuals, coeff, args=(x,y,sigma), full_output=True) print "Fit values for a, b", p[0][0], p[0][1]
Example #3
• Generate a sample of 1000 events distributed according to a Gaussian distribuWon (mean =0, variance = 1)
• Fill a histogram with the data • Fit the histogram to a Gaussian (take into account the
uncertainty on the bin content) • Print the mean and the variance
13/9/2013 Python TutoWal 23
Example #3 (I)
• Extract the bin content using the return values of matplotlib.pyplot hist
13/9/2013 Python TutoWal 24
tuple : (binContents, binEdges, patches)
Example #3 (II)
13/9/2013 Python TutoWal 25
x = np.random.randn(10000) binContents, binEdges, patches = plt.hist(x,bins=60,range=(-‐3,3)) binWidth = binEdges[1]-‐binEdges[0] nBins = len(binContents) binCenters = range(nBins) binErrors = range(nBins) for i in range(len(binContents)): binCenters[i] = (binEdges[i+1]+binEdges[i])/2 binErrors[i] = sqrt(binContents[i])
In today’s tutorial
We learnt 1. How to read in a text file 2. Store its content in arrays 3. Define and call funcWons 4. Fit data 5. Print fit results 6. Plot fit results
Slides, scripts and input files can be found at: hLp://trshare.triumf.ca/~canepa/PYTHON/Tutorial2/
13/9/2013 Python TutoWal 26
More material
13/9/2013 Python TutoWal 27
Name
• A name in Python is roughly analogous to a variable in just about any other language, but with a few extras.
• Because of Python’s dynamic nature, you can apply a name to just about anything.
13/9/2013 Python TutoWal 28
a = 5.0 a = ‘a’ a = [1,2,3] def fun():
print “Hello” a = fun
Name Space
• A namespace is a space that holds names.
• Each module gets it’s own global namespace • Once you import that module into your script, you can
access the names by prefixing them with the module name
• Each namespace is also completely isolated
13/9/2013 Python TutoWal 29
Math package
• FuncWons from the "math" package do not operate on numpy arrays (which you should always be using instead of lists)
• Use funcWons from numpy to do this. Example:
import numpy import math x = numpy.asarray([0,2,3,4,5]) y = math.sqrt(x) #Error! y = numpy.sqrt(x) #No error
13/9/2013 Python TutoWal 30