from javax.swing import JFrame
from org.jlab.groot.data import H1F
from org.jlab.groot.fitter import DataFitter
from org.jlab.groot.graphics import *
from org.jlab.groot.math import *
from java.lang import Math


# define a function
class CustomFunction(Func1D):         # function describing a power law
    def evaluate(self, x):
           xsum = 0.0
           for i in range(self.getNPars()):
                xsum = xsum + self.getParameter(i)*Math.pow(x,i)
           return xsum 



frame = JFrame("Basic GROOT Demo")
canvas =EmbeddedCanvas()
frame.setSize(800,500)
histogram = H1F("histogram",100,-5.0,5.0) 
f1 = CustomFunction("CustomFunction", -5.1, 5.1)
f1.addParameter("p0")
f1.setParameter(0, 30.0)
f1.addParameter("p1")
f1.setParameter(1, -6.0)
f1.addParameter("p2")
f1.setParameter(2, 1.8)
f1.addParameter("p3")
f1.setParameter(3, .0001)

rndm = RandomFunc(f1)
for j in range(64000):
       histogram.fill(rndm.random())
histogram.setTitleX("Randomly Generated Function")
histogram.setTitleY("Counts")
canvas.getPad(0).setTitle("CustomFunction Example")
histogram.setLineWidth(2)
histogram.setLineColor(21)
histogram.setFillColor(34)
histogram.setOptStat(10)
		
f1.setLineColor(5)
f1.setLineWidth(7)
f1.setOptStat(111110)
		
DataFitter.fit(f1, histogram, "Q")
canvas.draw(histogram)
canvas.draw(f1,"same")
	
canvas.setFont("Avenir")  
canvas.setTitleSize(32)
canvas.setAxisTitleSize(24)
canvas.setAxisLabelSize(18)
canvas.setStatBoxFontSize(18)
frame.add(canvas)
frame.setLocationRelativeTo(None)
frame.setVisible(True)
