
"""
<h1> Code example</h1>


In this example we generate a Gaussian distribution and fit it with
a Gaussian function.

$$
P(x) = \frac{1}{\sigma \sqrt {2\pi} } 
e^{(x - \mu)^2 /  2\sigma ^2} 
$$

Look at  the <a href="http://en.wikipedia.org/wiki/Gaussian_function">Wikipedia definition</a> 

"""
 
from java.awt import Color
from java.util import Random
from jhplot  import *


c1 = HPlot("Canvas",600,400,1, 1)
c1.setGTitle("Fit example"); #put title
c1.visible(1)
c1.setAutoRange()

min=-3.0
max=3.0
h1 = H1D("Simple1",50, min, max)
rand = Random()

# fill a histogram
for i in range(5000):
      h1.fill(rand.nextGaussian())

h1.setPenWidthErr(2)
h1.setStyle("p")
h1.setSymbol(4)
h1.setDrawLine(0)
c1.setNameX("Xaxis")
c1.setNameY("Yaxis");
c1.setName("Canvas title")
c1.drawStatBox(h1)

# create all factories
c1.factories();

# access  IAnalysisFactory
af = c1.analF()

# access  ITreeFactory
tf=c1.treeF()


# access  IFitFactory
fitf=c1.fitF()

# access IFunctionFactory
funcF=c1.funcF()


# make fit using JAIDA
fitter  = fitf.createFitter( "chi2", "jminuit" )
result = fitter.fit(h1.get(), "g" )
fresult=result.fittedFunction();             
fPars     = result.fittedParameters()
fParErrs  = result.errors()
fParNames = result.fittedParameterNames()
print "Fit results:"
for i in range(fresult.numberOfParameters()):
   print(fParNames[i]+" : "+str(fPars[i])+" +- "+str(fParErrs[i]))

# make F1D function from IFunction in the same range as histogram
f2 = F1D("Gaussian",fresult,min,max)
f2.setColor(Color.blue)
f2.setPenWidth(3);

# draw fit line
c1.draw(f2)
# draw histogram on top
c1.draw(h1)

# export to png
# c1.export(Editor.DocMasterName()+".png")
