Non-linear fits using he Chi2 method with HFitter
Source code name: "fit_hfitter1.py"
Programming language: Python
Topic: Data fitting/hfitter
DMelt Version 1. Last modified: 12/08/2015. License: Free
https://datamelt.org/code/cache/fit_hfitter1_6913.py
To run this script using the DMelt IDE, copy the above URL link to the menu [File]→[Read script from URL] of the DMelt IDE.



from jhplot  import * 
from java.util import Random

'''
A comment

'''

f=HFitter()
print f.getFuncCatalog()
f.setFunc('g')
f.setPar('amplitude',50)

h1 = H1D('Data',50, -4, 4)
h1.setPenWidthErr(2)
h1.setStyle("p")
h1.setSymbol(4)
h1.setDrawLine(0)

r = Random()
for i in range(1000):
      h1.fill(r.nextGaussian())

c1 = HPlot('Canvas')
c1.visible()
c1.setAutoRange()
c1.draw(h1)

f.setRange(-4,4)
f.fit(h1)
ff=f.getFittedFunc()

# get fitted results
r=f.getResult()
Pars   = r.fittedParameters()
Errors = r.errors()
Names  = r.fittedParameterNames()
print "Fit results:"
for i in range(ff.numberOfParameters()):
  print Names[i]+" : "+str(Pars[i])+" +- "+str(Errors[i])


mess='χ^{2}/ndf='+str(round(r.quality()*r.ndf()))
mess=mess+" / "+str(r.ndf()) 
lab=HLabel(mess, 0.12, 0.69, 'NDC')
c1.add(lab) 


# draw function
f2 = F1D("Gaussian",ff,-4,4)
f2.setPenWidth(3)
c1.draw(f2)
print 'Quality=',r.quality(), ' NDF=',r.ndf()