Fitting data using several Gaussian distributions added together
Source code name: "fit_many_gaussians.py"
Programming language: Python
Topic: Data fitting/hfitter
DMelt Version 1. Last modified: 12/08/2015. License: Pro
https://datamelt.org/code/cache/fit_many_gaussians_5661.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 jhplot.io import *
from java.awt import Color
from java.util import Random
from jhplot.math.StatisticSample  import *

xmin=0
xmax=20
h1 = H1D('Data',100,xmin,xmax)
r= Random()

f=F1D('10+10*x',xmin,xmax)
p=f.getParse()
max=f.eval(xmax)

for i in range(10000):
  a=randomRejection(10,p,max,xmin,xmax)
  h1.fill(a)
  h1.fill(0.3*r.nextGaussian()+4)
  h1.fill(0.6*r.nextGaussian()+10)
  h1.fill(0.6*r.nextGaussian()+15)


c1 = HPlot('Canvas')
c1.setRange(0,20,0,4000)
c1.visible()
c1.draw(h1) 

f=HFitter()
f.setFunc('p1+g')
func=f.getFunc()
f.setPar('mean',4); f.setPar('amplitude',100)
print func.parameterNames()
f.setRange(0,7)
f.fit(h1)


ff=f.getFittedFunc()
r=f.getResult()
ff=f.getFittedFunc()
r=f.getResult()
fPars  = r.fittedParameters()


## next gaussiaon
f.setFunc('p1+g+g')
func=f.getFunc()
func.setParameters(fPars.tolist()+[500,10,0.5])
f.setRange(0,13)
f.fit(h1)
ff=f.getFittedFunc()
r=f.getResult()
fPars  = r.fittedParameters()
print func.parameterNames(), func.parameters()


# next gaussian 
f.setFunc('p1+g+g+g')
func=f.getFunc()
func.setParameters(fPars.tolist()+[500,15,0.5])
print func.parameterNames(), func.parameters()
f.setRange(0,20)
f.fit(h1)
ff=f.getFittedFunc()


# plot all 
f2 = F1D('Gaussians+background',ff,0,20)
f2.setPenWidth(1)
f2.setColor(Color.blue)
c1.draw(f2)


You see the box below because you did not login.