advance_nonlinear_fitting.py an example of nonlinear fitting a double slit single photon experimental data
# load data
import pandas as pd
= pd.read_csv ('data.csv')
df =df.get('position').to_numpy()
x=df.get('counts').to_numpy()
y
# simple way to convert numbers to the float format
=x*1.0
x=y*1.0
y
# import modules needed for data analysis
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# First we plot our data with error bars
plt.figure() #plt.errorbar(x,y, yerr=.005, xerr=3, fmt='o', label='data')
'o', label='data')
plt.plot(x,y,
plt.ion()
# We will attempt to fit data with inverse square dependence
def model(x, I0, a_s, d_s, x0, Background):
=np.pi;
pi=532.0; # in nm
lmbda=50; # in cm
l# xsingle = pi*a/lmbda*x/l;
# xdouble = pi*d/lmbda*x/l;
=a_s*(x-x0)
xsingle=d_s*(x-x0)
xdouble= np.power( np.sin(xsingle)/xsingle, 2);
single_slit = np.power( np.cos(xdouble), 2);
double_slit return (I0*double_slit*single_slit + Background)
## When you do nonlinear fitting, having a good guess is important.
# Otherwise fit my converge to unexpected parameters
=[350, np.pi/400, np.pi/60, 505.0, 150.0]; # [I0, a_s, d_s, x0, Background ] coefficients
guessParameters
=np.linspace(100, 800, 1000)
xf*guessParameters), 'b--', label='guess fit: I0=%.4g, a_s=%.4g, d_s=%.4g, x0=%.4g, Background=%.4g' % tuple(guessParameters))
plt.plot(xf, model(xf,
plt.legend()# plt.show() , we might delay or not the plot rendering
# We might repeat it several time to have a reasonable guess which is close to the data
'data_with_a_guess_line.svg')
plt.savefig(
## Finally we do the fitting
= curve_fit(model, x, y, guessParameters)
finalParameters, finalParametersErrors
# lets add the best fit line to the plot
plt.figure()
plt.clf()'o', label='data')
plt.plot(x,y, *finalParameters), 'r-', label='best fit: I0=%.4g, a_s=%.4g, d_s=%.4g, x0=%.4g, Background=%.4g' % tuple(finalParameters))
plt.plot(xf, model(xf,
plt.legend(); # time to see the final plot
plt.show()'data_with_and_fit_line.svg')
plt.savefig(
## Output fit parameter values and their uncertainties
print("Model parameters:")
print("I0 =", finalParameters[0], " +/- ",np.sqrt(finalParametersErrors[0,0]))
print("a_s =", finalParameters[1], " +/- ",np.sqrt(finalParametersErrors[1,1]))
print("d_s =", finalParameters[2], " +/- ",np.sqrt(finalParametersErrors[2,2]))
print("x0 =", finalParameters[3], " +/- ",np.sqrt(finalParametersErrors[3,3]))
print("Background =", finalParameters[4], " +/- ",np.sqrt(finalParametersErrors[4,4]))