import scipy as sp
from scipy.optimize import curve_fit
import matplotlib as mpl # As of July 2017 Bucknell computers use v. 2.x
import matplotlib.pyplot as plt
# Following is an Ipython magic command that puts figures in the notebook.
# For figures in separate windows, comment out following line and uncomment
# the next line
# Must come before defaults are changed.
%matplotlib notebook
#%matplotlib
# As of Aug. 2017 reverting to 1.x defaults.
# In 2.x text.ustex requires dvipng, texlive-latex-extra, and texlive-fonts-recommended,
# which don't seem to be universal
# See https://stackoverflow.com/questions/38906356/error-running-matplotlib-in-latex-type1cm?
mpl.style.use('classic')
# M.L. modifications of matplotlib defaults using syntax of v.2.0
# More info at http://matplotlib.org/2.0.0/users/deflt_style_changes.html
# Changes can also be put in matplotlibrc file, or effected using mpl.rcParams[]
plt.rc('figure', figsize = (6, 4.5)) # Reduces overall size of figures
plt.rc('axes', labelsize=16, titlesize=14)
plt.rc('figure', autolayout = True) # Adjusts supblot parameters for new size
data = sp.loadtxt("sample2.dat") # Each line in file corresponds to
# single data point: x,y,u
x = data.T[0] # The .T gives transpose of array
y = data.T[1]
u = data.T[2]
# More "pythonic" reading of data
# The "unpack = True" reads columns.
x, y, u = sp.loadtxt("sample2.dat", unpack=True)
# "quasi-continuous" set of x's for plotting of function:
xfine = sp.linspace(min(x), max(x), 201)
plt.figure(1)
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.title('Data')
plt.axhline(0, color='magenta')
# Pad x-range on plot:
plt.xlim(min(x) - 0.05*(max(x) - min(x)), max(x) + 0.05*(max(x) - min(x)))
plt.errorbar(x, y, yerr=u, fmt='o');
def fun(x, a, b, c, d):
return a*sp.exp(-(x-b)**2/2/c**2) + d
Initial "guesses" for parameters a,b,c,d
p0 = 3.5, 105., 8, 0.2
# "quasi-continuous" set of x's for plotting of function:
xfine = sp.linspace(min(x), max(x), 201)
plt.figure(2)
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.title('Data with initial "guess"')
plt.axhline(0, color='magenta')
# Pad x-range on plot:
plt.xlim(min(x) - 0.05*(max(x) - min(x)), max(x) + 0.05*(max(x) - min(x)))
plt.errorbar(x, y, yerr=u, fmt='o')
plt.plot(xfine, fun(xfine, *p0));
popt, pcov = sp.optimize.curve_fit(fun, x, y, p0, sigma=u)
# "quasi-continuous" set of x's for plotting of function:
plt.figure(3)
xfine = sp.linspace(min(x), max(x), 201)
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.title('Data with best fit')
plt.axhline(0, color='magenta')
# Pad x-range on plot:
plt.xlim(min(x) - 0.05*(max(x) - min(x)), max(x) + 0.05*(max(x) - min(x)))
plt.errorbar(x, y, yerr=u, fmt='o')
plt.plot(xfine, fun(xfine, *popt));
popt # Best fit parameters
pcov # Covariance matrix
for i in range(len(popt)):
print("parameter", i,"=", popt[i], "+/-", sp.sqrt(pcov[i,i]))
For nicer formatting of output, can use features of sympy.
NOTE: Matrix is from sympy; it's not the same as sp.matrix
from sympy import *
from sympy import init_printing
init_printing()
Matrix(pcov)
NOTE:
absolute_sigma=True is equivalent to Mathematica VarianceEstimatorFunction-> (1&).
False gives covariance matrix based on estimated errors in data (weights are just relative).
popt, pcov2 = sp.optimize.curve_fit(fun, x, y, p0, sigma=u, absolute_sigma=True)
Matrix(pcov2)
plt.figure(4)
plt.axhline(0, color='magenta')
plt.title('normalized residuals')
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.grid()
plt.scatter(x, (fun(x, *popt) - y)/u);
Calculation of reduced chi-square parameter:
\begin{equation} \chi_R^2= \frac{1}{N-c}\times\sum_{i=1}^N \frac{(y_i-f(x_i))^2}{\sigma_i^2}, \end{equation}sp.sum((y - fun(x, *popt))**2/u**2)/(len(data) - 4)
version_information
is from J.R. Johansson (jrjohansson at gmail.com)
See Introduction to scientific computing with Python:
http://nbviewer.jupyter.org/github/jrjohansson/scientific-python-lectures/blob/master/Lecture-0-Scientific-Computing-with-Python.ipynb
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
%load_ext version_information
#%install_ext http://raw.github.com/jrjohansson/version_information/master/version_information.py
%version_information scipy, matplotlib, sympy