1# Script to test non-linear and Gaussian fits 2import random 3random.seed(1) 4from math import * 5 6global gaussian_curve 7def gaussian_curve(x): 8 y1 = 2.0 9 A1 = 10.0 10 w1 = 10.0 11 xc1 = 50.0 12 return (y1 + A1*sqrt(2/pi)/w1*exp(-2*((x-xc1)/w1)**2)) #this is the default Gauss formula used by SciDAVis 13 14dp=0.003 #noise's stddev 15 16#generate a table t1 with Gaussian data points with some noise and random y-errors 17t1Name="Gaussian-curve" 18t1=newTable(t1Name,3,100) 19for i in range(1,t1.numRows()+1): 20 xx=float(i) 21 t1.setCell(1,i,xx) 22 t1.setCell(2,i,gaussian_curve(xx)+random.uniform(0,dp)) 23 t1.setCell(3,i,random.uniform(0,dp)) 24 25g1=plot(t1,'2',1) #plotting the curve 26 27l1=g1.activeLayer() 28curve1=t1Name+"_2" 29l1.addErrorBars(curve1,t1,'3') 30 31g1.confirmClose(False) 32t1.confirmClose(False) 33 34f1=GaussFit(l1,curve1) #Gauss fit 35f1.setInitialValues(11,49.1,11,1) #* 36f1.fit() 37print(f1.chiSquare()) 38#assert f1.chiSquare() < 1e-4,"f1.chiSquare() >=1e-4" 39assert f1.rSquare() > 0.99,"f1.rSquare() >= 0.99" 40 41 #* for some unknown reason, this fit does not work (or works randomly) without initial values when called from 42# a python script. It works fine when called from Analysis -> Quick Fit -> Fit Gaussian 43 44#non-linear fit (using a Gauss formula, of course) 45f2=NonLinearFit(l1,curve1) 46f2.setFormula("y0+A*sqrt(2/PI)/w*exp(-2*((x-xc)/w)^2)") 47f2.setParameters("A","xc","w","y0") 48f2.setInitialValues(11,49.1,11,1) 49f2.setYErrorSource(0) #** using 0 or Fit.UnknownErrors in the argument disable the use of error bar in the fit 50f2.setColor("blue") 51f2.fit() 52assert f2.chiSquare() < 1e-4 53assert f2.rSquare() > 0.99 54#** the non-linear fit is not converging with error bars when called from a python script. It looks to work 55# fine when called from Analysis -> Fit Wizard... 56 57app.exit() 58