Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409...
Transcript of Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409...
![Page 1: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/1.jpg)
Tutorial 2 PHY409 Anadi Canepa
[email protected] Office, TRIUMF MOB 92B (1-‐604-‐222-‐7330)
Alan Manning [email protected]
Mohammad Samani [email protected]
![Page 2: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/2.jpg)
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
![Page 3: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/3.jpg)
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
![Page 4: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/4.jpg)
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
![Page 5: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/5.jpg)
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
![Page 6: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/6.jpg)
Input file and script
hLp://trshare.triumf.ca/~canepa/PYTHON/Tutorial2/ • input_p0.txt • fiUest_p0.py
13/9/2013 Python TutoWal 6
![Page 7: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/7.jpg)
Important Concepts
1. Objects 2. Module 3. Package
13/9/2013 Python TutoWal 7
![Page 8: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/8.jpg)
(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
![Page 9: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/9.jpg)
(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
![Page 10: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/10.jpg)
(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
![Page 11: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/11.jpg)
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)
![Page 12: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/12.jpg)
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)
![Page 13: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/13.jpg)
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
![Page 14: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/14.jpg)
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
![Page 15: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/15.jpg)
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 *
![Page 16: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/16.jpg)
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))
![Page 17: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/17.jpg)
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])
![Page 18: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/18.jpg)
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()
![Page 19: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/19.jpg)
Example #1: Result
13/9/2013 Python TutoWal 19
![Page 20: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/20.jpg)
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
![Page 21: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/21.jpg)
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
![Page 22: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/22.jpg)
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]
![Page 23: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/23.jpg)
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
![Page 24: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/24.jpg)
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)
![Page 25: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/25.jpg)
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])
![Page 26: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/26.jpg)
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
![Page 27: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/27.jpg)
More material
13/9/2013 Python TutoWal 27
![Page 28: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/28.jpg)
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
![Page 29: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/29.jpg)
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
![Page 30: Tutorial2PHY409 - University of British Columbiaphys409/PDFs/PythonTutorial2.pdf · Tutorial2PHY409 Anadi&Canepa canepa@triumf.ca& Office,&TRIUMF&MOB&92 B (16042227330) & Alan&Manning&mannin2@phas.ubc.ca](https://reader030.fdocuments.us/reader030/viewer/2022040803/5e3e5245f3ab935f1b21f8b6/html5/thumbnails/30.jpg)
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